target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
assets/jqwidgets/demos/react/app/grid/cascadingcomboboxes/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
class App extends React.Component {
render() {
let data = '[{ "Country": "Belgium", "City": "Brussels"}, {"Country": "France", "City": "Paris"}, {"Country": "USA", "City": "Washington" }]';
let source =
{
datatype: 'json',
datafields: [
{ name: 'Country', type: 'string' },
{ name: 'City', type: 'string' }
],
localdata: data
};
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{
text: 'Country', datafield: 'Country', width: 150, columntype: 'combobox',
cellvaluechanging: (row, datafield, columntype, oldvalue, newvalue) => {
if (newvalue != oldvalue) {
this.refs.myGrid.setcellvalue(row, 'City', 'Select a city...');
};
}
},
{
text: 'City', datafield: 'City', width: 150, columntype: 'combobox',
initeditor: (row, cellvalue, editor, celltext, cellwidth, cellheight) => {
let country = this.refs.myGrid.getcellvalue(row, 'Country');
let city = editor.val();
let cities = new Array();
switch (country) {
case 'Belgium':
cities = ['Bruges', 'Brussels', 'Ghent'];
break;
case 'France':
cities = ['Bordeaux', 'Lille', 'Paris'];
break;
case 'USA':
cities = ['Los Angeles', 'Minneapolis', 'Washington'];
break;
};
editor.jqxComboBox({ autoDropDownHeight: true, source: cities });
if (city != 'Select a city...') {
let index = cities.indexOf(city);
editor.jqxComboBox('selectIndex', index);
}
}
}
];
return (
<JqxGrid ref='myGrid'
width={300} source={dataAdapter} selectionmode={'singlecell'}
autoheight={true} editable={true} columns={columns}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
gatsby-strapi-tutorial/cms/plugins/content-manager/admin/src/components/WysiwygDropUpload/index.js | strapi/strapi-examples | /**
*
* WysiwygDropUpload
*
*/
import React from 'react';
import styles from './styles.scss';
/* eslint-disable jsx-a11y/label-has-for */
const WysiwygDropUpload = (props) => {
return (
<label
{...props}
className={styles.wysiwygDropUpload}
>
<input
onChange={() => {}}
type="file"
tabIndex="-1"
/>
</label>
);
};
export default WysiwygDropUpload;
|
ajax/libs/angular-ui-select/0.19.8/select.js | tholu/cdnjs | /*!
* ui-select
* http://github.com/angular-ui/ui-select
* Version: 0.19.7 - 2017-04-15T14:28:36.649Z
* License: MIT
*/
(function () {
"use strict";
var KEY = {
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
BACKSPACE: 8,
DELETE: 46,
COMMAND: 91,
MAP: { 91 : "COMMAND", 8 : "BACKSPACE" , 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSEBREAK" , 20 : "CAPSLOCK" , 27 : "ESC" , 32 : "SPACE" , 33 : "PAGE_UP", 34 : "PAGE_DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT" , 38 : "UP" , 39 : "RIGHT" , 40 : "DOWN" , 43 : "+" , 44 : "PRINTSCREEN" , 45 : "INSERT" , 46 : "DELETE", 48 : "0" , 49 : "1" , 50 : "2" , 51 : "3" , 52 : "4" , 53 : "5" , 54 : "6" , 55 : "7" , 56 : "8" , 57 : "9" , 59 : ";", 61 : "=" , 65 : "A" , 66 : "B" , 67 : "C" , 68 : "D" , 69 : "E" , 70 : "F" , 71 : "G" , 72 : "H" , 73 : "I" , 74 : "J" , 75 : "K" , 76 : "L", 77 : "M" , 78 : "N" , 79 : "O" , 80 : "P" , 81 : "Q" , 82 : "R" , 83 : "S" , 84 : "T" , 85 : "U" , 86 : "V" , 87 : "W" , 88 : "X" , 89 : "Y" , 90 : "Z", 96 : "0" , 97 : "1" , 98 : "2" , 99 : "3" , 100 : "4" , 101 : "5" , 102 : "6" , 103 : "7" , 104 : "8" , 105 : "9", 106 : "*" , 107 : "+" , 109 : "-" , 110 : "." , 111 : "/", 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12", 144 : "NUMLOCK" , 145 : "SCROLLLOCK" , 186 : ";" , 187 : "=" , 188 : "," , 189 : "-" , 190 : "." , 191 : "/" , 192 : "`" , 219 : "[" , 220 : "\\" , 221 : "]" , 222 : "'"
},
isControl: function (e) {
var k = e.which;
switch (k) {
case KEY.COMMAND:
case KEY.SHIFT:
case KEY.CTRL:
case KEY.ALT:
return true;
}
if (e.metaKey || e.ctrlKey || e.altKey) return true;
return false;
},
isFunctionKey: function (k) {
k = k.which ? k.which : k;
return k >= 112 && k <= 123;
},
isVerticalMovement: function (k){
return ~[KEY.UP, KEY.DOWN].indexOf(k);
},
isHorizontalMovement: function (k){
return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k);
},
toSeparator: function (k) {
var sep = {ENTER:"\n",TAB:"\t",SPACE:" "}[k];
if (sep) return sep;
// return undefined for special keys other than enter, tab or space.
// no way to use them to cut strings.
return KEY[k] ? undefined : k;
}
};
function isNil(value) {
return angular.isUndefined(value) || value === null;
}
/**
* Add querySelectorAll() to jqLite.
*
* jqLite find() is limited to lookups by tag name.
* TODO This will change with future versions of AngularJS, to be removed when this happens
*
* See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586
* See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598
*/
if (angular.element.prototype.querySelectorAll === undefined) {
angular.element.prototype.querySelectorAll = function(selector) {
return angular.element(this[0].querySelectorAll(selector));
};
}
/**
* Add closest() to jqLite.
*/
if (angular.element.prototype.closest === undefined) {
angular.element.prototype.closest = function( selector) {
var elem = this[0];
var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
while (elem) {
if (matchesSelector.bind(elem)(selector)) {
return elem;
} else {
elem = elem.parentElement;
}
}
return false;
};
}
var latestId = 0;
var uis = angular.module('ui.select', [])
.constant('uiSelectConfig', {
theme: 'bootstrap',
searchEnabled: true,
sortable: false,
placeholder: '', // Empty by default, like HTML tag <select>
refreshDelay: 1000, // In milliseconds
closeOnSelect: true,
skipFocusser: false,
dropdownPosition: 'auto',
removeSelected: true,
resetSearchInput: true,
generateId: function() {
return latestId++;
},
appendToBody: false,
spinnerEnabled: false,
spinnerClass: 'glyphicon glyphicon-refresh ui-select-spin',
backspaceReset: true
})
// See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913
.service('uiSelectMinErr', function() {
var minErr = angular.$$minErr('ui.select');
return function() {
var error = minErr.apply(this, arguments);
var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), '');
return new Error(message);
};
})
// Recreates old behavior of ng-transclude. Used internally.
.directive('uisTranscludeAppend', function () {
return {
link: function (scope, element, attrs, ctrl, transclude) {
transclude(scope, function (clone) {
element.append(clone);
});
}
};
})
/**
* Highlights text that matches $select.search.
*
* Taken from AngularUI Bootstrap Typeahead
* See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340
*/
.filter('highlight', function() {
function escapeRegexp(queryToEscape) {
return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function(matchItem, query) {
return query && matchItem ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem;
};
})
/**
* A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/
*
* Taken from AngularUI Bootstrap Position:
* See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70
*/
.factory('uisOffset',
['$document', '$window',
function ($document, $window) {
return function(element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
};
};
}]);
/**
* Debounces functions
*
* Taken from UI Bootstrap $$debounce source code
* See https://github.com/angular-ui/bootstrap/blob/master/src/debounce/debounce.js
*
*/
uis.factory('$$uisDebounce', ['$timeout', function($timeout) {
return function(callback, debounceTime) {
var timeoutPromise;
return function() {
var self = this;
var args = Array.prototype.slice.call(arguments);
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
timeoutPromise = $timeout(function() {
callback.apply(self, args);
}, debounceTime);
};
};
}]);
uis.directive('uiSelectChoices',
['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', '$window',
function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile, $window) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Needed so the uiSelect can detect the transcluded content
tElement.addClass('ui-select-choices');
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
return theme + '/choices.tpl.html';
},
compile: function(tElement, tAttrs) {
if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression.");
// var repeat = RepeatParser.parse(attrs.repeat);
var groupByExp = tAttrs.groupBy;
var groupFilterExp = tAttrs.groupFilter;
if (groupByExp) {
var groups = tElement.querySelectorAll('.ui-select-choices-group');
if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length);
groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression());
}
var parserResult = RepeatParser.parse(tAttrs.repeat);
var choices = tElement.querySelectorAll('.ui-select-choices-row');
if (choices.length !== 1) {
throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length);
}
choices.attr('ng-repeat', parserResult.repeatExpression(groupByExp))
.attr('ng-if', '$select.open'); //Prevent unnecessary watches when dropdown is closed
var rowsInner = tElement.querySelectorAll('.ui-select-choices-row-inner');
if (rowsInner.length !== 1) {
throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length);
}
rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat
// If IE8 then need to target rowsInner to apply the ng-click attr as choices will not capture the event.
var clickTarget = $window.document.addEventListener ? choices : rowsInner;
clickTarget.attr('ng-click', '$select.select(' + parserResult.itemName + ',$select.skipFocusser,$event)');
return function link(scope, element, attrs, $select) {
$select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult
$select.disableChoiceExpression = attrs.uiDisableChoice;
$select.onHighlightCallback = attrs.onHighlight;
$select.minimumInputLength = parseInt(attrs.minimumInputLength) || 0;
$select.dropdownPosition = attrs.position ? attrs.position.toLowerCase() : uiSelectConfig.dropdownPosition;
scope.$watch('$select.search', function(newValue) {
if(newValue && !$select.open && $select.multiple) $select.activate(false, true);
$select.activeIndex = $select.tagging.isActivated ? -1 : 0;
if (!attrs.minimumInputLength || $select.search.length >= attrs.minimumInputLength) {
$select.refresh(attrs.refresh);
} else {
$select.items = [];
}
});
attrs.$observe('refreshDelay', function() {
// $eval() is needed otherwise we get a string instead of a number
var refreshDelay = scope.$eval(attrs.refreshDelay);
$select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay;
});
scope.$watch('$select.open', function(open) {
if (open) {
tElement.attr('role', 'listbox');
$select.refresh(attrs.refresh);
} else {
element.removeAttr('role');
}
});
};
}
};
}]);
/**
* Contains ui-select "intelligence".
*
* The goal is to limit dependency on the DOM whenever possible and
* put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
*/
uis.controller('uiSelectCtrl',
['$scope', '$element', '$timeout', '$filter', '$$uisDebounce', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window',
function($scope, $element, $timeout, $filter, $$uisDebounce, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) {
var ctrl = this;
var EMPTY_SEARCH = '';
ctrl.placeholder = uiSelectConfig.placeholder;
ctrl.searchEnabled = uiSelectConfig.searchEnabled;
ctrl.sortable = uiSelectConfig.sortable;
ctrl.refreshDelay = uiSelectConfig.refreshDelay;
ctrl.paste = uiSelectConfig.paste;
ctrl.resetSearchInput = uiSelectConfig.resetSearchInput;
ctrl.refreshing = false;
ctrl.spinnerEnabled = uiSelectConfig.spinnerEnabled;
ctrl.spinnerClass = uiSelectConfig.spinnerClass;
ctrl.removeSelected = uiSelectConfig.removeSelected; //If selected item(s) should be removed from dropdown list
ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function
ctrl.skipFocusser = false; //Set to true to avoid returning focus to ctrl when item is selected
ctrl.search = EMPTY_SEARCH;
ctrl.activeIndex = 0; //Dropdown of choices
ctrl.items = []; //All available choices
ctrl.open = false;
ctrl.focus = false;
ctrl.disabled = false;
ctrl.selected = undefined;
ctrl.dropdownPosition = 'auto';
ctrl.focusser = undefined; //Reference to input element used to handle focus events
ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
ctrl.tagging = {isActivated: false, fct: undefined};
ctrl.taggingTokens = {isActivated: false, tokens: undefined};
ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
ctrl.clickTriggeredSelect = false;
ctrl.$filter = $filter;
ctrl.$element = $element;
// Use $injector to check for $animate and store a reference to it
ctrl.$animate = (function () {
try {
return $injector.get('$animate');
} catch (err) {
// $animate does not exist
return null;
}
})();
ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
if (ctrl.searchInput.length !== 1) {
throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length);
}
ctrl.isEmpty = function() {
return isNil(ctrl.selected) || ctrl.selected === '' || (ctrl.multiple && ctrl.selected.length === 0);
};
function _findIndex(collection, predicate, thisArg){
if (collection.findIndex){
return collection.findIndex(predicate, thisArg);
} else {
var list = Object(collection);
var length = list.length >>> 0;
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
}
}
// Most of the time the user does not want to empty the search input when in typeahead mode
function _resetSearchInput() {
if (ctrl.resetSearchInput) {
ctrl.search = EMPTY_SEARCH;
//reset activeIndex
if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
ctrl.activeIndex = _findIndex(ctrl.items, function(item){
return angular.equals(this, item);
}, ctrl.selected);
}
}
}
function _groupsFilter(groups, groupNames) {
var i, j, result = [];
for(i = 0; i < groupNames.length ;i++){
for(j = 0; j < groups.length ;j++){
if(groups[j].name == [groupNames[i]]){
result.push(groups[j]);
}
}
}
return result;
}
// When the user clicks on ui-select, displays the dropdown list
ctrl.activate = function(initSearchValue, avoidReset) {
if (!ctrl.disabled && !ctrl.open) {
if(!avoidReset) _resetSearchInput();
$scope.$broadcast('uis:activate');
ctrl.open = true;
ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
// ensure that the index is set to zero for tagging variants
// that where first option is auto-selected
if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
ctrl.activeIndex = 0;
}
var container = $element.querySelectorAll('.ui-select-choices-content');
var searchInput = $element.querySelectorAll('.ui-select-search');
if (ctrl.$animate && ctrl.$animate.on && ctrl.$animate.enabled(container[0])) {
var animateHandler = function(elem, phase) {
if (phase === 'start' && ctrl.items.length === 0) {
// Only focus input after the animation has finished
ctrl.$animate.off('removeClass', searchInput[0], animateHandler);
$timeout(function () {
ctrl.focusSearchInput(initSearchValue);
});
} else if (phase === 'close') {
// Only focus input after the animation has finished
ctrl.$animate.off('enter', container[0], animateHandler);
$timeout(function () {
ctrl.focusSearchInput(initSearchValue);
});
}
};
if (ctrl.items.length > 0) {
ctrl.$animate.on('enter', container[0], animateHandler);
} else {
ctrl.$animate.on('removeClass', searchInput[0], animateHandler);
}
} else {
$timeout(function () {
ctrl.focusSearchInput(initSearchValue);
if(!ctrl.tagging.isActivated && ctrl.items.length > 1) {
_ensureHighlightVisible();
}
});
}
}
else if (ctrl.open && !ctrl.searchEnabled) {
// Close the selection if we don't have search enabled, and we click on the select again
ctrl.close();
}
};
ctrl.focusSearchInput = function (initSearchValue) {
ctrl.search = initSearchValue || ctrl.search;
ctrl.searchInput[0].focus();
};
ctrl.findGroupByName = function(name) {
return ctrl.groups && ctrl.groups.filter(function(group) {
return group.name === name;
})[0];
};
ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) {
function updateGroups(items) {
var groupFn = $scope.$eval(groupByExp);
ctrl.groups = [];
angular.forEach(items, function(item) {
var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
var group = ctrl.findGroupByName(groupName);
if(group) {
group.items.push(item);
}
else {
ctrl.groups.push({name: groupName, items: [item]});
}
});
if(groupFilterExp){
var groupFilterFn = $scope.$eval(groupFilterExp);
if( angular.isFunction(groupFilterFn)){
ctrl.groups = groupFilterFn(ctrl.groups);
} else if(angular.isArray(groupFilterFn)){
ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn);
}
}
ctrl.items = [];
ctrl.groups.forEach(function(group) {
ctrl.items = ctrl.items.concat(group.items);
});
}
function setPlainItems(items) {
ctrl.items = items || [];
}
ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems;
ctrl.parserResult = RepeatParser.parse(repeatAttr);
ctrl.isGrouped = !!groupByExp;
ctrl.itemProperty = ctrl.parserResult.itemName;
//If collection is an Object, convert it to Array
var originalSource = ctrl.parserResult.source;
//When an object is used as source, we better create an array and use it as 'source'
var createArrayFromObject = function(){
var origSrc = originalSource($scope);
$scope.$uisSource = Object.keys(origSrc).map(function(v){
var result = {};
result[ctrl.parserResult.keyName] = v;
result.value = origSrc[v];
return result;
});
};
if (ctrl.parserResult.keyName){ // Check for (key,value) syntax
createArrayFromObject();
ctrl.parserResult.source = $parse('$uisSource' + ctrl.parserResult.filters);
$scope.$watch(originalSource, function(newVal, oldVal){
if (newVal !== oldVal) createArrayFromObject();
}, true);
}
ctrl.refreshItems = function (data){
data = data || ctrl.parserResult.source($scope);
var selectedItems = ctrl.selected;
//TODO should implement for single mode removeSelected
if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.multiple || !ctrl.removeSelected) {
ctrl.setItemsFn(data);
}else{
if ( data !== undefined && data !== null ) {
var filteredItems = data.filter(function(i) {
return angular.isArray(selectedItems) ? selectedItems.every(function(selectedItem) {
return !angular.equals(i, selectedItem);
}) : !angular.equals(i, selectedItems);
});
ctrl.setItemsFn(filteredItems);
}
}
if (ctrl.dropdownPosition === 'auto' || ctrl.dropdownPosition === 'up'){
$scope.calculateDropdownPos();
}
$scope.$broadcast('uis:refresh');
};
// See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
$scope.$watchCollection(ctrl.parserResult.source, function(items) {
if (items === undefined || items === null) {
// If the user specifies undefined or null => reset the collection
// Special case: items can be undefined if the user did not initialized the collection on the scope
// i.e $scope.addresses = [] is missing
ctrl.items = [];
} else {
if (!angular.isArray(items)) {
throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
} else {
//Remove already selected items (ex: while searching)
//TODO Should add a test
ctrl.refreshItems(items);
//update the view value with fresh data from items, if there is a valid model value
if(angular.isDefined(ctrl.ngModel.$modelValue)) {
ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
}
}
}
});
};
var _refreshDelayPromise;
/**
* Typeahead mode: lets the user refresh the collection using his own function.
*
* See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
*/
ctrl.refresh = function(refreshAttr) {
if (refreshAttr !== undefined) {
// Debounce
// See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
// FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
if (_refreshDelayPromise) {
$timeout.cancel(_refreshDelayPromise);
}
_refreshDelayPromise = $timeout(function() {
if ($scope.$select.search.length >= $scope.$select.minimumInputLength) {
var refreshPromise = $scope.$eval(refreshAttr);
if (refreshPromise && angular.isFunction(refreshPromise.then) && !ctrl.refreshing) {
ctrl.refreshing = true;
refreshPromise.finally(function() {
ctrl.refreshing = false;
});
}
}
}, ctrl.refreshDelay);
}
};
ctrl.isActive = function(itemScope) {
if ( !ctrl.open ) {
return false;
}
var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
var isActive = itemIndex == ctrl.activeIndex;
if ( !isActive || itemIndex < 0 ) {
return false;
}
if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
itemScope.$eval(ctrl.onHighlightCallback);
}
return isActive;
};
var _isItemSelected = function (item) {
return (ctrl.selected && angular.isArray(ctrl.selected) &&
ctrl.selected.filter(function (selection) { return angular.equals(selection, item); }).length > 0);
};
var disabledItems = [];
function _updateItemDisabled(item, isDisabled) {
var disabledItemIndex = disabledItems.indexOf(item);
if (isDisabled && disabledItemIndex === -1) {
disabledItems.push(item);
}
if (!isDisabled && disabledItemIndex > -1) {
disabledItems.splice(disabledItemIndex, 1);
}
}
function _isItemDisabled(item) {
return disabledItems.indexOf(item) > -1;
}
ctrl.isDisabled = function(itemScope) {
if (!ctrl.open) return;
var item = itemScope[ctrl.itemProperty];
var itemIndex = ctrl.items.indexOf(item);
var isDisabled = false;
if (itemIndex >= 0 && (angular.isDefined(ctrl.disableChoiceExpression) || ctrl.multiple)) {
if (item.isTag) return false;
if (ctrl.multiple) {
isDisabled = _isItemSelected(item);
}
if (!isDisabled && angular.isDefined(ctrl.disableChoiceExpression)) {
isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression));
}
_updateItemDisabled(item, isDisabled);
}
return isDisabled;
};
// When the user selects an item with ENTER or clicks the dropdown
ctrl.select = function(item, skipFocusser, $event) {
if (isNil(item) || !_isItemDisabled(item)) {
if ( ! ctrl.items && ! ctrl.search && ! ctrl.tagging.isActivated) return;
if (!item || !_isItemDisabled(item)) {
// if click is made on existing item, prevent from tagging, ctrl.search does not matter
ctrl.clickTriggeredSelect = false;
if($event && ($event.type === 'click' || $event.type === 'touchend') && item)
ctrl.clickTriggeredSelect = true;
if(ctrl.tagging.isActivated && ctrl.clickTriggeredSelect === false) {
// if taggingLabel is disabled and item is undefined we pull from ctrl.search
if ( ctrl.taggingLabel === false ) {
if ( ctrl.activeIndex < 0 ) {
if (item === undefined) {
item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search;
}
if (!item || angular.equals( ctrl.items[0], item ) ) {
return;
}
} else {
// keyboard nav happened first, user selected from dropdown
item = ctrl.items[ctrl.activeIndex];
}
} else {
// tagging always operates at index zero, taggingLabel === false pushes
// the ctrl.search value without having it injected
if ( ctrl.activeIndex === 0 ) {
// ctrl.tagging pushes items to ctrl.items, so we only have empty val
// for `item` if it is a detected duplicate
if ( item === undefined ) return;
// create new item on the fly if we don't already have one;
// use tagging function if we have one
if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
item = ctrl.tagging.fct(item);
if (!item) return;
// if item type is 'string', apply the tagging label
} else if ( typeof item === 'string' ) {
// trim the trailing space
item = item.replace(ctrl.taggingLabel,'').trim();
}
}
}
// search ctrl.selected for dupes potentially caused by tagging and return early if found
if (_isItemSelected(item)) {
ctrl.close(skipFocusser);
return;
}
}
_resetSearchInput();
$scope.$broadcast('uis:select', item);
if (ctrl.closeOnSelect) {
ctrl.close(skipFocusser);
}
}
}
};
// Closes the dropdown
ctrl.close = function(skipFocusser) {
if (!ctrl.open) return;
if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
ctrl.open = false;
_resetSearchInput();
$scope.$broadcast('uis:close', skipFocusser);
};
ctrl.setFocus = function(){
if (!ctrl.focus) ctrl.focusInput[0].focus();
};
ctrl.clear = function($event) {
ctrl.select(null);
$event.stopPropagation();
$timeout(function() {
ctrl.focusser[0].focus();
}, 0, false);
};
// Toggle dropdown
ctrl.toggle = function(e) {
if (ctrl.open) {
ctrl.close();
e.preventDefault();
e.stopPropagation();
} else {
ctrl.activate();
}
};
// Set default function for locked choices - avoids unnecessary
// logic if functionality is not being used
ctrl.isLocked = function () {
return false;
};
$scope.$watch(function () {
return angular.isDefined(ctrl.lockChoiceExpression) && ctrl.lockChoiceExpression !== "";
}, _initaliseLockedChoices);
function _initaliseLockedChoices(doInitalise) {
if(!doInitalise) return;
var lockedItems = [];
function _updateItemLocked(item, isLocked) {
var lockedItemIndex = lockedItems.indexOf(item);
if (isLocked && lockedItemIndex === -1) {
lockedItems.push(item);
}
if (!isLocked && lockedItemIndex > -1) {
lockedItems.splice(lockedItemIndex, 1);
}
}
function _isItemlocked(item) {
return lockedItems.indexOf(item) > -1;
}
ctrl.isLocked = function (itemScope, itemIndex) {
var isLocked = false,
item = ctrl.selected[itemIndex];
if(item) {
if (itemScope) {
isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression));
_updateItemLocked(item, isLocked);
} else {
isLocked = _isItemlocked(item);
}
}
return isLocked;
};
}
var sizeWatch = null;
var updaterScheduled = false;
ctrl.sizeSearchInput = function() {
var input = ctrl.searchInput[0],
container = ctrl.$element[0],
calculateContainerWidth = function() {
// Return the container width only if the search input is visible
return container.clientWidth * !!input.offsetParent;
},
updateIfVisible = function(containerWidth) {
if (containerWidth === 0) {
return false;
}
var inputWidth = containerWidth - input.offsetLeft;
if (inputWidth < 50) inputWidth = containerWidth;
ctrl.searchInput.css('width', inputWidth+'px');
return true;
};
ctrl.searchInput.css('width', '10px');
$timeout(function() { //Give tags time to render correctly
if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) {
sizeWatch = $scope.$watch(function() {
if (!updaterScheduled) {
updaterScheduled = true;
$scope.$$postDigest(function() {
updaterScheduled = false;
if (updateIfVisible(calculateContainerWidth())) {
sizeWatch();
sizeWatch = null;
}
});
}
}, angular.noop);
}
});
};
function _handleDropDownSelection(key) {
var processed = true;
switch (key) {
case KEY.DOWN:
if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
else if (ctrl.activeIndex < ctrl.items.length - 1) {
var idx = ++ctrl.activeIndex;
while(_isItemDisabled(ctrl.items[idx]) && idx < ctrl.items.length) {
ctrl.activeIndex = ++idx;
}
}
break;
case KEY.UP:
var minActiveIndex = (ctrl.search.length === 0 && ctrl.tagging.isActivated) ? -1 : 0;
if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
else if (ctrl.activeIndex > minActiveIndex) {
var idxmin = --ctrl.activeIndex;
while(_isItemDisabled(ctrl.items[idxmin]) && idxmin > minActiveIndex) {
ctrl.activeIndex = --idxmin;
}
}
break;
case KEY.TAB:
if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true);
break;
case KEY.ENTER:
if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){
ctrl.select(ctrl.items[ctrl.activeIndex], ctrl.skipFocusser); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode
} else {
ctrl.activate(false, true); //In case its the search input in 'multiple' mode
}
break;
case KEY.ESC:
ctrl.close();
break;
default:
processed = false;
}
return processed;
}
// Bind to keyboard shortcuts
ctrl.searchInput.on('keydown', function(e) {
var key = e.which;
if (~[KEY.ENTER,KEY.ESC].indexOf(key)){
e.preventDefault();
e.stopPropagation();
}
$scope.$apply(function() {
var tagged = false;
if (ctrl.items.length > 0 || ctrl.tagging.isActivated) {
if(!_handleDropDownSelection(key) && !ctrl.searchEnabled) {
e.preventDefault();
e.stopPropagation();
}
if ( ctrl.taggingTokens.isActivated ) {
for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
// make sure there is a new value to push via tagging
if ( ctrl.search.length > 0 ) {
tagged = true;
}
}
}
if ( tagged ) {
$timeout(function() {
ctrl.searchInput.triggerHandler('tagged');
var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim();
if ( ctrl.tagging.fct ) {
newItem = ctrl.tagging.fct( newItem );
}
if (newItem) ctrl.select(newItem, true);
});
}
}
}
});
if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
_ensureHighlightVisible();
}
if (key === KEY.ENTER || key === KEY.ESC) {
e.preventDefault();
e.stopPropagation();
}
});
ctrl.searchInput.on('paste', function (e) {
var data;
if (window.clipboardData && window.clipboardData.getData) { // IE
data = window.clipboardData.getData('Text');
} else {
data = (e.originalEvent || e).clipboardData.getData('text/plain');
}
// Prepend the current input field text to the paste buffer.
data = ctrl.search + data;
if (data && data.length > 0) {
// If tagging try to split by tokens and add items
if (ctrl.taggingTokens.isActivated) {
var items = [];
for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) { // split by first token that is contained in data
var separator = KEY.toSeparator(ctrl.taggingTokens.tokens[i]) || ctrl.taggingTokens.tokens[i];
if (data.indexOf(separator) > -1) {
items = data.split(separator);
break; // only split by one token
}
}
if (items.length === 0) {
items = [data];
}
var oldsearch = ctrl.search;
angular.forEach(items, function (item) {
var newItem = ctrl.tagging.fct ? ctrl.tagging.fct(item) : item;
if (newItem) {
ctrl.select(newItem, true);
}
});
ctrl.search = oldsearch || EMPTY_SEARCH;
e.preventDefault();
e.stopPropagation();
} else if (ctrl.paste) {
ctrl.paste(data);
ctrl.search = EMPTY_SEARCH;
e.preventDefault();
e.stopPropagation();
}
}
});
ctrl.searchInput.on('tagged', function() {
$timeout(function() {
_resetSearchInput();
});
});
// See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
function _ensureHighlightVisible() {
var container = $element.querySelectorAll('.ui-select-choices-content');
var choices = container.querySelectorAll('.ui-select-choices-row');
if (choices.length < 1) {
throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
}
if (ctrl.activeIndex < 0) {
return;
}
var highlighted = choices[ctrl.activeIndex];
var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
var height = container[0].offsetHeight;
if (posY > height) {
container[0].scrollTop += posY - height;
} else if (posY < highlighted.clientHeight) {
if (ctrl.isGrouped && ctrl.activeIndex === 0)
container[0].scrollTop = 0; //To make group header visible when going all the way up
else
container[0].scrollTop -= highlighted.clientHeight - posY;
}
}
var onResize = $$uisDebounce(function() {
ctrl.sizeSearchInput();
}, 50);
angular.element($window).bind('resize', onResize);
$scope.$on('$destroy', function() {
ctrl.searchInput.off('keyup keydown tagged blur paste');
angular.element($window).off('resize', onResize);
});
$scope.$watch('$select.activeIndex', function(activeIndex) {
if (activeIndex)
$element.find('input').attr(
'aria-activedescendant',
'ui-select-choices-row-' + ctrl.generatedId + '-' + activeIndex);
});
$scope.$watch('$select.open', function(open) {
if (!open)
$element.find('input').removeAttr('aria-activedescendant');
});
}]);
uis.directive('uiSelect',
['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout',
function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) {
return {
restrict: 'EA',
templateUrl: function(tElement, tAttrs) {
var theme = tAttrs.theme || uiSelectConfig.theme;
return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html');
},
replace: true,
transclude: true,
require: ['uiSelect', '^ngModel'],
scope: true,
controller: 'uiSelectCtrl',
controllerAs: '$select',
compile: function(tElement, tAttrs) {
// Allow setting ngClass on uiSelect
var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass);
if(match) {
var combined = '{'+ match[1] +', '+ match[2] +'}';
tAttrs.ngClass = combined;
tElement.attr('ng-class', combined);
}
//Multiple or Single depending if multiple attribute presence
if (angular.isDefined(tAttrs.multiple))
tElement.append('<ui-select-multiple/>').removeAttr('multiple');
else
tElement.append('<ui-select-single/>');
if (tAttrs.inputId)
tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId;
return function(scope, element, attrs, ctrls, transcludeFn) {
var $select = ctrls[0];
var ngModel = ctrls[1];
$select.generatedId = uiSelectConfig.generateId();
$select.baseTitle = attrs.title || 'Select box';
$select.focusserTitle = $select.baseTitle + ' focus';
$select.focusserId = 'focusser-' + $select.generatedId;
$select.closeOnSelect = function() {
if (angular.isDefined(attrs.closeOnSelect)) {
return $parse(attrs.closeOnSelect)();
} else {
return uiSelectConfig.closeOnSelect;
}
}();
scope.$watch('skipFocusser', function() {
var skipFocusser = scope.$eval(attrs.skipFocusser);
$select.skipFocusser = skipFocusser !== undefined ? skipFocusser : uiSelectConfig.skipFocusser;
});
$select.onSelectCallback = $parse(attrs.onSelect);
$select.onRemoveCallback = $parse(attrs.onRemove);
//Set reference to ngModel from uiSelectCtrl
$select.ngModel = ngModel;
$select.choiceGrouped = function(group){
return $select.isGrouped && group && group.name;
};
if(attrs.tabindex){
attrs.$observe('tabindex', function(value) {
$select.focusInput.attr('tabindex', value);
element.removeAttr('tabindex');
});
}
scope.$watch(function () { return scope.$eval(attrs.searchEnabled); }, function(newVal) {
$select.searchEnabled = newVal !== undefined ? newVal : uiSelectConfig.searchEnabled;
});
scope.$watch('sortable', function() {
var sortable = scope.$eval(attrs.sortable);
$select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable;
});
attrs.$observe('backspaceReset', function() {
// $eval() is needed otherwise we get a string instead of a boolean
var backspaceReset = scope.$eval(attrs.backspaceReset);
$select.backspaceReset = backspaceReset !== undefined ? backspaceReset : true;
});
attrs.$observe('limit', function() {
//Limit the number of selections allowed
$select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined;
});
scope.$watch('removeSelected', function() {
var removeSelected = scope.$eval(attrs.removeSelected);
$select.removeSelected = removeSelected !== undefined ? removeSelected : uiSelectConfig.removeSelected;
});
attrs.$observe('disabled', function() {
// No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string
$select.disabled = attrs.disabled !== undefined ? attrs.disabled : false;
});
attrs.$observe('resetSearchInput', function() {
// $eval() is needed otherwise we get a string instead of a boolean
var resetSearchInput = scope.$eval(attrs.resetSearchInput);
$select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true;
});
attrs.$observe('paste', function() {
$select.paste = scope.$eval(attrs.paste);
});
attrs.$observe('tagging', function() {
if(attrs.tagging !== undefined)
{
// $eval() is needed otherwise we get a string instead of a boolean
var taggingEval = scope.$eval(attrs.tagging);
$select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined};
}
else
{
$select.tagging = {isActivated: false, fct: undefined};
}
});
attrs.$observe('taggingLabel', function() {
if(attrs.tagging !== undefined )
{
// check eval for FALSE, in this case, we disable the labels
// associated with tagging
if ( attrs.taggingLabel === 'false' ) {
$select.taggingLabel = false;
}
else
{
$select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)';
}
}
});
attrs.$observe('taggingTokens', function() {
if (attrs.tagging !== undefined) {
var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER'];
$select.taggingTokens = {isActivated: true, tokens: tokens };
}
});
attrs.$observe('spinnerEnabled', function() {
// $eval() is needed otherwise we get a string instead of a boolean
var spinnerEnabled = scope.$eval(attrs.spinnerEnabled);
$select.spinnerEnabled = spinnerEnabled !== undefined ? spinnerEnabled : uiSelectConfig.spinnerEnabled;
});
attrs.$observe('spinnerClass', function() {
var spinnerClass = attrs.spinnerClass;
$select.spinnerClass = spinnerClass !== undefined ? attrs.spinnerClass : uiSelectConfig.spinnerClass;
});
//Automatically gets focus when loaded
if (angular.isDefined(attrs.autofocus)){
$timeout(function(){
$select.setFocus();
});
}
//Gets focus based on scope event name (e.g. focus-on='SomeEventName')
if (angular.isDefined(attrs.focusOn)){
scope.$on(attrs.focusOn, function() {
$timeout(function(){
$select.setFocus();
});
});
}
function onDocumentClick(e) {
if (!$select.open) return; //Skip it if dropdown is close
var contains = false;
if (window.jQuery) {
// Firefox 3.6 does not support element.contains()
// See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
contains = window.jQuery.contains(element[0], e.target);
} else {
contains = element[0].contains(e.target);
}
if (!contains && !$select.clickTriggeredSelect) {
var skipFocusser;
if (!$select.skipFocusser) {
//Will lose focus only with certain targets
var focusableControls = ['input','button','textarea','select'];
var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select
skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select
if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea
} else {
skipFocusser = true;
}
$select.close(skipFocusser);
scope.$digest();
}
$select.clickTriggeredSelect = false;
}
// See Click everywhere but here event http://stackoverflow.com/questions/12931369
$document.on('click', onDocumentClick);
scope.$on('$destroy', function() {
$document.off('click', onDocumentClick);
});
// Move transcluded elements to their correct position in main template
transcludeFn(scope, function(clone) {
// See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html
// One day jqLite will be replaced by jQuery and we will be able to write:
// var transcludedElement = clone.filter('.my-class')
// instead of creating a hackish DOM element:
var transcluded = angular.element('<div>').append(clone);
var transcludedMatch = transcluded.querySelectorAll('.ui-select-match');
transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr
transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes
if (transcludedMatch.length !== 1) {
throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length);
}
element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch);
var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices');
transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr
transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes
if (transcludedChoices.length !== 1) {
throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length);
}
element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices);
var transcludedNoChoice = transcluded.querySelectorAll('.ui-select-no-choice');
transcludedNoChoice.removeAttr('ui-select-no-choice'); //To avoid loop in case directive as attr
transcludedNoChoice.removeAttr('data-ui-select-no-choice'); // Properly handle HTML5 data-attributes
if (transcludedNoChoice.length == 1) {
element.querySelectorAll('.ui-select-no-choice').replaceWith(transcludedNoChoice);
}
});
// Support for appending the select field to the body when its open
var appendToBody = scope.$eval(attrs.appendToBody);
if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) {
scope.$watch('$select.open', function(isOpen) {
if (isOpen) {
positionDropdown();
} else {
resetDropdown();
}
});
// Move the dropdown back to its original location when the scope is destroyed. Otherwise
// it might stick around when the user routes away or the select field is otherwise removed
scope.$on('$destroy', function() {
resetDropdown();
});
}
// Hold on to a reference to the .ui-select-container element for appendToBody support
var placeholder = null,
originalWidth = '';
function positionDropdown() {
// Remember the absolute position of the element
var offset = uisOffset(element);
// Clone the element into a placeholder element to take its original place in the DOM
placeholder = angular.element('<div class="ui-select-placeholder"></div>');
placeholder[0].style.width = offset.width + 'px';
placeholder[0].style.height = offset.height + 'px';
element.after(placeholder);
// Remember the original value of the element width inline style, so it can be restored
// when the dropdown is closed
originalWidth = element[0].style.width;
// Now move the actual dropdown element to the end of the body
$document.find('body').append(element);
element[0].style.position = 'absolute';
element[0].style.left = offset.left + 'px';
element[0].style.top = offset.top + 'px';
element[0].style.width = offset.width + 'px';
}
function resetDropdown() {
if (placeholder === null) {
// The dropdown has not actually been display yet, so there's nothing to reset
return;
}
// Move the dropdown element back to its original location in the DOM
placeholder.replaceWith(element);
placeholder = null;
element[0].style.position = '';
element[0].style.left = '';
element[0].style.top = '';
element[0].style.width = originalWidth;
// Set focus back on to the moved element
$select.setFocus();
}
// Hold on to a reference to the .ui-select-dropdown element for direction support.
var dropdown = null,
directionUpClassName = 'direction-up';
// Support changing the direction of the dropdown if there isn't enough space to render it.
scope.$watch('$select.open', function() {
if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){
scope.calculateDropdownPos();
}
});
var setDropdownPosUp = function(offset, offsetDropdown){
offset = offset || uisOffset(element);
offsetDropdown = offsetDropdown || uisOffset(dropdown);
dropdown[0].style.position = 'absolute';
dropdown[0].style.top = (offsetDropdown.height * -1) + 'px';
element.addClass(directionUpClassName);
};
var setDropdownPosDown = function(offset, offsetDropdown){
element.removeClass(directionUpClassName);
offset = offset || uisOffset(element);
offsetDropdown = offsetDropdown || uisOffset(dropdown);
dropdown[0].style.position = '';
dropdown[0].style.top = '';
};
var calculateDropdownPosAfterAnimation = function() {
// Delay positioning the dropdown until all choices have been added so its height is correct.
$timeout(function() {
if ($select.dropdownPosition === 'up') {
//Go UP
setDropdownPosUp();
} else {
//AUTO
element.removeClass(directionUpClassName);
var offset = uisOffset(element);
var offsetDropdown = uisOffset(dropdown);
//https://code.google.com/p/chromium/issues/detail?id=342307#c4
var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox).
// Determine if the direction of the dropdown needs to be changed.
if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) {
//Go UP
setDropdownPosUp(offset, offsetDropdown);
}else{
//Go DOWN
setDropdownPosDown(offset, offsetDropdown);
}
}
// Display the dropdown once it has been positioned.
dropdown[0].style.opacity = 1;
});
};
var opened = false;
scope.calculateDropdownPos = function() {
if ($select.open) {
dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown');
if (dropdown.length === 0) {
return;
}
// Hide the dropdown so there is no flicker until $timeout is done executing.
if ($select.search === '' && !opened) {
dropdown[0].style.opacity = 0;
opened = true;
}
if (!uisOffset(dropdown).height && $select.$animate && $select.$animate.on && $select.$animate.enabled(dropdown)) {
var needsCalculated = true;
$select.$animate.on('enter', dropdown, function (elem, phase) {
if (phase === 'close' && needsCalculated) {
calculateDropdownPosAfterAnimation();
needsCalculated = false;
}
});
} else {
calculateDropdownPosAfterAnimation();
}
} else {
if (dropdown === null || dropdown.length === 0) {
return;
}
// Reset the position of the dropdown.
dropdown[0].style.opacity = 0;
dropdown[0].style.position = '';
dropdown[0].style.top = '';
element.removeClass(directionUpClassName);
}
};
};
}
};
}]);
uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Needed so the uiSelect can detect the transcluded content
tElement.addClass('ui-select-match');
var parent = tElement.parent();
// Gets theme attribute from parent (ui-select)
var theme = getAttribute(parent, 'theme') || uiSelectConfig.theme;
var multi = angular.isDefined(getAttribute(parent, 'multiple'));
return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
},
link: function(scope, element, attrs, $select) {
$select.lockChoiceExpression = attrs.uiLockChoice;
attrs.$observe('placeholder', function(placeholder) {
$select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
});
function setAllowClear(allow) {
$select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
}
attrs.$observe('allowClear', setAllowClear);
setAllowClear(attrs.allowClear);
if($select.multiple){
$select.sizeSearchInput();
}
}
};
function getAttribute(elem, attribute) {
if (elem[0].hasAttribute(attribute))
return elem.attr(attribute);
if (elem[0].hasAttribute('data-' + attribute))
return elem.attr('data-' + attribute);
if (elem[0].hasAttribute('x-' + attribute))
return elem.attr('x-' + attribute);
}
}]);
uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) {
return {
restrict: 'EA',
require: ['^uiSelect', '^ngModel'],
controller: ['$scope','$timeout', function($scope, $timeout){
var ctrl = this,
$select = $scope.$select,
ngModel;
if (angular.isUndefined($select.selected))
$select.selected = [];
//Wait for link fn to inject it
$scope.$evalAsync(function(){ ngModel = $scope.ngModel; });
ctrl.activeMatchIndex = -1;
ctrl.updateModel = function(){
ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes
ctrl.refreshComponent();
};
ctrl.refreshComponent = function(){
//Remove already selected items
//e.g. When user clicks on a selection, the selected array changes and
//the dropdown should remove that item
if($select.refreshItems){
$select.refreshItems();
}
if($select.sizeSearchInput){
$select.sizeSearchInput();
}
};
// Remove item from multiple select
ctrl.removeChoice = function(index){
// if the choice is locked, don't remove it
if($select.isLocked(null, index)) return false;
var removedChoice = $select.selected[index];
var locals = {};
locals[$select.parserResult.itemName] = removedChoice;
$select.selected.splice(index, 1);
ctrl.activeMatchIndex = -1;
$select.sizeSearchInput();
// Give some time for scope propagation.
$timeout(function(){
$select.onRemoveCallback($scope, {
$item: removedChoice,
$model: $select.parserResult.modelMapper($scope, locals)
});
});
ctrl.updateModel();
return true;
};
ctrl.getPlaceholder = function(){
//Refactor single?
if($select.selected && $select.selected.length) return;
return $select.placeholder;
};
}],
controllerAs: '$selectMultiple',
link: function(scope, element, attrs, ctrls) {
var $select = ctrls[0];
var ngModel = scope.ngModel = ctrls[1];
var $selectMultiple = scope.$selectMultiple;
//$select.selected = raw selected objects (ignoring any property binding)
$select.multiple = true;
//Input that will handle focus
$select.focusInput = $select.searchInput;
//Properly check for empty if set to multiple
ngModel.$isEmpty = function(value) {
return !value || value.length === 0;
};
//From view --> model
ngModel.$parsers.unshift(function () {
var locals = {},
result,
resultMultiple = [];
for (var j = $select.selected.length - 1; j >= 0; j--) {
locals = {};
locals[$select.parserResult.itemName] = $select.selected[j];
result = $select.parserResult.modelMapper(scope, locals);
resultMultiple.unshift(result);
}
return resultMultiple;
});
// From model --> view
ngModel.$formatters.unshift(function (inputValue) {
var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
locals = {},
result;
if (!data) return inputValue;
var resultMultiple = [];
var checkFnMultiple = function(list, value){
if (!list || !list.length) return;
for (var p = list.length - 1; p >= 0; p--) {
locals[$select.parserResult.itemName] = list[p];
result = $select.parserResult.modelMapper(scope, locals);
if($select.parserResult.trackByExp){
var propsItemNameMatches = /(\w*)\./.exec($select.parserResult.trackByExp);
var matches = /\.([^\s]+)/.exec($select.parserResult.trackByExp);
if(propsItemNameMatches && propsItemNameMatches.length > 0 && propsItemNameMatches[1] == $select.parserResult.itemName){
if(matches && matches.length>0 && result[matches[1]] == value[matches[1]]){
resultMultiple.unshift(list[p]);
return true;
}
}
}
if (angular.equals(result,value)){
resultMultiple.unshift(list[p]);
return true;
}
}
return false;
};
if (!inputValue) return resultMultiple; //If ngModel was undefined
for (var k = inputValue.length - 1; k >= 0; k--) {
//Check model array of currently selected items
if (!checkFnMultiple($select.selected, inputValue[k])){
//Check model array of all items available
if (!checkFnMultiple(data, inputValue[k])){
//If not found on previous lists, just add it directly to resultMultiple
resultMultiple.unshift(inputValue[k]);
}
}
}
return resultMultiple;
});
//Watch for external model changes
scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) {
if (oldValue != newValue){
//update the view value with fresh data from items, if there is a valid model value
if(angular.isDefined(ngModel.$modelValue)) {
ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
}
$selectMultiple.refreshComponent();
}
});
ngModel.$render = function() {
// Make sure that model value is array
if(!angular.isArray(ngModel.$viewValue)){
// Have tolerance for null or undefined values
if (isNil(ngModel.$viewValue)){
ngModel.$viewValue = [];
} else {
throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue);
}
}
$select.selected = ngModel.$viewValue;
$selectMultiple.refreshComponent();
scope.$evalAsync(); //To force $digest
};
scope.$on('uis:select', function (event, item) {
if($select.selected.length >= $select.limit) {
return;
}
$select.selected.push(item);
var locals = {};
locals[$select.parserResult.itemName] = item;
$timeout(function(){
$select.onSelectCallback(scope, {
$item: item,
$model: $select.parserResult.modelMapper(scope, locals)
});
});
$selectMultiple.updateModel();
});
scope.$on('uis:activate', function () {
$selectMultiple.activeMatchIndex = -1;
});
scope.$watch('$select.disabled', function(newValue, oldValue) {
// As the search input field may now become visible, it may be necessary to recompute its size
if (oldValue && !newValue) $select.sizeSearchInput();
});
$select.searchInput.on('keydown', function(e) {
var key = e.which;
scope.$apply(function() {
var processed = false;
// var tagged = false; //Checkme
if(KEY.isHorizontalMovement(key)){
processed = _handleMatchSelection(key);
}
if (processed && key != KEY.TAB) {
//TODO Check si el tab selecciona aun correctamente
//Crear test
e.preventDefault();
e.stopPropagation();
}
});
});
function _getCaretPosition(el) {
if(angular.isNumber(el.selectionStart)) return el.selectionStart;
// selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
else return el.value.length;
}
// Handles selected options in "multiple" mode
function _handleMatchSelection(key){
var caretPosition = _getCaretPosition($select.searchInput[0]),
length = $select.selected.length,
// none = -1,
first = 0,
last = length-1,
curr = $selectMultiple.activeMatchIndex,
next = $selectMultiple.activeMatchIndex+1,
prev = $selectMultiple.activeMatchIndex-1,
newIndex = curr;
if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
$select.close();
function getNewActiveMatchIndex(){
switch(key){
case KEY.LEFT:
// Select previous/first item
if(~$selectMultiple.activeMatchIndex) return prev;
// Select last item
else return last;
break;
case KEY.RIGHT:
// Open drop-down
if(!~$selectMultiple.activeMatchIndex || curr === last){
$select.activate();
return false;
}
// Select next/last item
else return next;
break;
case KEY.BACKSPACE:
// Remove selected item and select previous/first
if(~$selectMultiple.activeMatchIndex){
if($selectMultiple.removeChoice(curr)) {
return prev;
} else {
return curr;
}
} else {
// If nothing yet selected, select last item
return last;
}
break;
case KEY.DELETE:
// Remove selected item and select next item
if(~$selectMultiple.activeMatchIndex){
$selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
return curr;
}
else return false;
}
}
newIndex = getNewActiveMatchIndex();
if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
return true;
}
$select.searchInput.on('keyup', function(e) {
if ( ! KEY.isVerticalMovement(e.which) ) {
scope.$evalAsync( function () {
$select.activeIndex = $select.taggingLabel === false ? -1 : 0;
});
}
// Push a "create new" item into array if there is a search string
if ( $select.tagging.isActivated && $select.search.length > 0 ) {
// return early with these keys
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
return;
}
// always reset the activeIndex to the first item when tagging
$select.activeIndex = $select.taggingLabel === false ? -1 : 0;
// taggingLabel === false bypasses all of this
if ($select.taggingLabel === false) return;
var items = angular.copy( $select.items );
var stashArr = angular.copy( $select.items );
var newItem;
var item;
var hasTag = false;
var dupeIndex = -1;
var tagItems;
var tagItem;
// case for object tagging via transform `$select.tagging.fct` function
if ( $select.tagging.fct !== undefined) {
tagItems = $select.$filter('filter')(items,{'isTag': true});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
// remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
if ( items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = $select.tagging.fct($select.search);
// verify the new tag doesn't match the value of a possible selection choice or an already selected item.
if (
stashArr.some(function (origItem) {
return angular.equals(origItem, newItem);
}) ||
$select.selected.some(function (origItem) {
return angular.equals(origItem, newItem);
})
) {
scope.$evalAsync(function () {
$select.activeIndex = 0;
$select.items = items;
});
return;
}
if (newItem) newItem.isTag = true;
// handle newItem string and stripping dupes in tagging string context
} else {
// find any tagging items already in the $select.items array and store them
tagItems = $select.$filter('filter')(items,function (item) {
return item.match($select.taggingLabel);
});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
item = items[0];
// remove existing tag item if found (should only ever be one tag item)
if ( item !== undefined && items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = $select.search+' '+$select.taggingLabel;
if ( _findApproxDupe($select.selected, $select.search) > -1 ) {
return;
}
// verify the the tag doesn't match the value of an existing item from
// the searched data set or the items already selected
if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) {
// if there is a tag from prev iteration, strip it / queue the change
// and return early
if ( hasTag ) {
items = stashArr;
scope.$evalAsync( function () {
$select.activeIndex = 0;
$select.items = items;
});
}
return;
}
if ( _findCaseInsensitiveDupe(stashArr) ) {
// if there is a tag from prev iteration, strip it
if ( hasTag ) {
$select.items = stashArr.slice(1,stashArr.length);
}
return;
}
}
if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem);
// dupe found, shave the first item
if ( dupeIndex > -1 ) {
items = items.slice(dupeIndex+1,items.length-1);
} else {
items = [];
if (newItem) items.push(newItem);
items = items.concat(stashArr);
}
scope.$evalAsync( function () {
$select.activeIndex = 0;
$select.items = items;
if ($select.isGrouped) {
// update item references in groups, so that indexOf will work after angular.copy
var itemsWithoutTag = newItem ? items.slice(1) : items;
$select.setItemsFn(itemsWithoutTag);
if (newItem) {
// add tag item as a new group
$select.items.unshift(newItem);
$select.groups.unshift({name: '', items: [newItem], tagging: true});
}
}
});
}
});
function _findCaseInsensitiveDupe(arr) {
if ( arr === undefined || $select.search === undefined ) {
return false;
}
var hasDupe = arr.filter( function (origItem) {
if ( $select.search.toUpperCase() === undefined || origItem === undefined ) {
return false;
}
return origItem.toUpperCase() === $select.search.toUpperCase();
}).length > 0;
return hasDupe;
}
function _findApproxDupe(haystack, needle) {
var dupeIndex = -1;
if(angular.isArray(haystack)) {
var tempArr = angular.copy(haystack);
for (var i = 0; i <tempArr.length; i++) {
// handle the simple string version of tagging
if ( $select.tagging.fct === undefined ) {
// search the array for the match
if ( tempArr[i]+' '+$select.taggingLabel === needle ) {
dupeIndex = i;
}
// handle the object tagging implementation
} else {
var mockObj = tempArr[i];
if (angular.isObject(mockObj)) {
mockObj.isTag = true;
}
if ( angular.equals(mockObj, needle) ) {
dupeIndex = i;
}
}
}
}
return dupeIndex;
}
$select.searchInput.on('blur', function() {
$timeout(function() {
$selectMultiple.activeMatchIndex = -1;
});
});
}
};
}]);
uis.directive('uiSelectNoChoice',
['uiSelectConfig', function (uiSelectConfig) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function (tElement) {
// Needed so the uiSelect can detect the transcluded content
tElement.addClass('ui-select-no-choice');
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
return theme + '/no-choice.tpl.html';
}
};
}]);
uis.directive('uiSelectSingle', ['$timeout','$compile', function($timeout, $compile) {
return {
restrict: 'EA',
require: ['^uiSelect', '^ngModel'],
link: function(scope, element, attrs, ctrls) {
var $select = ctrls[0];
var ngModel = ctrls[1];
//From view --> model
ngModel.$parsers.unshift(function (inputValue) {
// Keep original value for undefined and null
if (isNil(inputValue)) {
return inputValue;
}
var locals = {},
result;
locals[$select.parserResult.itemName] = inputValue;
result = $select.parserResult.modelMapper(scope, locals);
return result;
});
//From model --> view
ngModel.$formatters.unshift(function (inputValue) {
// Keep original value for undefined and null
if (isNil(inputValue)) {
return inputValue;
}
var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
locals = {},
result;
if (data){
var checkFnSingle = function(d){
locals[$select.parserResult.itemName] = d;
result = $select.parserResult.modelMapper(scope, locals);
return result === inputValue;
};
//If possible pass same object stored in $select.selected
if ($select.selected && checkFnSingle($select.selected)) {
return $select.selected;
}
for (var i = data.length - 1; i >= 0; i--) {
if (checkFnSingle(data[i])) return data[i];
}
}
return inputValue;
});
//Update viewValue if model change
scope.$watch('$select.selected', function(newValue) {
if (ngModel.$viewValue !== newValue) {
ngModel.$setViewValue(newValue);
}
});
ngModel.$render = function() {
$select.selected = ngModel.$viewValue;
};
scope.$on('uis:select', function (event, item) {
$select.selected = item;
var locals = {};
locals[$select.parserResult.itemName] = item;
$timeout(function() {
$select.onSelectCallback(scope, {
$item: item,
$model: isNil(item) ? item : $select.parserResult.modelMapper(scope, locals)
});
});
});
scope.$on('uis:close', function (event, skipFocusser) {
$timeout(function(){
$select.focusser.prop('disabled', false);
if (!skipFocusser) $select.focusser[0].focus();
},0,false);
});
scope.$on('uis:activate', function () {
focusser.prop('disabled', true); //Will reactivate it on .close()
});
//Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954
var focusser = angular.element("<input ng-disabled='$select.disabled' class='ui-select-focusser ui-select-offscreen' type='text' id='{{ $select.focusserId }}' aria-label='{{ $select.focusserTitle }}' aria-haspopup='true' role='button' />");
$compile(focusser)(scope);
$select.focusser = focusser;
//Input that will handle focus
$select.focusInput = focusser;
element.parent().append(focusser);
focusser.bind("focus", function(){
scope.$evalAsync(function(){
$select.focus = true;
});
});
focusser.bind("blur", function(){
scope.$evalAsync(function(){
$select.focus = false;
});
});
focusser.bind("keydown", function(e){
if (e.which === KEY.BACKSPACE && $select.backspaceReset !== false) {
e.preventDefault();
e.stopPropagation();
$select.select(undefined);
scope.$apply();
return;
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
return;
}
if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){
e.preventDefault();
e.stopPropagation();
$select.activate();
}
scope.$digest();
});
focusser.bind("keyup input", function(e){
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) {
return;
}
$select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input
focusser.val('');
scope.$digest();
});
}
};
}]);
// Make multiple matches sortable
uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) {
return {
require: ['^^uiSelect', '^ngModel'],
link: function(scope, element, attrs, ctrls) {
if (scope[attrs.uiSelectSort] === null) {
throw uiSelectMinErr('sort', 'Expected a list to sort');
}
var $select = ctrls[0];
var $ngModel = ctrls[1];
var options = angular.extend({
axis: 'horizontal'
},
scope.$eval(attrs.uiSelectSortOptions));
var axis = options.axis;
var draggingClassName = 'dragging';
var droppingClassName = 'dropping';
var droppingBeforeClassName = 'dropping-before';
var droppingAfterClassName = 'dropping-after';
scope.$watch(function(){
return $select.sortable;
}, function(newValue){
if (newValue) {
element.attr('draggable', true);
} else {
element.removeAttr('draggable');
}
});
element.on('dragstart', function(event) {
element.addClass(draggingClassName);
(event.dataTransfer || event.originalEvent.dataTransfer).setData('text', scope.$index.toString());
});
element.on('dragend', function() {
removeClass(draggingClassName);
});
var move = function(from, to) {
/*jshint validthis: true */
this.splice(to, 0, this.splice(from, 1)[0]);
};
var removeClass = function(className) {
angular.forEach($select.$element.querySelectorAll('.' + className), function(el){
angular.element(el).removeClass(className);
});
};
var dragOverHandler = function(event) {
event.preventDefault();
var offset = axis === 'vertical' ? event.offsetY || event.layerY || (event.originalEvent ? event.originalEvent.offsetY : 0) : event.offsetX || event.layerX || (event.originalEvent ? event.originalEvent.offsetX : 0);
if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) {
removeClass(droppingAfterClassName);
element.addClass(droppingBeforeClassName);
} else {
removeClass(droppingBeforeClassName);
element.addClass(droppingAfterClassName);
}
};
var dropTimeout;
var dropHandler = function(event) {
event.preventDefault();
var droppedItemIndex = parseInt((event.dataTransfer || event.originalEvent.dataTransfer).getData('text'), 10);
// prevent event firing multiple times in firefox
$timeout.cancel(dropTimeout);
dropTimeout = $timeout(function() {
_dropHandler(droppedItemIndex);
}, 20);
};
var _dropHandler = function(droppedItemIndex) {
var theList = scope.$eval(attrs.uiSelectSort);
var itemToMove = theList[droppedItemIndex];
var newIndex = null;
if (element.hasClass(droppingBeforeClassName)) {
if (droppedItemIndex < scope.$index) {
newIndex = scope.$index - 1;
} else {
newIndex = scope.$index;
}
} else {
if (droppedItemIndex < scope.$index) {
newIndex = scope.$index;
} else {
newIndex = scope.$index + 1;
}
}
move.apply(theList, [droppedItemIndex, newIndex]);
$ngModel.$setViewValue(Date.now());
scope.$apply(function() {
scope.$emit('uiSelectSort:change', {
array: theList,
item: itemToMove,
from: droppedItemIndex,
to: newIndex
});
});
removeClass(droppingClassName);
removeClass(droppingBeforeClassName);
removeClass(droppingAfterClassName);
element.off('drop', dropHandler);
};
element.on('dragenter', function() {
if (element.hasClass(draggingClassName)) {
return;
}
element.addClass(droppingClassName);
element.on('dragover', dragOverHandler);
element.on('drop', dropHandler);
});
element.on('dragleave', function(event) {
if (event.target != element) {
return;
}
removeClass(droppingClassName);
removeClass(droppingBeforeClassName);
removeClass(droppingAfterClassName);
element.off('dragover', dragOverHandler);
element.off('drop', dropHandler);
});
}
};
}]);
uis.directive('uisOpenClose', ['$parse', '$timeout', function ($parse, $timeout) {
return {
restrict: 'A',
require: 'uiSelect',
link: function (scope, element, attrs, $select) {
$select.onOpenCloseCallback = $parse(attrs.uisOpenClose);
scope.$watch('$select.open', function (isOpen, previousState) {
if (isOpen !== previousState) {
$timeout(function () {
$select.onOpenCloseCallback(scope, {
isOpen: isOpen
});
});
}
});
}
};
}]);
/**
* Parses "repeat" attribute.
*
* Taken from AngularJS ngRepeat source code
* See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211
*
* Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat:
* https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697
*/
uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) {
var self = this;
/**
* Example:
* expression = "address in addresses | filter: {street: $select.search} track by $index"
* itemName = "address",
* source = "addresses | filter: {street: $select.search}",
* trackByExp = "$index",
*/
self.parse = function(expression) {
var match;
//var isObjectCollection = /\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)/.test(expression);
// If an array is used as collection
// if (isObjectCollection){
// 000000000000000000000000000000111111111000000000000000222222222222220033333333333333333333330000444444444444444444000000000000000055555555555000000000000000000000066666666600000000
match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(\s*[\s\S]+?)?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
// 1 Alias
// 2 Item
// 3 Key on (key,value)
// 4 Value on (key,value)
// 5 Source expression (including filters)
// 6 Track by
if (!match) {
throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var source = match[5],
filters = '';
// When using (key,value) ui-select requires filters to be extracted, since the object
// is converted to an array for $select.items
// (in which case the filters need to be reapplied)
if (match[3]) {
// Remove any enclosing parenthesis
source = match[5].replace(/(^\()|(\)$)/g, '');
// match all after | but not after ||
var filterMatch = match[5].match(/^\s*(?:[\s\S]+?)(?:[^\|]|\|\|)+([\s\S]*)\s*$/);
if(filterMatch && filterMatch[1].trim()) {
filters = filterMatch[1];
source = source.replace(filters, '');
}
}
return {
itemName: match[4] || match[2], // (lhs) Left-hand side,
keyName: match[3], //for (key, value) syntax
source: $parse(source),
filters: filters,
trackByExp: match[6],
modelMapper: $parse(match[1] || match[4] || match[2]),
repeatExpression: function (grouped) {
var expression = this.itemName + ' in ' + (grouped ? '$group.items' : '$select.items');
if (this.trackByExp) {
expression += ' track by ' + this.trackByExp;
}
return expression;
}
};
};
self.getGroupNgRepeatExpression = function() {
return '$group in $select.groups track by $group.name';
};
}]);
}());
angular.module("ui.select").run(["$templateCache", function($templateCache) {$templateCache.put("bootstrap/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content ui-select-dropdown dropdown-menu\" ng-show=\"$select.open && $select.items.length > 0\"><li class=\"ui-select-choices-group\" id=\"ui-select-choices-{{ $select.generatedId }}\"><div class=\"divider\" ng-show=\"$select.isGrouped && $index > 0\"></div><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label dropdown-header\" ng-bind=\"$group.name\"></div><div ng-attr-id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\" role=\"option\"><span class=\"ui-select-choices-row-inner\"></span></div></li></ul>");
$templateCache.put("bootstrap/match-multiple.tpl.html","<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected track by $index\"><span class=\"ui-select-match-item btn btn-default btn-xs\" tabindex=\"-1\" type=\"button\" ng-disabled=\"$select.disabled\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'btn-primary\':$selectMultiple.activeMatchIndex === $index, \'select-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span class=\"close ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\"> ×</span> <span uis-transclude-append=\"\"></span></span></span></span>");
$templateCache.put("bootstrap/match.tpl.html","<div class=\"ui-select-match\" ng-hide=\"$select.open && $select.searchEnabled\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><span tabindex=\"-1\" class=\"btn btn-default form-control ui-select-toggle\" aria-label=\"{{ $select.baseTitle }} activate\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" style=\"outline: 0;\"><span ng-show=\"$select.isEmpty()\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"ui-select-match-text pull-left\" ng-class=\"{\'ui-select-allow-clear\': $select.allowClear && !$select.isEmpty()}\" ng-transclude=\"\"></span> <i class=\"caret pull-right\" ng-click=\"$select.toggle($event)\"></i> <a ng-show=\"$select.allowClear && !$select.isEmpty() && ($select.disabled !== true)\" aria-label=\"{{ $select.baseTitle }} clear\" style=\"margin-right: 10px\" ng-click=\"$select.clear($event)\" class=\"btn btn-xs btn-link pull-right\"><i class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></i></a></span></div>");
$templateCache.put("bootstrap/no-choice.tpl.html","<ul class=\"ui-select-no-choice dropdown-menu\" ng-show=\"$select.items.length == 0\"><li ng-transclude=\"\"></li></ul>");
$templateCache.put("bootstrap/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control\" ng-class=\"{open: $select.open}\"><div><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-expanded=\"{{$select.open}}\" aria-label=\"{{$select.baseTitle}}\" ng-class=\"{\'spinner\': $select.refreshing}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");
$templateCache.put("bootstrap/select.tpl.html","<div class=\"ui-select-container ui-select-bootstrap dropdown\" ng-class=\"{open: $select.open}\"><div class=\"ui-select-match\"></div><span ng-show=\"$select.open && $select.refreshing && $select.spinnerEnabled\" class=\"ui-select-refreshing {{$select.spinnerClass}}\"></span> <input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" aria-expanded=\"true\" aria-label=\"{{ $select.baseTitle }}\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" class=\"form-control ui-select-search\" ng-class=\"{ \'ui-select-search-hidden\' : !$select.searchEnabled }\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.open\"><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");
$templateCache.put("select2/choices.tpl.html","<ul tabindex=\"-1\" class=\"ui-select-choices ui-select-choices-content select2-results\"><li class=\"ui-select-choices-group\" ng-class=\"{\'select2-result-with-children\': $select.choiceGrouped($group) }\"><div ng-show=\"$select.choiceGrouped($group)\" class=\"ui-select-choices-group-label select2-result-label\" ng-bind=\"$group.name\"></div><ul id=\"ui-select-choices-{{ $select.generatedId }}\" ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li role=\"option\" ng-attr-id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{\'select2-highlighted\': $select.isActive(this), \'select2-disabled\': $select.isDisabled(this)}\"><div class=\"select2-result-label ui-select-choices-row-inner\"></div></li></ul></li></ul>");
$templateCache.put("select2/match-multiple.tpl.html","<span class=\"ui-select-match\"><li class=\"ui-select-match-item select2-search-choice\" ng-repeat=\"$item in $select.selected track by $index\" ng-class=\"{\'select2-search-choice-focus\':$selectMultiple.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$selectMultiple.removeChoice($index)\" tabindex=\"-1\"></a></li></span>");
$templateCache.put("select2/match.tpl.html","<a class=\"select2-choice ui-select-match\" ng-class=\"{\'select2-default\': $select.isEmpty()}\" ng-click=\"$select.toggle($event)\" aria-label=\"{{ $select.baseTitle }} select\"><span ng-show=\"$select.isEmpty()\" class=\"select2-chosen\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"select2-chosen\" ng-transclude=\"\"></span> <abbr ng-if=\"$select.allowClear && !$select.isEmpty()\" class=\"select2-search-choice-close\" ng-click=\"$select.clear($event)\"></abbr> <span class=\"select2-arrow ui-select-toggle\"><b></b></span></a>");
$templateCache.put("select2/no-choice.tpl.html","<div class=\"ui-select-no-choice dropdown\" ng-show=\"$select.items.length == 0\"><div class=\"dropdown-content\"><div data-selectable=\"\" ng-transclude=\"\"></div></div></div>");
$templateCache.put("select2/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple select2 select2-container select2-container-multi\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled}\"><ul class=\"select2-choices\"><span class=\"ui-select-match\"></span><li class=\"select2-search-field\"><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"select2-input ui-select-search\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-model=\"$select.search\" ng-click=\"$select.activate()\" style=\"width: 34px;\" ondrop=\"return false;\"></li></ul><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open || $select.items.length === 0}\"><div class=\"ui-select-choices\"></div></div></div>");
$templateCache.put("select2/select.tpl.html","<div class=\"ui-select-container select2 select2-container\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled, \'select2-container-active\': $select.focus, \'select2-allowclear\': $select.allowClear && !$select.isEmpty()}\"><div class=\"ui-select-match\"></div><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"search-container\" ng-class=\"{\'ui-select-search-hidden\':!$select.searchEnabled, \'select2-search\':$select.searchEnabled}\"><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" ng-class=\"{\'select2-active\': $select.refreshing}\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" class=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div></div>");
$templateCache.put("selectize/choices.tpl.html","<div ng-show=\"$select.open\" class=\"ui-select-choices ui-select-dropdown selectize-dropdown\" ng-class=\"{\'single\': !$select.multiple, \'multi\': $select.multiple}\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\"><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label optgroup-header\" ng-bind=\"$group.name\"></div><div role=\"option\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><div class=\"option ui-select-choices-row-inner\" data-selectable=\"\"></div></div></div></div></div>");
$templateCache.put("selectize/match-multiple.tpl.html","<div class=\"ui-select-match\" data-value=\"\" ng-repeat=\"$item in $select.selected track by $index\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'active\':$selectMultiple.activeMatchIndex === $index}\" ui-select-sort=\"$select.selected\"><span class=\"ui-select-match-item\" ng-class=\"{\'select-locked\':$select.isLocked(this, $index)}\"><span uis-transclude-append=\"\"></span> <span class=\"remove ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\">×</span></span></div>");
$templateCache.put("selectize/match.tpl.html","<div ng-hide=\"$select.searchEnabled && ($select.open || $select.isEmpty())\" class=\"ui-select-match\"><span ng-show=\"!$select.searchEnabled && ($select.isEmpty() || $select.open)\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty() || $select.open\" ng-transclude=\"\"></span></div>");
$templateCache.put("selectize/no-choice.tpl.html","<div class=\"ui-select-no-choice selectize-dropdown\" ng-show=\"$select.items.length == 0\"><div class=\"selectize-dropdown-content\"><div data-selectable=\"\" ng-transclude=\"\"></div></div></div>");
$templateCache.put("selectize/select-multiple.tpl.html","<div class=\"ui-select-container selectize-control multi plugin-remove_button\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search\" ng-class=\"{\'ui-select-search-hidden\':!$select.searchEnabled}\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-model=\"$select.search\" ng-disabled=\"$select.disabled\" aria-expanded=\"{{$select.open}}\" aria-label=\"{{ $select.baseTitle }}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");
$templateCache.put("selectize/select.tpl.html","<div class=\"ui-select-container selectize-control single\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-class=\"{\'ui-select-search-hidden\':!$select.searchEnabled}\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.isEmpty() && !$select.open\" ng-disabled=\"$select.disabled\" aria-label=\"{{ $select.baseTitle }}\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");}]); |
pages/index.js | InnoD-WebTier/bsjas | import React from 'react';
import Helmet from 'react-helmet';
import { config } from 'config';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';
class Index extends React.Component {
render () {
const backgroundLink = prefixLink(`/assets/bg.jpeg`);
const style = {
'background': "url('" + backgroundLink + "') no-repeat center center",
'color': 'white',
'width': '100%',
'height': 'calc(100vh - 80px)',
'-webkit-background-size': 'cover',
'-moz-background-size': 'cover',
'-o-background-size': 'cover',
'background-size': 'cover',
'display': 'flex',
'justify-content': 'center',
'align-items': 'center',
};
return (
<div>
<Helmet
title={config.siteTitle}
/>
<div className="site-landing" style={style}>
<div className="box">
<p className="title">
Engaging the Berkeley Community in dialogue on Asia.
</p>
<p className="subtitle">
BSJAS is an Institute of East Asian Studies sponsored journal that strives to showcase the best undergraduate and graduate work in Asia-related fields.
</p>
<Link to={prefixLink("journal/")}>
<div className="button">
Submit your work
</div>
</Link>
<Link to={prefixLink("about/")}>
<div className="button">
Learn more
</div>
</Link>
</div>
</div>
</div>
);
}
}
export default Index;
|
ajax/libs/zeroclipboard/2.1.4/ZeroClipboard.js | jimmybyrum/cdnjs | /*!
* ZeroClipboard
* The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.
* Copyright (c) 2014 Jon Rohan, James M. Greene
* Licensed MIT
* http://zeroclipboard.org/
* v2.1.4
*/
(function(window, undefined) {
"use strict";
/**
* Store references to critically important global functions that may be
* overridden on certain web pages.
*/
var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _round = _window.Math.round, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice;
/**
* Convert an `arguments` object into an Array.
*
* @returns The arguments as an Array
* @private
*/
var _args = function(argumentsObj) {
return _slice.call(argumentsObj, 0);
};
/**
* Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`.
*
* @returns The target object, augmented
* @private
*/
var _extend = function() {
var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {};
for (i = 1, len = args.length; i < len; i++) {
if ((arg = args[i]) != null) {
for (prop in arg) {
if (_hasOwn.call(arg, prop)) {
src = target[prop];
copy = arg[prop];
if (target !== copy && copy !== undefined) {
target[prop] = copy;
}
}
}
}
}
return target;
};
/**
* Return a deep copy of the source object or array.
*
* @returns Object or Array
* @private
*/
var _deepCopy = function(source) {
var copy, i, len, prop;
if (typeof source !== "object" || source == null) {
copy = source;
} else if (typeof source.length === "number") {
copy = [];
for (i = 0, len = source.length; i < len; i++) {
if (_hasOwn.call(source, i)) {
copy[i] = _deepCopy(source[i]);
}
}
} else {
copy = {};
for (prop in source) {
if (_hasOwn.call(source, prop)) {
copy[prop] = _deepCopy(source[prop]);
}
}
}
return copy;
};
/**
* Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep.
* The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to
* be kept.
*
* @returns A new filtered object.
* @private
*/
var _pick = function(obj, keys) {
var newObj = {};
for (var i = 0, len = keys.length; i < len; i++) {
if (keys[i] in obj) {
newObj[keys[i]] = obj[keys[i]];
}
}
return newObj;
};
/**
* Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit.
* The inverse of `_pick`.
*
* @returns A new filtered object.
* @private
*/
var _omit = function(obj, keys) {
var newObj = {};
for (var prop in obj) {
if (keys.indexOf(prop) === -1) {
newObj[prop] = obj[prop];
}
}
return newObj;
};
/**
* Remove all owned, enumerable properties from an object.
*
* @returns The original object without its owned, enumerable properties.
* @private
*/
var _deleteOwnProperties = function(obj) {
if (obj) {
for (var prop in obj) {
if (_hasOwn.call(obj, prop)) {
delete obj[prop];
}
}
}
return obj;
};
/**
* Determine if an element is contained within another element.
*
* @returns Boolean
* @private
*/
var _containedBy = function(el, ancestorEl) {
if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) {
do {
if (el === ancestorEl) {
return true;
}
el = el.parentNode;
} while (el);
}
return false;
};
/**
* Get the URL path's parent directory.
*
* @returns String or `undefined`
* @private
*/
var _getDirPathOfUrl = function(url) {
var dir;
if (typeof url === "string" && url) {
dir = url.split("#")[0].split("?")[0];
dir = url.slice(0, url.lastIndexOf("/") + 1);
}
return dir;
};
/**
* Get the current script's URL by throwing an `Error` and analyzing it.
*
* @returns String or `undefined`
* @private
*/
var _getCurrentScriptUrlFromErrorStack = function(stack) {
var url, matches;
if (typeof stack === "string" && stack) {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
} else {
matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (matches && matches[1]) {
url = matches[1];
}
}
}
return url;
};
/**
* Get the current script's URL by throwing an `Error` and analyzing it.
*
* @returns String or `undefined`
* @private
*/
var _getCurrentScriptUrlFromError = function() {
var url, err;
try {
throw new _Error();
} catch (e) {
err = e;
}
if (err) {
url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack);
}
return url;
};
/**
* Get the current script's URL.
*
* @returns String or `undefined`
* @private
*/
var _getCurrentScriptUrl = function() {
var jsPath, scripts, i;
if (_document.currentScript && (jsPath = _document.currentScript.src)) {
return jsPath;
}
scripts = _document.getElementsByTagName("script");
if (scripts.length === 1) {
return scripts[0].src || undefined;
}
if ("readyState" in scripts[0]) {
for (i = scripts.length; i--; ) {
if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) {
return jsPath;
}
}
}
if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) {
return jsPath;
}
if (jsPath = _getCurrentScriptUrlFromError()) {
return jsPath;
}
return undefined;
};
/**
* Get the unanimous parent directory of ALL script tags.
* If any script tags are either (a) inline or (b) from differing parent
* directories, this method must return `undefined`.
*
* @returns String or `undefined`
* @private
*/
var _getUnanimousScriptParentDir = function() {
var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script");
for (i = scripts.length; i--; ) {
if (!(jsPath = scripts[i].src)) {
jsDir = null;
break;
}
jsPath = _getDirPathOfUrl(jsPath);
if (jsDir == null) {
jsDir = jsPath;
} else if (jsDir !== jsPath) {
jsDir = null;
break;
}
}
return jsDir || undefined;
};
/**
* Get the presumed location of the "ZeroClipboard.swf" file, based on the location
* of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.).
*
* @returns String
* @private
*/
var _getDefaultSwfPath = function() {
var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || "";
return jsDir + "ZeroClipboard.swf";
};
/**
* Keep track of the state of the Flash object.
* @private
*/
var _flashState = {
bridge: null,
version: "0.0.0",
pluginType: "unknown",
disabled: null,
outdated: null,
unavailable: null,
deactivated: null,
overdue: null,
ready: null
};
/**
* The minimum Flash Player version required to use ZeroClipboard completely.
* @readonly
* @private
*/
var _minimumFlashVersion = "11.0.0";
/**
* Keep track of all event listener registrations.
* @private
*/
var _handlers = {};
/**
* Keep track of the currently activated element.
* @private
*/
var _currentElement;
/**
* Keep track of data for the pending clipboard transaction.
* @private
*/
var _clipData = {};
/**
* Keep track of data formats for the pending clipboard transaction.
* @private
*/
var _clipDataFormatMap = null;
/**
* The `message` store for events
* @private
*/
var _eventMessages = {
ready: "Flash communication is established",
error: {
"flash-disabled": "Flash is disabled or not installed",
"flash-outdated": "Flash is too outdated to support ZeroClipboard",
"flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript",
"flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate",
"flash-overdue": "Flash communication was established but NOT within the acceptable time limit"
}
};
/**
* ZeroClipboard configuration defaults for the Core module.
* @private
*/
var _globalConfig = {
swfPath: _getDefaultSwfPath(),
trustedDomains: window.location.host ? [ window.location.host ] : [],
cacheBust: true,
forceEnhancedClipboard: false,
flashLoadTimeout: 3e4,
autoActivate: true,
bubbleEvents: true,
containerId: "global-zeroclipboard-html-bridge",
containerClass: "global-zeroclipboard-container",
swfObjectId: "global-zeroclipboard-flash-bridge",
hoverClass: "zeroclipboard-is-hover",
activeClass: "zeroclipboard-is-active",
forceHandCursor: false,
title: null,
zIndex: 999999999
};
/**
* The underlying implementation of `ZeroClipboard.config`.
* @private
*/
var _config = function(options) {
if (typeof options === "object" && options !== null) {
for (var prop in options) {
if (_hasOwn.call(options, prop)) {
if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) {
_globalConfig[prop] = options[prop];
} else if (_flashState.bridge == null) {
if (prop === "containerId" || prop === "swfObjectId") {
if (_isValidHtml4Id(options[prop])) {
_globalConfig[prop] = options[prop];
} else {
throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID");
}
} else {
_globalConfig[prop] = options[prop];
}
}
}
}
}
if (typeof options === "string" && options) {
if (_hasOwn.call(_globalConfig, options)) {
return _globalConfig[options];
}
return;
}
return _deepCopy(_globalConfig);
};
/**
* The underlying implementation of `ZeroClipboard.state`.
* @private
*/
var _state = function() {
return {
browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]),
flash: _omit(_flashState, [ "bridge" ]),
zeroclipboard: {
version: ZeroClipboard.version,
config: ZeroClipboard.config()
}
};
};
/**
* The underlying implementation of `ZeroClipboard.isFlashUnusable`.
* @private
*/
var _isFlashUnusable = function() {
return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated);
};
/**
* The underlying implementation of `ZeroClipboard.on`.
* @private
*/
var _on = function(eventType, listener) {
var i, len, events, added = {};
if (typeof eventType === "string" && eventType) {
events = eventType.toLowerCase().split(/\s+/);
} else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
for (i in eventType) {
if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
ZeroClipboard.on(i, eventType[i]);
}
}
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].replace(/^on/, "");
added[eventType] = true;
if (!_handlers[eventType]) {
_handlers[eventType] = [];
}
_handlers[eventType].push(listener);
}
if (added.ready && _flashState.ready) {
ZeroClipboard.emit({
type: "ready"
});
}
if (added.error) {
var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ];
for (i = 0, len = errorTypes.length; i < len; i++) {
if (_flashState[errorTypes[i]] === true) {
ZeroClipboard.emit({
type: "error",
name: "flash-" + errorTypes[i]
});
break;
}
}
}
}
return ZeroClipboard;
};
/**
* The underlying implementation of `ZeroClipboard.off`.
* @private
*/
var _off = function(eventType, listener) {
var i, len, foundIndex, events, perEventHandlers;
if (arguments.length === 0) {
events = _keys(_handlers);
} else if (typeof eventType === "string" && eventType) {
events = eventType.split(/\s+/);
} else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
for (i in eventType) {
if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
ZeroClipboard.off(i, eventType[i]);
}
}
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].toLowerCase().replace(/^on/, "");
perEventHandlers = _handlers[eventType];
if (perEventHandlers && perEventHandlers.length) {
if (listener) {
foundIndex = perEventHandlers.indexOf(listener);
while (foundIndex !== -1) {
perEventHandlers.splice(foundIndex, 1);
foundIndex = perEventHandlers.indexOf(listener, foundIndex);
}
} else {
perEventHandlers.length = 0;
}
}
}
}
return ZeroClipboard;
};
/**
* The underlying implementation of `ZeroClipboard.handlers`.
* @private
*/
var _listeners = function(eventType) {
var copy;
if (typeof eventType === "string" && eventType) {
copy = _deepCopy(_handlers[eventType]) || null;
} else {
copy = _deepCopy(_handlers);
}
return copy;
};
/**
* The underlying implementation of `ZeroClipboard.emit`.
* @private
*/
var _emit = function(event) {
var eventCopy, returnVal, tmp;
event = _createEvent(event);
if (!event) {
return;
}
if (_preprocessEvent(event)) {
return;
}
if (event.type === "ready" && _flashState.overdue === true) {
return ZeroClipboard.emit({
type: "error",
name: "flash-overdue"
});
}
eventCopy = _extend({}, event);
_dispatchCallbacks.call(this, eventCopy);
if (event.type === "copy") {
tmp = _mapClipDataToFlash(_clipData);
returnVal = tmp.data;
_clipDataFormatMap = tmp.formatMap;
}
return returnVal;
};
/**
* The underlying implementation of `ZeroClipboard.create`.
* @private
*/
var _create = function() {
if (typeof _flashState.ready !== "boolean") {
_flashState.ready = false;
}
if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) {
var maxWait = _globalConfig.flashLoadTimeout;
if (typeof maxWait === "number" && maxWait >= 0) {
_setTimeout(function() {
if (typeof _flashState.deactivated !== "boolean") {
_flashState.deactivated = true;
}
if (_flashState.deactivated === true) {
ZeroClipboard.emit({
type: "error",
name: "flash-deactivated"
});
}
}, maxWait);
}
_flashState.overdue = false;
_embedSwf();
}
};
/**
* The underlying implementation of `ZeroClipboard.destroy`.
* @private
*/
var _destroy = function() {
ZeroClipboard.clearData();
ZeroClipboard.blur();
ZeroClipboard.emit("destroy");
_unembedSwf();
ZeroClipboard.off();
};
/**
* The underlying implementation of `ZeroClipboard.setData`.
* @private
*/
var _setData = function(format, data) {
var dataObj;
if (typeof format === "object" && format && typeof data === "undefined") {
dataObj = format;
ZeroClipboard.clearData();
} else if (typeof format === "string" && format) {
dataObj = {};
dataObj[format] = data;
} else {
return;
}
for (var dataFormat in dataObj) {
if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) {
_clipData[dataFormat] = dataObj[dataFormat];
}
}
};
/**
* The underlying implementation of `ZeroClipboard.clearData`.
* @private
*/
var _clearData = function(format) {
if (typeof format === "undefined") {
_deleteOwnProperties(_clipData);
_clipDataFormatMap = null;
} else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
delete _clipData[format];
}
};
/**
* The underlying implementation of `ZeroClipboard.getData`.
* @private
*/
var _getData = function(format) {
if (typeof format === "undefined") {
return _deepCopy(_clipData);
} else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
return _clipData[format];
}
};
/**
* The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`.
* @private
*/
var _focus = function(element) {
if (!(element && element.nodeType === 1)) {
return;
}
if (_currentElement) {
_removeClass(_currentElement, _globalConfig.activeClass);
if (_currentElement !== element) {
_removeClass(_currentElement, _globalConfig.hoverClass);
}
}
_currentElement = element;
_addClass(element, _globalConfig.hoverClass);
var newTitle = element.getAttribute("title") || _globalConfig.title;
if (typeof newTitle === "string" && newTitle) {
var htmlBridge = _getHtmlBridge(_flashState.bridge);
if (htmlBridge) {
htmlBridge.setAttribute("title", newTitle);
}
}
var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer";
_setHandCursor(useHandCursor);
_reposition();
};
/**
* The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`.
* @private
*/
var _blur = function() {
var htmlBridge = _getHtmlBridge(_flashState.bridge);
if (htmlBridge) {
htmlBridge.removeAttribute("title");
htmlBridge.style.left = "0px";
htmlBridge.style.top = "-9999px";
htmlBridge.style.width = "1px";
htmlBridge.style.top = "1px";
}
if (_currentElement) {
_removeClass(_currentElement, _globalConfig.hoverClass);
_removeClass(_currentElement, _globalConfig.activeClass);
_currentElement = null;
}
};
/**
* The underlying implementation of `ZeroClipboard.activeElement`.
* @private
*/
var _activeElement = function() {
return _currentElement || null;
};
/**
* Check if a value is a valid HTML4 `ID` or `Name` token.
* @private
*/
var _isValidHtml4Id = function(id) {
return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id);
};
/**
* Create or update an `event` object, based on the `eventType`.
* @private
*/
var _createEvent = function(event) {
var eventType;
if (typeof event === "string" && event) {
eventType = event;
event = {};
} else if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
eventType = event.type;
}
if (!eventType) {
return;
}
_extend(event, {
type: eventType.toLowerCase(),
target: event.target || _currentElement || null,
relatedTarget: event.relatedTarget || null,
currentTarget: _flashState && _flashState.bridge || null,
timeStamp: event.timeStamp || _now() || null
});
var msg = _eventMessages[event.type];
if (event.type === "error" && event.name && msg) {
msg = msg[event.name];
}
if (msg) {
event.message = msg;
}
if (event.type === "ready") {
_extend(event, {
target: null,
version: _flashState.version
});
}
if (event.type === "error") {
if (/^flash-(disabled|outdated|unavailable|deactivated|overdue)$/.test(event.name)) {
_extend(event, {
target: null,
minimumVersion: _minimumFlashVersion
});
}
if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) {
_extend(event, {
version: _flashState.version
});
}
}
if (event.type === "copy") {
event.clipboardData = {
setData: ZeroClipboard.setData,
clearData: ZeroClipboard.clearData
};
}
if (event.type === "aftercopy") {
event = _mapClipResultsFromFlash(event, _clipDataFormatMap);
}
if (event.target && !event.relatedTarget) {
event.relatedTarget = _getRelatedTarget(event.target);
}
event = _addMouseData(event);
return event;
};
/**
* Get a relatedTarget from the target's `data-clipboard-target` attribute
* @private
*/
var _getRelatedTarget = function(targetEl) {
var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target");
return relatedTargetId ? _document.getElementById(relatedTargetId) : null;
};
/**
* Add element and position data to `MouseEvent` instances
* @private
*/
var _addMouseData = function(event) {
if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
var srcElement = event.target;
var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined;
var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined;
var pos = _getDOMObjectPosition(srcElement);
var screenLeft = _window.screenLeft || _window.screenX || 0;
var screenTop = _window.screenTop || _window.screenY || 0;
var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft;
var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop;
var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0);
var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0);
var clientX = pageX - scrollLeft;
var clientY = pageY - scrollTop;
var screenX = screenLeft + clientX;
var screenY = screenTop + clientY;
var moveX = typeof event.movementX === "number" ? event.movementX : 0;
var moveY = typeof event.movementY === "number" ? event.movementY : 0;
delete event._stageX;
delete event._stageY;
_extend(event, {
srcElement: srcElement,
fromElement: fromElement,
toElement: toElement,
screenX: screenX,
screenY: screenY,
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY,
x: clientX,
y: clientY,
movementX: moveX,
movementY: moveY,
offsetX: 0,
offsetY: 0,
layerX: 0,
layerY: 0
});
}
return event;
};
/**
* Determine if an event's registered handlers should be execute synchronously or asynchronously.
*
* @returns {boolean}
* @private
*/
var _shouldPerformAsync = function(event) {
var eventType = event && typeof event.type === "string" && event.type || "";
return !/^(?:(?:before)?copy|destroy)$/.test(eventType);
};
/**
* Control if a callback should be executed asynchronously or not.
*
* @returns `undefined`
* @private
*/
var _dispatchCallback = function(func, context, args, async) {
if (async) {
_setTimeout(function() {
func.apply(context, args);
}, 0);
} else {
func.apply(context, args);
}
};
/**
* Handle the actual dispatching of events to client instances.
*
* @returns `undefined`
* @private
*/
var _dispatchCallbacks = function(event) {
if (!(typeof event === "object" && event && event.type)) {
return;
}
var async = _shouldPerformAsync(event);
var wildcardTypeHandlers = _handlers["*"] || [];
var specificTypeHandlers = _handlers[event.type] || [];
var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
if (handlers && handlers.length) {
var i, len, func, context, eventCopy, originalContext = this;
for (i = 0, len = handlers.length; i < len; i++) {
func = handlers[i];
context = originalContext;
if (typeof func === "string" && typeof _window[func] === "function") {
func = _window[func];
}
if (typeof func === "object" && func && typeof func.handleEvent === "function") {
context = func;
func = func.handleEvent;
}
if (typeof func === "function") {
eventCopy = _extend({}, event);
_dispatchCallback(func, context, [ eventCopy ], async);
}
}
}
return this;
};
/**
* Preprocess any special behaviors, reactions, or state changes after receiving this event.
* Executes only once per event emitted, NOT once per client.
* @private
*/
var _preprocessEvent = function(event) {
var element = event.target || _currentElement || null;
var sourceIsSwf = event._source === "swf";
delete event._source;
var flashErrorNames = [ "flash-disabled", "flash-outdated", "flash-unavailable", "flash-deactivated", "flash-overdue" ];
switch (event.type) {
case "error":
if (flashErrorNames.indexOf(event.name) !== -1) {
_extend(_flashState, {
disabled: event.name === "flash-disabled",
outdated: event.name === "flash-outdated",
unavailable: event.name === "flash-unavailable",
deactivated: event.name === "flash-deactivated",
overdue: event.name === "flash-overdue",
ready: false
});
}
break;
case "ready":
var wasDeactivated = _flashState.deactivated === true;
_extend(_flashState, {
disabled: false,
outdated: false,
unavailable: false,
deactivated: false,
overdue: wasDeactivated,
ready: !wasDeactivated
});
break;
case "copy":
var textContent, htmlContent, targetEl = event.relatedTarget;
if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) {
event.clipboardData.clearData();
event.clipboardData.setData("text/plain", textContent);
if (htmlContent !== textContent) {
event.clipboardData.setData("text/html", htmlContent);
}
} else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) {
event.clipboardData.clearData();
event.clipboardData.setData("text/plain", textContent);
}
break;
case "aftercopy":
ZeroClipboard.clearData();
if (element && element !== _safeActiveElement() && element.focus) {
element.focus();
}
break;
case "_mouseover":
ZeroClipboard.focus(element);
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
_fireMouseEvent(_extend({}, event, {
type: "mouseenter",
bubbles: false,
cancelable: false
}));
}
_fireMouseEvent(_extend({}, event, {
type: "mouseover"
}));
}
break;
case "_mouseout":
ZeroClipboard.blur();
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
_fireMouseEvent(_extend({}, event, {
type: "mouseleave",
bubbles: false,
cancelable: false
}));
}
_fireMouseEvent(_extend({}, event, {
type: "mouseout"
}));
}
break;
case "_mousedown":
_addClass(element, _globalConfig.activeClass);
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
case "_mouseup":
_removeClass(element, _globalConfig.activeClass);
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
case "_click":
case "_mousemove":
if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
_fireMouseEvent(_extend({}, event, {
type: event.type.slice(1)
}));
}
break;
}
if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
return true;
}
};
/**
* Dispatch a synthetic MouseEvent.
*
* @returns `undefined`
* @private
*/
var _fireMouseEvent = function(event) {
if (!(event && typeof event.type === "string" && event)) {
return;
}
var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = {
view: doc.defaultView || _window,
canBubble: true,
cancelable: true,
detail: event.type === "click" ? 1 : 0,
button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1
}, args = _extend(defaults, event);
if (!target) {
return;
}
if (doc.createEvent && target.dispatchEvent) {
args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ];
e = doc.createEvent("MouseEvents");
if (e.initMouseEvent) {
e.initMouseEvent.apply(e, args);
e._source = "js";
target.dispatchEvent(e);
}
}
};
/**
* Create the HTML bridge element to embed the Flash object into.
* @private
*/
var _createHtmlBridge = function() {
var container = _document.createElement("div");
container.id = _globalConfig.containerId;
container.className = _globalConfig.containerClass;
container.style.position = "absolute";
container.style.left = "0px";
container.style.top = "-9999px";
container.style.width = "1px";
container.style.height = "1px";
container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex);
return container;
};
/**
* Get the HTML element container that wraps the Flash bridge object/element.
* @private
*/
var _getHtmlBridge = function(flashBridge) {
var htmlBridge = flashBridge && flashBridge.parentNode;
while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) {
htmlBridge = htmlBridge.parentNode;
}
return htmlBridge || null;
};
/**
* Create the SWF object.
*
* @returns The SWF object reference.
* @private
*/
var _embedSwf = function() {
var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge);
if (!flashBridge) {
var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig);
var allowNetworking = allowScriptAccess === "never" ? "none" : "all";
var flashvars = _vars(_globalConfig);
var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig);
container = _createHtmlBridge();
var divToBeReplaced = _document.createElement("div");
container.appendChild(divToBeReplaced);
_document.body.appendChild(container);
var tmpDiv = _document.createElement("div");
var oldIE = _flashState.pluginType === "activex";
tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>";
flashBridge = tmpDiv.firstChild;
tmpDiv = null;
flashBridge.ZeroClipboard = ZeroClipboard;
container.replaceChild(flashBridge, divToBeReplaced);
}
if (!flashBridge) {
flashBridge = _document[_globalConfig.swfObjectId];
if (flashBridge && (len = flashBridge.length)) {
flashBridge = flashBridge[len - 1];
}
if (!flashBridge && container) {
flashBridge = container.firstChild;
}
}
_flashState.bridge = flashBridge || null;
return flashBridge;
};
/**
* Destroy the SWF object.
* @private
*/
var _unembedSwf = function() {
var flashBridge = _flashState.bridge;
if (flashBridge) {
var htmlBridge = _getHtmlBridge(flashBridge);
if (htmlBridge) {
if (_flashState.pluginType === "activex" && "readyState" in flashBridge) {
flashBridge.style.display = "none";
(function removeSwfFromIE() {
if (flashBridge.readyState === 4) {
for (var prop in flashBridge) {
if (typeof flashBridge[prop] === "function") {
flashBridge[prop] = null;
}
}
if (flashBridge.parentNode) {
flashBridge.parentNode.removeChild(flashBridge);
}
if (htmlBridge.parentNode) {
htmlBridge.parentNode.removeChild(htmlBridge);
}
} else {
_setTimeout(removeSwfFromIE, 10);
}
})();
} else {
if (flashBridge.parentNode) {
flashBridge.parentNode.removeChild(flashBridge);
}
if (htmlBridge.parentNode) {
htmlBridge.parentNode.removeChild(htmlBridge);
}
}
}
_flashState.ready = null;
_flashState.bridge = null;
_flashState.deactivated = null;
}
};
/**
* Map the data format names of the "clipData" to Flash-friendly names.
*
* @returns A new transformed object.
* @private
*/
var _mapClipDataToFlash = function(clipData) {
var newClipData = {}, formatMap = {};
if (!(typeof clipData === "object" && clipData)) {
return;
}
for (var dataFormat in clipData) {
if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) {
switch (dataFormat.toLowerCase()) {
case "text/plain":
case "text":
case "air:text":
case "flash:text":
newClipData.text = clipData[dataFormat];
formatMap.text = dataFormat;
break;
case "text/html":
case "html":
case "air:html":
case "flash:html":
newClipData.html = clipData[dataFormat];
formatMap.html = dataFormat;
break;
case "application/rtf":
case "text/rtf":
case "rtf":
case "richtext":
case "air:rtf":
case "flash:rtf":
newClipData.rtf = clipData[dataFormat];
formatMap.rtf = dataFormat;
break;
default:
break;
}
}
}
return {
data: newClipData,
formatMap: formatMap
};
};
/**
* Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping).
*
* @returns A new transformed object.
* @private
*/
var _mapClipResultsFromFlash = function(clipResults, formatMap) {
if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) {
return clipResults;
}
var newResults = {};
for (var prop in clipResults) {
if (_hasOwn.call(clipResults, prop)) {
if (prop !== "success" && prop !== "data") {
newResults[prop] = clipResults[prop];
continue;
}
newResults[prop] = {};
var tmpHash = clipResults[prop];
for (var dataFormat in tmpHash) {
if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) {
newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat];
}
}
}
}
return newResults;
};
/**
* Will look at a path, and will create a "?noCache={time}" or "&noCache={time}"
* query param string to return. Does NOT append that string to the original path.
* This is useful because ExternalInterface often breaks when a Flash SWF is cached.
*
* @returns The `noCache` query param with necessary "?"/"&" prefix.
* @private
*/
var _cacheBust = function(path, options) {
var cacheBust = options == null || options && options.cacheBust === true;
if (cacheBust) {
return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now();
} else {
return "";
}
};
/**
* Creates a query string for the FlashVars param.
* Does NOT include the cache-busting query param.
*
* @returns FlashVars query string
* @private
*/
var _vars = function(options) {
var i, len, domain, domains, str = "", trustedOriginsExpanded = [];
if (options.trustedDomains) {
if (typeof options.trustedDomains === "string") {
domains = [ options.trustedDomains ];
} else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
domains = options.trustedDomains;
}
}
if (domains && domains.length) {
for (i = 0, len = domains.length; i < len; i++) {
if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") {
domain = _extractDomain(domains[i]);
if (!domain) {
continue;
}
if (domain === "*") {
trustedOriginsExpanded.length = 0;
trustedOriginsExpanded.push(domain);
break;
}
trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]);
}
}
}
if (trustedOriginsExpanded.length) {
str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(","));
}
if (options.forceEnhancedClipboard === true) {
str += (str ? "&" : "") + "forceEnhancedClipboard=true";
}
if (typeof options.swfObjectId === "string" && options.swfObjectId) {
str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId);
}
return str;
};
/**
* Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or
* URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/").
*
* @returns the domain
* @private
*/
var _extractDomain = function(originOrUrl) {
if (originOrUrl == null || originOrUrl === "") {
return null;
}
originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, "");
if (originOrUrl === "") {
return null;
}
var protocolIndex = originOrUrl.indexOf("//");
originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2);
var pathIndex = originOrUrl.indexOf("/");
originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex);
if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") {
return null;
}
return originOrUrl || null;
};
/**
* Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`.
*
* @returns The appropriate script access level.
* @private
*/
var _determineScriptAccess = function() {
var _extractAllDomains = function(origins) {
var i, len, tmp, resultsArray = [];
if (typeof origins === "string") {
origins = [ origins ];
}
if (!(typeof origins === "object" && origins && typeof origins.length === "number")) {
return resultsArray;
}
for (i = 0, len = origins.length; i < len; i++) {
if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) {
if (tmp === "*") {
resultsArray.length = 0;
resultsArray.push("*");
break;
}
if (resultsArray.indexOf(tmp) === -1) {
resultsArray.push(tmp);
}
}
}
return resultsArray;
};
return function(currentDomain, configOptions) {
var swfDomain = _extractDomain(configOptions.swfPath);
if (swfDomain === null) {
swfDomain = currentDomain;
}
var trustedDomains = _extractAllDomains(configOptions.trustedDomains);
var len = trustedDomains.length;
if (len > 0) {
if (len === 1 && trustedDomains[0] === "*") {
return "always";
}
if (trustedDomains.indexOf(currentDomain) !== -1) {
if (len === 1 && currentDomain === swfDomain) {
return "sameDomain";
}
return "always";
}
}
return "never";
};
}();
/**
* Get the currently active/focused DOM element.
*
* @returns the currently active/focused element, or `null`
* @private
*/
var _safeActiveElement = function() {
try {
return _document.activeElement;
} catch (err) {
return null;
}
};
/**
* Add a class to an element, if it doesn't already have it.
*
* @returns The element, with its new class added.
* @private
*/
var _addClass = function(element, value) {
if (!element || element.nodeType !== 1) {
return element;
}
if (element.classList) {
if (!element.classList.contains(value)) {
element.classList.add(value);
}
return element;
}
if (value && typeof value === "string") {
var classNames = (value || "").split(/\s+/);
if (element.nodeType === 1) {
if (!element.className) {
element.className = value;
} else {
var className = " " + element.className + " ", setClass = element.className;
for (var c = 0, cl = classNames.length; c < cl; c++) {
if (className.indexOf(" " + classNames[c] + " ") < 0) {
setClass += " " + classNames[c];
}
}
element.className = setClass.replace(/^\s+|\s+$/g, "");
}
}
}
return element;
};
/**
* Remove a class from an element, if it has it.
*
* @returns The element, with its class removed.
* @private
*/
var _removeClass = function(element, value) {
if (!element || element.nodeType !== 1) {
return element;
}
if (element.classList) {
if (element.classList.contains(value)) {
element.classList.remove(value);
}
return element;
}
if (typeof value === "string" && value) {
var classNames = value.split(/\s+/);
if (element.nodeType === 1 && element.className) {
var className = (" " + element.className + " ").replace(/[\n\t]/g, " ");
for (var c = 0, cl = classNames.length; c < cl; c++) {
className = className.replace(" " + classNames[c] + " ", " ");
}
element.className = className.replace(/^\s+|\s+$/g, "");
}
}
return element;
};
/**
* Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`,
* then we assume that it should be a hand ("pointer") cursor if the element
* is an anchor element ("a" tag).
*
* @returns The computed style property.
* @private
*/
var _getStyle = function(el, prop) {
var value = _window.getComputedStyle(el, null).getPropertyValue(prop);
if (prop === "cursor") {
if (!value || value === "auto") {
if (el.nodeName === "A") {
return "pointer";
}
}
}
return value;
};
/**
* Get the zoom factor of the browser. Always returns `1.0`, except at
* non-default zoom levels in IE<8 and some older versions of WebKit.
*
* @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`).
* @private
*/
var _getZoomFactor = function() {
var rect, physicalWidth, logicalWidth, zoomFactor = 1;
if (typeof _document.body.getBoundingClientRect === "function") {
rect = _document.body.getBoundingClientRect();
physicalWidth = rect.right - rect.left;
logicalWidth = _document.body.offsetWidth;
zoomFactor = _round(physicalWidth / logicalWidth * 100) / 100;
}
return zoomFactor;
};
/**
* Get the DOM positioning info of an element.
*
* @returns Object containing the element's position, width, and height.
* @private
*/
var _getDOMObjectPosition = function(obj) {
var info = {
left: 0,
top: 0,
width: 0,
height: 0
};
if (obj.getBoundingClientRect) {
var rect = obj.getBoundingClientRect();
var pageXOffset, pageYOffset, zoomFactor;
if ("pageXOffset" in _window && "pageYOffset" in _window) {
pageXOffset = _window.pageXOffset;
pageYOffset = _window.pageYOffset;
} else {
zoomFactor = _getZoomFactor();
pageXOffset = _round(_document.documentElement.scrollLeft / zoomFactor);
pageYOffset = _round(_document.documentElement.scrollTop / zoomFactor);
}
var leftBorderWidth = _document.documentElement.clientLeft || 0;
var topBorderWidth = _document.documentElement.clientTop || 0;
info.left = rect.left + pageXOffset - leftBorderWidth;
info.top = rect.top + pageYOffset - topBorderWidth;
info.width = "width" in rect ? rect.width : rect.right - rect.left;
info.height = "height" in rect ? rect.height : rect.bottom - rect.top;
}
return info;
};
/**
* Reposition the Flash object to cover the currently activated element.
*
* @returns `undefined`
* @private
*/
var _reposition = function() {
var htmlBridge;
if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) {
var pos = _getDOMObjectPosition(_currentElement);
_extend(htmlBridge.style, {
width: pos.width + "px",
height: pos.height + "px",
top: pos.top + "px",
left: pos.left + "px",
zIndex: "" + _getSafeZIndex(_globalConfig.zIndex)
});
}
};
/**
* Sends a signal to the Flash object to display the hand cursor if `true`.
*
* @returns `undefined`
* @private
*/
var _setHandCursor = function(enabled) {
if (_flashState.ready === true) {
if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") {
_flashState.bridge.setHandCursor(enabled);
} else {
_flashState.ready = false;
}
}
};
/**
* Get a safe value for `zIndex`
*
* @returns an integer, or "auto"
* @private
*/
var _getSafeZIndex = function(val) {
if (/^(?:auto|inherit)$/.test(val)) {
return val;
}
var zIndex;
if (typeof val === "number" && !_isNaN(val)) {
zIndex = val;
} else if (typeof val === "string") {
zIndex = _getSafeZIndex(_parseInt(val, 10));
}
return typeof zIndex === "number" ? zIndex : "auto";
};
/**
* Detect the Flash Player status, version, and plugin type.
*
* @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code}
* @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript}
*
* @returns `undefined`
* @private
*/
var _detectFlashSupport = function(ActiveXObject) {
var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = "";
/**
* Derived from Apple's suggested sniffer.
* @param {String} desc e.g. "Shockwave Flash 7.0 r61"
* @returns {String} "7.0.61"
* @private
*/
function parseFlashVersion(desc) {
var matches = desc.match(/[\d]+/g);
matches.length = 3;
return matches.join(".");
}
function isPepperFlash(flashPlayerFileName) {
return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin");
}
function inspectPlugin(plugin) {
if (plugin) {
hasFlash = true;
if (plugin.version) {
flashVersion = parseFlashVersion(plugin.version);
}
if (!flashVersion && plugin.description) {
flashVersion = parseFlashVersion(plugin.description);
}
if (plugin.filename) {
isPPAPI = isPepperFlash(plugin.filename);
}
}
}
if (_navigator.plugins && _navigator.plugins.length) {
plugin = _navigator.plugins["Shockwave Flash"];
inspectPlugin(plugin);
if (_navigator.plugins["Shockwave Flash 2.0"]) {
hasFlash = true;
flashVersion = "2.0.0.11";
}
} else if (_navigator.mimeTypes && _navigator.mimeTypes.length) {
mimeType = _navigator.mimeTypes["application/x-shockwave-flash"];
plugin = mimeType && mimeType.enabledPlugin;
inspectPlugin(plugin);
} else if (typeof ActiveXObject !== "undefined") {
isActiveX = true;
try {
ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
hasFlash = true;
flashVersion = parseFlashVersion(ax.GetVariable("$version"));
} catch (e1) {
try {
ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
hasFlash = true;
flashVersion = "6.0.21";
} catch (e2) {
try {
ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
hasFlash = true;
flashVersion = parseFlashVersion(ax.GetVariable("$version"));
} catch (e3) {
isActiveX = false;
}
}
}
}
_flashState.disabled = hasFlash !== true;
_flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion);
_flashState.version = flashVersion || "0.0.0";
_flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown";
};
/**
* Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later.
*/
_detectFlashSupport(_ActiveXObject);
/**
* A shell constructor for `ZeroClipboard` client instances.
*
* @constructor
*/
var ZeroClipboard = function() {
if (!(this instanceof ZeroClipboard)) {
return new ZeroClipboard();
}
if (typeof ZeroClipboard._createClient === "function") {
ZeroClipboard._createClient.apply(this, _args(arguments));
}
};
/**
* The ZeroClipboard library's version number.
*
* @static
* @readonly
* @property {string}
*/
_defineProperty(ZeroClipboard, "version", {
value: "2.1.4",
writable: false,
configurable: true,
enumerable: true
});
/**
* Update or get a copy of the ZeroClipboard global configuration.
* Returns a copy of the current/updated configuration.
*
* @returns Object
* @static
*/
ZeroClipboard.config = function() {
return _config.apply(this, _args(arguments));
};
/**
* Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard.
*
* @returns Object
* @static
*/
ZeroClipboard.state = function() {
return _state.apply(this, _args(arguments));
};
/**
* Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc.
*
* @returns Boolean
* @static
*/
ZeroClipboard.isFlashUnusable = function() {
return _isFlashUnusable.apply(this, _args(arguments));
};
/**
* Register an event listener.
*
* @returns `ZeroClipboard`
* @static
*/
ZeroClipboard.on = function() {
return _on.apply(this, _args(arguments));
};
/**
* Unregister an event listener.
* If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`.
* If no `eventType` is provided, it will unregister all listeners for every event type.
*
* @returns `ZeroClipboard`
* @static
*/
ZeroClipboard.off = function() {
return _off.apply(this, _args(arguments));
};
/**
* Retrieve event listeners for an `eventType`.
* If no `eventType` is provided, it will retrieve all listeners for every event type.
*
* @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null`
*/
ZeroClipboard.handlers = function() {
return _listeners.apply(this, _args(arguments));
};
/**
* Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners.
*
* @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`.
* @static
*/
ZeroClipboard.emit = function() {
return _emit.apply(this, _args(arguments));
};
/**
* Create and embed the Flash object.
*
* @returns The Flash object
* @static
*/
ZeroClipboard.create = function() {
return _create.apply(this, _args(arguments));
};
/**
* Self-destruct and clean up everything, including the embedded Flash object.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.destroy = function() {
return _destroy.apply(this, _args(arguments));
};
/**
* Set the pending data for clipboard injection.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.setData = function() {
return _setData.apply(this, _args(arguments));
};
/**
* Clear the pending data for clipboard injection.
* If no `format` is provided, all pending data formats will be cleared.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.clearData = function() {
return _clearData.apply(this, _args(arguments));
};
/**
* Get a copy of the pending data for clipboard injection.
* If no `format` is provided, a copy of ALL pending data formats will be returned.
*
* @returns `String` or `Object`
* @static
*/
ZeroClipboard.getData = function() {
return _getData.apply(this, _args(arguments));
};
/**
* Sets the current HTML object that the Flash object should overlay. This will put the global
* Flash object on top of the current element; depending on the setup, this may also set the
* pending clipboard text data as well as the Flash object's wrapping element's title attribute
* based on the underlying HTML element and ZeroClipboard configuration.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.focus = ZeroClipboard.activate = function() {
return _focus.apply(this, _args(arguments));
};
/**
* Un-overlays the Flash object. This will put the global Flash object off-screen; depending on
* the setup, this may also unset the Flash object's wrapping element's title attribute based on
* the underlying HTML element and ZeroClipboard configuration.
*
* @returns `undefined`
* @static
*/
ZeroClipboard.blur = ZeroClipboard.deactivate = function() {
return _blur.apply(this, _args(arguments));
};
/**
* Returns the currently focused/"activated" HTML element that the Flash object is wrapping.
*
* @returns `HTMLElement` or `null`
* @static
*/
ZeroClipboard.activeElement = function() {
return _activeElement.apply(this, _args(arguments));
};
/**
* Keep track of the ZeroClipboard client instance counter.
*/
var _clientIdCounter = 0;
/**
* Keep track of the state of the client instances.
*
* Entry structure:
* _clientMeta[client.id] = {
* instance: client,
* elements: [],
* handlers: {}
* };
*/
var _clientMeta = {};
/**
* Keep track of the ZeroClipboard clipped elements counter.
*/
var _elementIdCounter = 0;
/**
* Keep track of the state of the clipped element relationships to clients.
*
* Entry structure:
* _elementMeta[element.zcClippingId] = [client1.id, client2.id];
*/
var _elementMeta = {};
/**
* Keep track of the state of the mouse event handlers for clipped elements.
*
* Entry structure:
* _mouseHandlers[element.zcClippingId] = {
* mouseover: function(event) {},
* mouseout: function(event) {},
* mouseenter: function(event) {},
* mouseleave: function(event) {},
* mousemove: function(event) {}
* };
*/
var _mouseHandlers = {};
/**
* Extending the ZeroClipboard configuration defaults for the Client module.
*/
_extend(_globalConfig, {
autoActivate: true
});
/**
* The real constructor for `ZeroClipboard` client instances.
* @private
*/
var _clientConstructor = function(elements) {
var client = this;
client.id = "" + _clientIdCounter++;
_clientMeta[client.id] = {
instance: client,
elements: [],
handlers: {}
};
if (elements) {
client.clip(elements);
}
ZeroClipboard.on("*", function(event) {
return client.emit(event);
});
ZeroClipboard.on("destroy", function() {
client.destroy();
});
ZeroClipboard.create();
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.on`.
* @private
*/
var _clientOn = function(eventType, listener) {
var i, len, events, added = {}, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers;
if (typeof eventType === "string" && eventType) {
events = eventType.toLowerCase().split(/\s+/);
} else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
for (i in eventType) {
if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
this.on(i, eventType[i]);
}
}
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].replace(/^on/, "");
added[eventType] = true;
if (!handlers[eventType]) {
handlers[eventType] = [];
}
handlers[eventType].push(listener);
}
if (added.ready && _flashState.ready) {
this.emit({
type: "ready",
client: this
});
}
if (added.error) {
var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ];
for (i = 0, len = errorTypes.length; i < len; i++) {
if (_flashState[errorTypes[i]]) {
this.emit({
type: "error",
name: "flash-" + errorTypes[i],
client: this
});
break;
}
}
}
}
return this;
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.off`.
* @private
*/
var _clientOff = function(eventType, listener) {
var i, len, foundIndex, events, perEventHandlers, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers;
if (arguments.length === 0) {
events = _keys(handlers);
} else if (typeof eventType === "string" && eventType) {
events = eventType.split(/\s+/);
} else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
for (i in eventType) {
if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
this.off(i, eventType[i]);
}
}
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].toLowerCase().replace(/^on/, "");
perEventHandlers = handlers[eventType];
if (perEventHandlers && perEventHandlers.length) {
if (listener) {
foundIndex = perEventHandlers.indexOf(listener);
while (foundIndex !== -1) {
perEventHandlers.splice(foundIndex, 1);
foundIndex = perEventHandlers.indexOf(listener, foundIndex);
}
} else {
perEventHandlers.length = 0;
}
}
}
}
return this;
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.handlers`.
* @private
*/
var _clientListeners = function(eventType) {
var copy = null, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers;
if (handlers) {
if (typeof eventType === "string" && eventType) {
copy = handlers[eventType] ? handlers[eventType].slice(0) : [];
} else {
copy = _deepCopy(handlers);
}
}
return copy;
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.emit`.
* @private
*/
var _clientEmit = function(event) {
if (_clientShouldEmit.call(this, event)) {
if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
event = _extend({}, event);
}
var eventCopy = _extend({}, _createEvent(event), {
client: this
});
_clientDispatchCallbacks.call(this, eventCopy);
}
return this;
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.clip`.
* @private
*/
var _clientClip = function(elements) {
elements = _prepClip(elements);
for (var i = 0; i < elements.length; i++) {
if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) {
if (!elements[i].zcClippingId) {
elements[i].zcClippingId = "zcClippingId_" + _elementIdCounter++;
_elementMeta[elements[i].zcClippingId] = [ this.id ];
if (_globalConfig.autoActivate === true) {
_addMouseHandlers(elements[i]);
}
} else if (_elementMeta[elements[i].zcClippingId].indexOf(this.id) === -1) {
_elementMeta[elements[i].zcClippingId].push(this.id);
}
var clippedElements = _clientMeta[this.id] && _clientMeta[this.id].elements;
if (clippedElements.indexOf(elements[i]) === -1) {
clippedElements.push(elements[i]);
}
}
}
return this;
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.unclip`.
* @private
*/
var _clientUnclip = function(elements) {
var meta = _clientMeta[this.id];
if (!meta) {
return this;
}
var clippedElements = meta.elements;
var arrayIndex;
if (typeof elements === "undefined") {
elements = clippedElements.slice(0);
} else {
elements = _prepClip(elements);
}
for (var i = elements.length; i--; ) {
if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) {
arrayIndex = 0;
while ((arrayIndex = clippedElements.indexOf(elements[i], arrayIndex)) !== -1) {
clippedElements.splice(arrayIndex, 1);
}
var clientIds = _elementMeta[elements[i].zcClippingId];
if (clientIds) {
arrayIndex = 0;
while ((arrayIndex = clientIds.indexOf(this.id, arrayIndex)) !== -1) {
clientIds.splice(arrayIndex, 1);
}
if (clientIds.length === 0) {
if (_globalConfig.autoActivate === true) {
_removeMouseHandlers(elements[i]);
}
delete elements[i].zcClippingId;
}
}
}
}
return this;
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.elements`.
* @private
*/
var _clientElements = function() {
var meta = _clientMeta[this.id];
return meta && meta.elements ? meta.elements.slice(0) : [];
};
/**
* The underlying implementation of `ZeroClipboard.Client.prototype.destroy`.
* @private
*/
var _clientDestroy = function() {
this.unclip();
this.off();
delete _clientMeta[this.id];
};
/**
* Inspect an Event to see if the Client (`this`) should honor it for emission.
* @private
*/
var _clientShouldEmit = function(event) {
if (!(event && event.type)) {
return false;
}
if (event.client && event.client !== this) {
return false;
}
var clippedEls = _clientMeta[this.id] && _clientMeta[this.id].elements;
var hasClippedEls = !!clippedEls && clippedEls.length > 0;
var goodTarget = !event.target || hasClippedEls && clippedEls.indexOf(event.target) !== -1;
var goodRelTarget = event.relatedTarget && hasClippedEls && clippedEls.indexOf(event.relatedTarget) !== -1;
var goodClient = event.client && event.client === this;
if (!(goodTarget || goodRelTarget || goodClient)) {
return false;
}
return true;
};
/**
* Handle the actual dispatching of events to a client instance.
*
* @returns `this`
* @private
*/
var _clientDispatchCallbacks = function(event) {
if (!(typeof event === "object" && event && event.type)) {
return;
}
var async = _shouldPerformAsync(event);
var wildcardTypeHandlers = _clientMeta[this.id] && _clientMeta[this.id].handlers["*"] || [];
var specificTypeHandlers = _clientMeta[this.id] && _clientMeta[this.id].handlers[event.type] || [];
var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
if (handlers && handlers.length) {
var i, len, func, context, eventCopy, originalContext = this;
for (i = 0, len = handlers.length; i < len; i++) {
func = handlers[i];
context = originalContext;
if (typeof func === "string" && typeof _window[func] === "function") {
func = _window[func];
}
if (typeof func === "object" && func && typeof func.handleEvent === "function") {
context = func;
func = func.handleEvent;
}
if (typeof func === "function") {
eventCopy = _extend({}, event);
_dispatchCallback(func, context, [ eventCopy ], async);
}
}
}
return this;
};
/**
* Prepares the elements for clipping/unclipping.
*
* @returns An Array of elements.
* @private
*/
var _prepClip = function(elements) {
if (typeof elements === "string") {
elements = [];
}
return typeof elements.length !== "number" ? [ elements ] : elements;
};
/**
* Add a `mouseover` handler function for a clipped element.
*
* @returns `undefined`
* @private
*/
var _addMouseHandlers = function(element) {
if (!(element && element.nodeType === 1)) {
return;
}
var _suppressMouseEvents = function(event) {
if (!(event || (event = _window.event))) {
return;
}
if (event._source !== "js") {
event.stopImmediatePropagation();
event.preventDefault();
}
delete event._source;
};
var _elementMouseOver = function(event) {
if (!(event || (event = _window.event))) {
return;
}
_suppressMouseEvents(event);
ZeroClipboard.focus(element);
};
element.addEventListener("mouseover", _elementMouseOver, false);
element.addEventListener("mouseout", _suppressMouseEvents, false);
element.addEventListener("mouseenter", _suppressMouseEvents, false);
element.addEventListener("mouseleave", _suppressMouseEvents, false);
element.addEventListener("mousemove", _suppressMouseEvents, false);
_mouseHandlers[element.zcClippingId] = {
mouseover: _elementMouseOver,
mouseout: _suppressMouseEvents,
mouseenter: _suppressMouseEvents,
mouseleave: _suppressMouseEvents,
mousemove: _suppressMouseEvents
};
};
/**
* Remove a `mouseover` handler function for a clipped element.
*
* @returns `undefined`
* @private
*/
var _removeMouseHandlers = function(element) {
if (!(element && element.nodeType === 1)) {
return;
}
var mouseHandlers = _mouseHandlers[element.zcClippingId];
if (!(typeof mouseHandlers === "object" && mouseHandlers)) {
return;
}
var key, val, mouseEvents = [ "move", "leave", "enter", "out", "over" ];
for (var i = 0, len = mouseEvents.length; i < len; i++) {
key = "mouse" + mouseEvents[i];
val = mouseHandlers[key];
if (typeof val === "function") {
element.removeEventListener(key, val, false);
}
}
delete _mouseHandlers[element.zcClippingId];
};
/**
* Creates a new ZeroClipboard client instance.
* Optionally, auto-`clip` an element or collection of elements.
*
* @constructor
*/
ZeroClipboard._createClient = function() {
_clientConstructor.apply(this, _args(arguments));
};
/**
* Register an event listener to the client.
*
* @returns `this`
*/
ZeroClipboard.prototype.on = function() {
return _clientOn.apply(this, _args(arguments));
};
/**
* Unregister an event handler from the client.
* If no `listener` function/object is provided, it will unregister all handlers for the provided `eventType`.
* If no `eventType` is provided, it will unregister all handlers for every event type.
*
* @returns `this`
*/
ZeroClipboard.prototype.off = function() {
return _clientOff.apply(this, _args(arguments));
};
/**
* Retrieve event listeners for an `eventType` from the client.
* If no `eventType` is provided, it will retrieve all listeners for every event type.
*
* @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null`
*/
ZeroClipboard.prototype.handlers = function() {
return _clientListeners.apply(this, _args(arguments));
};
/**
* Event emission receiver from the Flash object for this client's registered JavaScript event listeners.
*
* @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`.
*/
ZeroClipboard.prototype.emit = function() {
return _clientEmit.apply(this, _args(arguments));
};
/**
* Register clipboard actions for new element(s) to the client.
*
* @returns `this`
*/
ZeroClipboard.prototype.clip = function() {
return _clientClip.apply(this, _args(arguments));
};
/**
* Unregister the clipboard actions of previously registered element(s) on the page.
* If no elements are provided, ALL registered elements will be unregistered.
*
* @returns `this`
*/
ZeroClipboard.prototype.unclip = function() {
return _clientUnclip.apply(this, _args(arguments));
};
/**
* Get all of the elements to which this client is clipped.
*
* @returns array of clipped elements
*/
ZeroClipboard.prototype.elements = function() {
return _clientElements.apply(this, _args(arguments));
};
/**
* Self-destruct and clean up everything for a single client.
* This will NOT destroy the embedded Flash object.
*
* @returns `undefined`
*/
ZeroClipboard.prototype.destroy = function() {
return _clientDestroy.apply(this, _args(arguments));
};
/**
* Stores the pending plain text to inject into the clipboard.
*
* @returns `this`
*/
ZeroClipboard.prototype.setText = function(text) {
ZeroClipboard.setData("text/plain", text);
return this;
};
/**
* Stores the pending HTML text to inject into the clipboard.
*
* @returns `this`
*/
ZeroClipboard.prototype.setHtml = function(html) {
ZeroClipboard.setData("text/html", html);
return this;
};
/**
* Stores the pending rich text (RTF) to inject into the clipboard.
*
* @returns `this`
*/
ZeroClipboard.prototype.setRichText = function(richText) {
ZeroClipboard.setData("application/rtf", richText);
return this;
};
/**
* Stores the pending data to inject into the clipboard.
*
* @returns `this`
*/
ZeroClipboard.prototype.setData = function() {
ZeroClipboard.setData.apply(this, _args(arguments));
return this;
};
/**
* Clears the pending data to inject into the clipboard.
* If no `format` is provided, all pending data formats will be cleared.
*
* @returns `this`
*/
ZeroClipboard.prototype.clearData = function() {
ZeroClipboard.clearData.apply(this, _args(arguments));
return this;
};
/**
* Gets a copy of the pending data to inject into the clipboard.
* If no `format` is provided, a copy of ALL pending data formats will be returned.
*
* @returns `String` or `Object`
*/
ZeroClipboard.prototype.getData = function() {
return ZeroClipboard.getData.apply(this, _args(arguments));
};
if (typeof define === "function" && define.amd) {
define(function() {
return ZeroClipboard;
});
} else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) {
module.exports = ZeroClipboard;
} else {
window.ZeroClipboard = ZeroClipboard;
}
})(function() {
return this || window;
}()); |
src/steps/SizeStep.js | scott113341/post | import React, { createElement as r } from 'react';
import { Link, Spacer, Step } from '../components/index.js';
import { formatPrice } from '../util.js';
export default class SizeStep extends React.Component {
render () {
const size = this.props.postcard.size;
const disabled = !this.isValid();
return r(Step, { title: 'postcard size' },
r('select', { value: size.selectedIndex, onChange: this.handleSizeSelectChange.bind(this) },
size.sizes.map((sizeOption, index) => {
return r('option', { key: index, value: index },
`${sizeOption.display} - ${formatPrice(sizeOption.price)}`
);
})
),
r(Spacer),
r(Link, { onClick: () => this.props.goToStep('back') }, 'back'),
r(Link, { onClick: () => this.props.goToStep('next'), disabled }, 'next')
);
}
isValid () {
return this.props.postcard.size.selectedIndex >= 0;
}
handleSizeSelectChange (e) {
this.props.changeSelectedSize(e.target.value);
}
}
|
ajax/libs/analytics.js/1.3.8/analytics.min.js | rigdern/cdnjs | (function(){function require(path,parent,orig){var resolved=require.resolve(path);if(null==resolved){orig=orig||path;parent=parent||"root";var err=new Error('Failed to require "'+orig+'" from "'+parent+'"');err.path=orig;err.parent=parent;err.require=true;throw err}var module=require.modules[resolved];if(!module._resolving&&!module.exports){var mod={};mod.exports={};mod.client=mod.component=true;module._resolving=true;module.call(this,mod.exports,require.relative(resolved),mod);delete module._resolving;module.exports=mod.exports}return module.exports}require.modules={};require.aliases={};require.resolve=function(path){if(path.charAt(0)==="/")path=path.slice(1);var paths=[path,path+".js",path+".json",path+"/index.js",path+"/index.json"];for(var i=0;i<paths.length;i++){var path=paths[i];if(require.modules.hasOwnProperty(path))return path;if(require.aliases.hasOwnProperty(path))return require.aliases[path]}};require.normalize=function(curr,path){var segs=[];if("."!=path.charAt(0))return path;curr=curr.split("/");path=path.split("/");for(var i=0;i<path.length;++i){if(".."==path[i]){curr.pop()}else if("."!=path[i]&&""!=path[i]){segs.push(path[i])}}return curr.concat(segs).join("/")};require.register=function(path,definition){require.modules[path]=definition};require.alias=function(from,to){if(!require.modules.hasOwnProperty(from)){throw new Error('Failed to alias "'+from+'", it does not exist')}require.aliases[to]=from};require.relative=function(parent){var p=require.normalize(parent,"..");function lastIndexOf(arr,obj){var i=arr.length;while(i--){if(arr[i]===obj)return i}return-1}function localRequire(path){var resolved=localRequire.resolve(path);return require(resolved,parent,path)}localRequire.resolve=function(path){var c=path.charAt(0);if("/"==c)return path.slice(1);if("."==c)return require.normalize(p,path);var segs=parent.split("/");var i=lastIndexOf(segs,"deps")+1;if(!i)i=0;path=segs.slice(0,i+1).join("/")+"/deps/"+path;return path};localRequire.exists=function(path){return require.modules.hasOwnProperty(localRequire.resolve(path))};return localRequire};require.register("avetisk-defaults/index.js",function(exports,require,module){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults});require.register("component-type/index.js",function(exports,require,module){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}});require.register("component-clone/index.js",function(exports,require,module){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}});require.register("component-cookie/index.js",function(exports,require,module){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}});require.register("component-each/index.js",function(exports,require,module){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}});require.register("component-indexof/index.js",function(exports,require,module){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}});require.register("component-emitter/index.js",function(exports,require,module){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}});require.register("component-event/index.js",function(exports,require,module){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}});require.register("component-inherit/index.js",function(exports,require,module){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}});require.register("component-object/index.js",function(exports,require,module){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}});require.register("component-trim/index.js",function(exports,require,module){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}});require.register("component-querystring/index.js",function(exports,require,module){var trim=require("trim");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");obj[parts[0]]=null==parts[1]?"":decodeURIComponent(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]))}return pairs.join("&")}});require.register("component-url/index.js",function(exports,require,module){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}});require.register("component-bind/index.js",function(exports,require,module){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}});require.register("segmentio-bind-all/index.js",function(exports,require,module){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}});require.register("ianstormtaylor-bind/index.js",function(exports,require,module){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}});require.register("timoxley-next-tick/index.js",function(exports,require,module){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}});require.register("ianstormtaylor-callback/index.js",function(exports,require,module){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback});require.register("ianstormtaylor-is-empty/index.js",function(exports,require,module){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}});require.register("ianstormtaylor-is/index.js",function(exports,require,module){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}});require.register("segmentio-after/index.js",function(exports,require,module){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}});require.register("yields-slug/index.js",function(exports,require,module){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}});require.register("segmentio-analytics.js-integration/lib/index.js",function(exports,require,module){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this._wrapInitialize();this._wrapLoad();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}});require.register("segmentio-analytics.js-integration/lib/protos.js",function(exports,require,module){var after=require("after");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var events=require("./events");Emitter(exports);exports.initialize=function(){this.load()};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);try{this.debug("%s with %o",method,args);this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;initialize.apply(this,arguments);this.emit("initialize");var self=this;if(this._readyOnInitialize){tick(function(){self.emit("ready")})}};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapLoad=function(){var load=this.load;this.load=function(callback){var self=this;this.debug("loading");if(this.loaded()){this.debug("already loaded");tick(function(){if(self._readyOnLoad)self.emit("ready");callback&&callback()});return}load.call(this,function(err,e){self.debug("loaded");self.emit("load");if(self._readyOnLoad)self.emit("ready");callback&&callback(err,e)})}};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize({category:arguments[0],name:arguments[1],properties:arguments[2],options:arguments[3]})}page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;this[method].apply(this,arguments);called=true;break}if(!called)t.apply(this,arguments)}}});require.register("segmentio-analytics.js-integration/lib/events.js",function(exports,require,module){module.exports={removedProduct:/removed product/i,viewedProduct:/viewed product/i,addedProduct:/added product/i,completedOrder:/completed order/i}});require.register("segmentio-analytics.js-integration/lib/statics.js",function(exports,require,module){var after=require("after");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this}});require.register("component-domify/index.js",function(exports,require,module){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}});require.register("component-once/index.js",function(exports,require,module){var n=0;var global=function(){return this}();module.exports=function(fn){var id=n++;function once(){if(this==global){if(once.called)return;once.called=true;return fn.apply(this,arguments)}var key="__called_"+id+"__";if(this[key])return;this[key]=true;return fn.apply(this,arguments)}return once}});require.register("segmentio-alias/index.js",function(exports,require,module){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}});require.register("segmentio-convert-dates/index.js",function(exports,require,module){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}});require.register("segmentio-global-queue/index.js",function(exports,require,module){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}});require.register("segmentio-load-date/index.js",function(exports,require,module){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time});require.register("segmentio-load-script/index.js",function(exports,require,module){var type=require("type");module.exports=function loadScript(options,callback){if(!options)throw new Error("Cant load nothing...");if(type(options)==="string")options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript);if(callback&&type(callback)==="function"){if(script.addEventListener){script.addEventListener("load",function(event){callback(null,event)},false);script.addEventListener("error",function(event){callback(new Error("Failed to load the script."),event)},false)}else if(script.attachEvent){script.attachEvent("onreadystatechange",function(event){if(/complete|loaded/.test(script.readyState)){callback(null,event)}})}}return script}});require.register("segmentio-on-body/index.js",function(exports,require,module){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}});require.register("segmentio-on-error/index.js",function(exports,require,module){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}});require.register("segmentio-to-iso-string/index.js",function(exports,require,module){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}});require.register("segmentio-to-unix-timestamp/index.js",function(exports,require,module){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}});require.register("segmentio-use-https/index.js",function(exports,require,module){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}});require.register("visionmedia-batch/index.js",function(exports,require,module){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}});require.register("segmentio-substitute/index.js",function(exports,require,module){module.exports=substitute;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){return null!=obj[prop]?obj[prop]:_})}});require.register("segmentio-load-pixel/index.js",function(exports,require,module){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}});require.register("segmentio-analytics.js-integrations/index.js",function(exports,require,module){var integrations=require("./lib/slugs");var each=require("each");each(integrations,function(slug){var plugin=require("./lib/"+slug);var name=plugin.Integration.prototype.name;exports[name]=plugin})});require.register("segmentio-analytics.js-integrations/lib/adroll.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(AdRoll);user=analytics.user()};var AdRoll=exports.Integration=integration("AdRoll").assumesPageview().readyOnLoad().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;if(user.id())window.adroll_custom_data={USER_ID:user.id()};window.__adroll_loaded=true;this.load()};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.load=function(callback){load({http:"http://a.adroll.com/j/roundtrip.js",https:"https://s.adroll.com/j/roundtrip.js"},callback)}});require.register("segmentio-analytics.js-integrations/lib/adwords.js",function(exports,require,module){var onbody=require("on-body");var integration=require("integration");var load=require("load-script");var domify=require("domify");module.exports=exports=function(analytics){analytics.addIntegration(AdWords)};var has=Object.prototype.hasOwnProperty;var AdWords=exports.Integration=integration("AdWords").readyOnLoad().option("conversionId","").option("events",{});AdWords.prototype.load=function(fn){onbody(fn)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.options.events;var event=track.event();if(!has.call(events,event))return;return this.conversion({value:track.revenue()||0,label:events[event],conversionId:id})};AdWords.prototype.conversion=function(obj,fn){if(this.reporting)return this.wait(obj);this.reporting=true;this.debug("sending %o",obj);var self=this;var write=document.write;document.write=append;window.google_conversion_id=obj.conversionId;window.google_conversion_language="en";window.google_conversion_format="3";window.google_conversion_color="ffffff";window.google_conversion_label=obj.label;window.google_conversion_value=obj.value;window.google_remarketing_only=false;load("//www.googleadservices.com/pagead/conversion.js",fn);function append(str){var el=domify(str);if(!el.src)return write(str);if(!/googleadservices/.test(el.src))return write(str);self.debug("append %o",el);document.body.appendChild(el);document.write=write;self.reporting=null}};AdWords.prototype.wait=function(obj){var self=this;var id=setTimeout(function(){clearTimeout(id);self.conversion(obj)},50)}});require.register("segmentio-analytics.js-integrations/lib/amplitude.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Amplitude)};var Amplitude=exports.Integration=integration("Amplitude").assumesPageview().readyOnInitialize().global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true);Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load()};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.load=function(callback){load("https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js",callback)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}});require.register("segmentio-analytics.js-integrations/lib/awesm.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Awesm);user=analytics.user()};var Awesm=exports.Integration=integration("awe.sm").assumesPageview().readyOnLoad().global("AWESM").option("apiKey","").option("events",{});Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load()};Awesm.prototype.loaded=function(){return!!window.AWESM._exists};Awesm.prototype.load=function(callback){var key=this.options.apiKey;load("//widgets.awe.sm/v3/widgets.js?key="+key+"&async=true",callback)};Awesm.prototype.track=function(track){var event=track.event();var goal=this.options.events[event];if(!goal)return;window.AWESM.convert(goal,track.cents(),null,user.id())}});require.register("segmentio-analytics.js-integrations/lib/awesomatic.js",function(exports,require,module){var integration=require("integration");
var is=require("is");var load=require("load-script");var noop=function(){};var onBody=require("on-body");var user;module.exports=exports=function(analytics){analytics.addIntegration(Awesomatic);user=analytics.user()};var Awesomatic=exports.Integration=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","");Awesomatic.prototype.initialize=function(page){var self=this;var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.emit("ready")})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)};Awesomatic.prototype.load=function(callback){var url="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js";load(url,callback)}});require.register("segmentio-analytics.js-integrations/lib/bing-ads.js",function(exports,require,module){var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(Bing)};var has=Object.prototype.hasOwnProperty;var Bing=exports.Integration=integration("Bing Ads").readyOnInitialize().option("siteId","").option("domainId","").option("goals",{});Bing.prototype.track=function(track){var goals=this.options.goals;var traits=track.traits();var event=track.event();if(!has.call(goals,event))return;var goal=goals[event];return exports.load(goal,track.revenue(),this.options)};exports.load=function(goal,revenue,options){var iframe=document.createElement("iframe");iframe.src="//flex.msn.com/mstag/tag/"+options.siteId+"/analytics.html"+"?domainId="+options.domainId+"&revenue="+revenue||0+"&actionid="+goal;+"&dedup=1"+"&type=1";iframe.width=1;iframe.height=1;return iframe}});require.register("segmentio-analytics.js-integrations/lib/bronto.js",function(exports,require,module){var integration=require("integration");var Track=require("facade").Track;var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(Bronto)};var Bronto=exports.Integration=integration("Bronto").readyOnLoad().global("__bta").option("siteId","").option("host","");Bronto.prototype.initialize=function(page){this.load()};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.load=function(fn){var self=this;load("//p.bm23.com/bta.js",function(err){if(err)return fn(err);var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);fn()})};Bronto.prototype.track=function(track){var revenue=track.revenue();var event=track.event();var type="number"==typeof revenue?"$":"t";this.bta.addConversionLegacy(type,event,revenue)};Bronto.prototype.completedOrder=function(track){var products=track.products();var props=track.properties();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addConversion({order_id:track.orderId(),date:props.date||new Date,items:items})}});require.register("segmentio-analytics.js-integrations/lib/bugherd.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(BugHerd)};var BugHerd=exports.Integration=integration("BugHerd").assumesPageview().readyOnLoad().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true);BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};this.load()};BugHerd.prototype.loaded=function(){return!!window._bugHerd};BugHerd.prototype.load=function(callback){load("//www.bugherd.com/sidebarv2.js?apikey="+this.options.apiKey,callback)}});require.register("segmentio-analytics.js-integrations/lib/bugsnag.js",function(exports,require,module){var integration=require("integration");var is=require("is");var extend=require("extend");var load=require("load-script");var onError=require("on-error");module.exports=exports=function(analytics){analytics.addIntegration(Bugsnag)};var Bugsnag=exports.Integration=integration("Bugsnag").readyOnLoad().global("Bugsnag").option("apiKey","");Bugsnag.prototype.initialize=function(page){this.load()};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.load=function(callback){var apiKey=this.options.apiKey;load("//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js",function(err){if(err)return callback(err);window.Bugsnag.apiKey=apiKey;callback()})};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}});require.register("segmentio-analytics.js-integrations/lib/chartbeat.js",function(exports,require,module){var integration=require("integration");var onBody=require("on-body");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Chartbeat)};var Chartbeat=exports.Integration=integration("Chartbeat").assumesPageview().readyOnLoad().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null);Chartbeat.prototype.initialize=function(page){window._sf_async_config=this.options;onBody(function(){window._sf_endpt=(new Date).getTime()});this.load()};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.load=function(callback){load({https:"https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js",http:"http://static.chartbeat.com/js/chartbeat.js"},callback)};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}});require.register("segmentio-analytics.js-integrations/lib/churnbee.js",function(exports,require,module){var push=require("global-queue")("_cbq");var integration=require("integration");var load=require("load-script");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};module.exports=exports=function(analytics){analytics.addIntegration(ChurnBee)};var ChurnBee=exports.Integration=integration("ChurnBee").readyOnInitialize().global("_cbq").global("ChurnBee").option("events",{}).option("apiKey","");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load()};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.load=function(fn){load("//api.churnbee.com/cb.js",fn)};ChurnBee.prototype.track=function(track){var events=this.options.events;var event=track.event();if(has.call(events,event))event=events[event];if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))}});require.register("segmentio-analytics.js-integrations/lib/clicktale.js",function(exports,require,module){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("integration");var is=require("is");var useHttps=require("use-https");var load=require("load-script");var onBody=require("on-body");module.exports=exports=function(analytics){analytics.addIntegration(ClickTale)};var ClickTale=exports.Integration=integration("ClickTale").assumesPageview().readyOnLoad().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","");ClickTale.prototype.initialize=function(page){var options=this.options;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});this.load(function(){window.ClickTale(options.projectId,options.recordingRatio,options.partitionId)})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.load=function(callback){var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");load({http:http,https:https},callback)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}});require.register("segmentio-analytics.js-integrations/lib/clicky.js",function(exports,require,module){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("integration");var is=require("is");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Clicky);user=analytics.user()};var Clicky=exports.Integration=integration("Clicky").assumesPageview().readyOnLoad().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null);Clicky.prototype.initialize=function(page){window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load()};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.load=function(callback){load("//static.getclicky.com/js",callback)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}});require.register("segmentio-analytics.js-integrations/lib/comscore.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Comscore)};var Comscore=exports.Integration=integration("comScore").assumesPageview().readyOnLoad().global("_comscore").global("COMSCORE").option("c1","2").option("c2","");Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];this.load()};Comscore.prototype.loaded=function(){return!!window.COMSCORE};Comscore.prototype.load=function(callback){load({http:"http://b.scorecardresearch.com/beacon.js",https:"https://sb.scorecardresearch.com/beacon.js"},callback)}});require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(CrazyEgg)};var CrazyEgg=exports.Integration=integration("Crazy Egg").assumesPageview().readyOnLoad().global("CE2").option("accountNumber","");CrazyEgg.prototype.initialize=function(page){this.load()};CrazyEgg.prototype.loaded=function(){return!!window.CE2};CrazyEgg.prototype.load=function(callback){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);var url="//dnn506yrbagrg.cloudfront.net/pages/scripts/"+path+".js?"+cache;load(url,callback)}});require.register("segmentio-analytics.js-integrations/lib/curebit.js",function(exports,require,module){var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var integration=require("integration");var Track=require("facade").Track;var iso=require("to-iso-string");var load=require("load-script");var extend=require("extend");var clone=require("clone");var each=require("each");var user;module.exports=exports=function(analytics){analytics.addIntegration(Curebit);user=analytics.user()};var Curebit=exports.Integration=integration("Curebit").readyOnInitialize().global("_curebitq").global("curebit").option("siteId","").option("iframeWidth",0).option("iframeHeight",0).option("iframeBorder",0).option("iframeId","").option("responsive",true).option("device","").option("server","https://www.curebit.com");Curebit.prototype.initialize=function(){push("init",{site_id:this.options.siteId,server:this.options.server});this.load()};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.load=function(fn){load("//d2jjzw81hqbuqv.cloudfront.net/assets/api/all-0.6.js",fn)};Curebit.prototype.identify=function(identify){push("register_affiliate",{responsive:this.options.responsive,device:this.options.device,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder},affiliate_member:{email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}})};Curebit.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}});require.register("segmentio-analytics.js-integrations/lib/customerio.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Customerio);user=analytics.user()};var Customerio=exports.Integration=integration("Customer.io").assumesPageview().readyOnInitialize().global("_cio").option("siteId","");Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load()};Customerio.prototype.loaded=function(){return!!(window._cio&&window._cio.pageHasLoaded)};Customerio.prototype.load=function(callback){var script=load("https://assets.customer.io/assets/track.js",callback);script.id="cio-tracker";script.setAttribute("data-site-id",this.options.siteId)};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}});require.register("segmentio-analytics.js-integrations/lib/drip.js",function(exports,require,module){var alias=require("alias");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");module.exports=exports=function(analytics){analytics.addIntegration(Drip)};var Drip=exports.Integration=integration("Drip").assumesPageview().readyOnLoad().global("dc").global("_dcq").global("_dcs").option("account","");Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load()};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.load=function(callback){load("//tag.getdrip.com/"+this.options.account+".js",callback)};Drip.prototype.track=function(track){var props=track.properties();var cents=Math.round(track.cents());props.action=track.event();if(cents)props.value=cents;delete props.revenue;push("track",props)}});require.register("segmentio-analytics.js-integrations/lib/errorception.js",function(exports,require,module){var callback=require("callback");var extend=require("extend");var integration=require("integration");var load=require("load-script");var onError=require("on-error");var push=require("global-queue")("_errs");module.exports=exports=function(analytics){analytics.addIntegration(Errorception)};var Errorception=exports.Integration=integration("Errorception").assumesPageview().readyOnInitialize().global("_errs").option("projectId","").option("meta",true);Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load()};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.load=function(callback){load("//beacon.errorception.com/"+this.options.projectId+".js",callback)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}});require.register("segmentio-analytics.js-integrations/lib/evergage.js",function(exports,require,module){var each=require("each");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_aaq");module.exports=exports=function(analytics){analytics.addIntegration(Evergage)};var Evergage=exports.Integration=integration("Evergage").assumesPageview().readyOnInitialize().global("_aaq").option("account","").option("dataset","");Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load()};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.load=function(callback){var account=this.options.account;var dataset=this.options.dataset;var url="//cdn.evergage.com/beacon/"+account+"/"+dataset+"/scripts/evergage.min.js";load(url,callback)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js",function(exports,require,module){var load=require("load-pixel")("//www.facebook.com/offsite_event.php");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(Facebook)};exports.load=load;var has=Object.prototype.hasOwnProperty;var Facebook=exports.Integration=integration("Facebook Ads").readyOnInitialize().option("currency","USD").option("events",{});Facebook.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();if(!has.call(events,event))return;return exports.load({currency:this.options.currency,value:track.revenue()||0,id:events[event]})}});require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js",function(exports,require,module){var push=require("global-queue")("_fxm");var integration=require("integration");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(FoxMetrics)};var FoxMetrics=exports.Integration=integration("FoxMetrics").assumesPageview().readyOnInitialize().global("_fxm").option("appId","");FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load()};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.load=function(callback){var id=this.options.appId;load("//d35tca7vmefkrc.cloudfront.net/scripts/"+id+".js",callback)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}});require.register("segmentio-analytics.js-integrations/lib/gauges.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_gauges");module.exports=exports=function(analytics){analytics.addIntegration(Gauges)};var Gauges=exports.Integration=integration("Gauges").assumesPageview().readyOnInitialize().global("_gauges").option("siteId","");Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load()};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.load=function(callback){var id=this.options.siteId;var script=load("//secure.gaug.es/track.js",callback);script.id="gauges-tracker";script.setAttribute("data-site-id",id)};Gauges.prototype.page=function(page){push("track")}});require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var onBody=require("on-body");module.exports=exports=function(analytics){analytics.addIntegration(GetSatisfaction)};var GetSatisfaction=exports.Integration=integration("Get Satisfaction").assumesPageview().readyOnLoad().global("GSFN").option("widgetId","");GetSatisfaction.prototype.initialize=function(page){var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id})})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN};GetSatisfaction.prototype.load=function(callback){load("https://loader.engage.gsfn.us/loader.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/google-analytics.js",function(exports,require,module){var callback=require("callback");var canonical=require("canonical");var each=require("each");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_gaq");var Track=require("facade").Track;var type=require("type");var url=require("url");var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoreReferrer",null).option("includeSearch",false).option("siteSpeedSampleRate",null).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false);GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.load=integration.loadClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(this.options.sendUserId&&user.id()){window.ga("set","&uid",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);this.load()};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.load=function(callback){load("//www.google-analytics.com/analytics.js",callback)};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();window.ga("send","event",{eventAction:event,eventCategory:this._category||props.category||"All",eventLabel:props.label,eventValue:formatValue(props.value||revenue),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce","ecommerce.js");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:track.total(),tax:track.tax(),id:orderId});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoreReferrer;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}this.load()};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.loadClassic=function(callback){if(this.options.doubleClick){load("//stats.g.doubleclick.net/dc.js",callback)}else{load({http:"http://www.google-analytics.com/ga.js",https:"https://ssl.google-analytics.com/ga.js"},callback)}};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var orderId=track.orderId();var products=track.products()||[];var props=track.properties();if(!orderId)return;push("_addTrans",orderId,props.affiliation,track.total(),track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}});require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js",function(exports,require,module){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(GTM)};var GTM=exports.Integration=integration("Google Tag Manager").assumesPageview().readyOnLoad().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true);GTM.prototype.initialize=function(){this.load()};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.load=function(fn){var id=this.options.containerId;push({"gtm.start":+new Date,event:"gtm.js"});load("//www.googletagmanager.com/gtm.js?id="+id+"&l=dataLayer",fn)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}});require.register("segmentio-analytics.js-integrations/lib/gosquared.js",function(exports,require,module){var Identify=require("facade").Identify;var Track=require("facade").Track;
var callback=require("callback");var integration=require("integration");var load=require("load-script");var onBody=require("on-body");var each=require("each");var user;module.exports=exports=function(analytics){analytics.addIntegration(GoSquared);user=analytics.user()};var GoSquared=exports.Integration=integration("GoSquared").assumesPageview().readyOnLoad().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true);GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load()};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.load=function(callback){load("//d1l6p2sc9645hc.cloudfront.net/tracker.js",callback)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}});require.register("segmentio-analytics.js-integrations/lib/heap.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Heap)};var Heap=exports.Integration=integration("Heap").assumesPageview().readyOnInitialize().global("heap").global("_heapid").option("apiKey","");Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load()};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.load=function(callback){load("//d36lvucg9kzous.cloudfront.net",callback)};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/hittail.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(HitTail)};var HitTail=exports.Integration=integration("HitTail").assumesPageview().readyOnLoad().global("htk").option("siteId","");HitTail.prototype.initialize=function(page){this.load()};HitTail.prototype.loaded=function(){return is.fn(window.htk)};HitTail.prototype.load=function(callback){var id=this.options.siteId;load("//"+id+".hittail.com/mlt.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/hubspot.js",function(exports,require,module){var callback=require("callback");var convert=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_hsq");module.exports=exports=function(analytics){analytics.addIntegration(HubSpot)};var HubSpot=exports.Integration=integration("HubSpot").assumesPageview().readyOnInitialize().global("_hsq").option("portalId",null);HubSpot.prototype.initialize=function(page){window._hsq=[];this.load()};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.load=function(fn){if(document.getElementById("hs-analytics"))return callback.async(fn);var id=this.options.portalId;var cache=Math.ceil(new Date/3e5)*3e5;var url="https://js.hs-analytics.net/analytics/"+cache+"/"+id+".js";var script=load(url,fn);script.id="hs-analytics"};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}});require.register("segmentio-analytics.js-integrations/lib/improvely.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Improvely)};var Improvely=exports.Integration=integration("Improvely").assumesPageview().readyOnInitialize().global("_improvely").global("improvely").option("domain","").option("projectId",null);Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load()};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.load=function(callback){var domain=this.options.domain;load("//"+domain+".iljmp.com/improvely.js",callback)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}});require.register("segmentio-analytics.js-integrations/lib/inspectlet.js",function(exports,require,module){var integration=require("integration");var alias=require("alias");var clone=require("clone");var load=require("load-script");var push=require("global-queue")("__insp");module.exports=exports=function(analytics){analytics.addIntegration(Inspectlet)};var Inspectlet=exports.Integration=integration("Inspectlet").assumesPageview().readyOnLoad().global("__insp").global("__insp_").option("wid","");Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load()};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.load=function(callback){load("//www.inspectlet.com/inspectlet.js",callback)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}});require.register("segmentio-analytics.js-integrations/lib/intercom.js",function(exports,require,module){var alias=require("alias");var convertDates=require("convert-dates");var integration=require("integration");var each=require("each");var is=require("is");var isEmail=require("is-email");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Intercom)};var Intercom=exports.Integration=integration("Intercom").assumesPageview().readyOnLoad().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false);Intercom.prototype.initialize=function(page){this.load()};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.load=function(callback){load("https://static.intercomcdn.com/intercom.v1.js",callback)};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(name)traits.name=name;if(companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company){traits.company=alias(traits.company,{created:"created_at"})}if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if(this.options.inbox){traits.widget={activator:this.options.activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackUserEvent",track.event(),track.traits())};function formatDate(date){return Math.floor(date/1e3)}});require.register("segmentio-analytics.js-integrations/lib/keen-io.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Keen)};var Keen=exports.Integration=integration("Keen IO").readyOnInitialize().global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true);Keen.prototype.initialize=function(){var options=this.options;window.Keen=window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};window.Keen.configure({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});this.load()};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.Base64)};Keen.prototype.load=function(callback){load("//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js",callback)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;window.Keen.setGlobalProperties(function(){return{user:user}})};Keen.prototype.track=function(track){window.Keen.addEvent(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js",function(exports,require,module){var alias=require("alias");var Batch=require("batch");var callback=require("callback");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(KISSmetrics)};var KISSmetrics=exports.Integration=integration("KISSmetrics").assumesPageview().readyOnInitialize().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true);KISSmetrics.prototype.initialize=function(page){window._kmq=[];this.load()};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.load=function(callback){var key=this.options.apiKey;var useless="//i.kissmetrics.com/i.js";var library="//doug1izaerwt3.cloudfront.net/"+key+".1.js";(new Batch).push(function(done){load(useless,done)}).push(function(done){load(library,done)}).end(callback)};KISSmetrics.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var props=track.properties({revenue:"Billing Amount"});push("record",track.event(),props)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.viewedProduct=function(track){push("record","Product Viewed",toProduct(track))};KISSmetrics.prototype.addedProduct=function(track){push("record","Product Added",toProduct(track))};KISSmetrics.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();push("record","Purchased",{"Order ID":track.orderId(),"Order Total":track.total()});window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var track=new Track({properties:product});var item=toProduct(track);item["Order ID"]=orderId;item._t=km.ts()+i;item._d=1;km.set(item)})})};function toProduct(track){return{Quantity:track.quantity(),Price:track.price(),Name:track.name(),SKU:track.sku()}}});require.register("segmentio-analytics.js-integrations/lib/klaviyo.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_learnq");module.exports=exports=function(analytics){analytics.addIntegration(Klaviyo)};var Klaviyo=exports.Integration=integration("Klaviyo").assumesPageview().readyOnInitialize().global("_learnq").option("apiKey","");Klaviyo.prototype.initialize=function(page){push("account",this.options.apiKey);this.load()};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.load=function(callback){load("//a.klaviyo.com/media/js/learnmarklet.js",callback)};var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/leadlander.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(LeadLander)};var LeadLander=exports.Integration=integration("LeadLander").assumesPageview().readyOnLoad().global("llactid").global("trackalyzer").option("accountId",null);LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load()};LeadLander.prototype.loaded=function(){return!!window.trackalyzer};LeadLander.prototype.load=function(callback){load("http://t6.trackalyzer.com/trackalyze-nodoc.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/livechat.js",function(exports,require,module){var each=require("each");var integration=require("integration");var load=require("load-script");var clone=require("clone");module.exports=exports=function(analytics){analytics.addIntegration(LiveChat)};var LiveChat=exports.Integration=integration("LiveChat").assumesPageview().readyOnLoad().global("__lc").option("group",0).option("license","");LiveChat.prototype.initialize=function(page){window.__lc=clone(this.options);this.isLoaded=false;this.load()};LiveChat.prototype.loaded=function(){return this.isLoaded};LiveChat.prototype.load=function(callback){var self=this;load("//cdn.livechatinc.com/tracking.js",function(err){if(err)return callback(err);self.isLoaded=true;callback()})};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}});require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js",function(exports,require,module){var Identify=require("facade").Identify;var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(LuckyOrange);user=analytics.user()};var LuckyOrange=exports.Integration=integration("Lucky Orange").assumesPageview().readyOnLoad().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null);LuckyOrange.prototype.initialize=function(page){window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));this.load()};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.load=function(callback){var cache=Math.floor((new Date).getTime()/6e4);load({http:"http://www.luckyorange.com/w.js?"+cache,https:"https://ssl.luckyorange.com/w.js?"+cache},callback)};LuckyOrange.prototype.identify=function(identify){var traits=window.__wtw_custom_user_data=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email}});require.register("segmentio-analytics.js-integrations/lib/lytics.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Lytics)};var Lytics=exports.Integration=integration("Lytics").readyOnInitialize().global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io");var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load()};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.load=function(callback){load("//c.lytics.io/static/io.min.js",callback)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}});require.register("segmentio-analytics.js-integrations/lib/mixpanel.js",function(exports,require,module){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("integration");var iso=require("to-iso-string");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Mixpanel)};var Mixpanel=exports.Integration=integration("Mixpanel").readyOnLoad().global("mixpanel").option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true);var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load()};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.load=function(callback){load("//cdn.mxpnl.com/libs/mixpanel-2.2.min.js",callback)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);traits=identify.traits(traitAliases);window.mixpanel.register(traits);if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&this.options.people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())}});require.register("segmentio-analytics.js-integrations/lib/mojn.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Mojn)};var Mojn=exports.Integration=integration("Mojn").option("customerCode","").global("_agTrack").readyOnInitialize();Mojn.prototype.initialize=function(){window._agTrack=window._agTrack||[];window._agTrack.push({cid:this.options.customerCode});this.load()};Mojn.prototype.load=function(fn){load("https://track.idtargeting.com/"+this.options.customerCode+"/track.js",fn)};Mojn.prototype.loaded=function(){return is.object(window._agTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._agTrack.push({conv:conv});return conv}});require.register("segmentio-analytics.js-integrations/lib/mouseflow.js",function(exports,require,module){var push=require("global-queue")("_mfq");var integration=require("integration");var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(Mouseflow)};var Mouseflow=exports.Integration=integration("Mouseflow").assumesPageview().readyOnLoad().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0);Mouseflow.prototype.initialize=function(page){this.load()};Mouseflow.prototype.loaded=function(){return!!(window._mfq&&[].push!=window._mfq.push)};Mouseflow.prototype.load=function(fn){var apiKey=this.options.apiKey;window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;load("//cdn.mouseflow.com/projects/"+apiKey+".js",fn)};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(hash){each(hash,function(k,v){push("setVariable",k,v)})}});require.register("segmentio-analytics.js-integrations/lib/mousestats.js",function(exports,require,module){var each=require("each");var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(MouseStats)};var MouseStats=exports.Integration=integration("MouseStats").assumesPageview().readyOnLoad().global("msaa").option("accountNumber","");MouseStats.prototype.initialize=function(page){this.load()};MouseStats.prototype.loaded=function(){return is.fn(window.msaa)};MouseStats.prototype.load=function(callback){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var partial=".mousestats.com/js/"+path+".js?"+cache;var http="http://www2"+partial;var https="https://ssl"+partial;load({http:http,https:https},callback)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}});require.register("segmentio-analytics.js-integrations/lib/olark.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var https=require("use-https");module.exports=exports=function(analytics){analytics.addIntegration(Olark)};var Olark=exports.Integration=integration("Olark").assumesPageview().readyOnInitialize().global("olark").option("identify",true).option("page",true).option("siteId","").option("track",false);Olark.prototype.initialize=function(page){window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);var self=this;box("onExpand",function(){self._open=true});box("onShrink",function(){self._open=false})};Olark.prototype.page=function(page){if(!this.options.page||!this._open)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;var msg=name?name.toLowerCase()+" page":props.url;chat("sendNotificationToOperator",{body:"looking at "+msg})};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();visitor("updateCustomFields",traits);if(email)visitor("updateEmailAddress",{emailAddress:email});if(phone)visitor("updatePhoneNumber",{phoneNumber:phone});if(name)visitor("updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)chat("updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track||!this._open)return;chat("sendNotificationToOperator",{body:'visitor triggered "'+track.event()+'"'})};function box(action,value){window.olark("api.box."+action,value)}function visitor(action,value){window.olark("api.visitor."+action,value)}function chat(action,value){window.olark("api.chat."+action,value)}});require.register("segmentio-analytics.js-integrations/lib/optimizely.js",function(exports,require,module){var bind=require("bind");var callback=require("callback");var each=require("each");var integration=require("integration");var push=require("global-queue")("optimizely");var tick=require("next-tick");var analytics;module.exports=exports=function(ajs){ajs.addIntegration(Optimizely);analytics=ajs};var Optimizely=exports.Integration=integration("Optimizely").readyOnInitialize().option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations)tick(this.replay)};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});analytics.identify(traits)}});require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(PerfectAudience)};var PerfectAudience=exports.Integration=integration("Perfect Audience").assumesPageview().readyOnLoad().global("_pa").option("siteId","");PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load()};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.load=function(callback){var id=this.options.siteId;load("//tag.perfectaudience.com/serve/"+id+".js",callback)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/pingdom.js",function(exports,require,module){var date=require("load-date");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_prum");module.exports=exports=function(analytics){analytics.addIntegration(Pingdom)};var Pingdom=exports.Integration=integration("Pingdom").assumesPageview().readyOnLoad().global("_prum").option("id","");
Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());this.load()};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)};Pingdom.prototype.load=function(callback){load("//rum-static.pingdom.net/prum.min.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/preact.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_lnq");module.exports=exports=function(analytics){analytics.addIntegration(Preact)};var Preact=exports.Integration=integration("Preact").assumesPageview().readyOnInitialize().global("_lnq").option("projectCode","");Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load()};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.load=function(callback){load("//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js",callback)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}});require.register("segmentio-analytics.js-integrations/lib/qualaroo.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;module.exports=exports=function(analytics){analytics.addIntegration(Qualaroo)};var Qualaroo=exports.Integration=integration("Qualaroo").assumesPageview().readyOnInitialize().global("_kiq").option("customerId","").option("siteToken","").option("track",false);Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];this.load()};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.load=function(callback){var token=this.options.siteToken;var id=this.options.customerId;load("//s3.amazonaws.com/ki.js/"+id+"/"+token+".js",callback)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}});require.register("segmentio-analytics.js-integrations/lib/quantcast.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_qevents",{wrap:false});var user;module.exports=exports=function(analytics){analytics.addIntegration(Quantcast);user=analytics.user()};var Quantcast=exports.Integration=integration("Quantcast").assumesPageview().readyOnInitialize().global("_qevents").global("__qc").option("pCode",null).option("labelPages",false);Quantcast.prototype.initialize=function(page){page=page||{};window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};if(user.id())settings.uid=user.id();push(settings);this.load()};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.load=function(callback){load({http:"http://edge.quantserve.com/quant.js",https:"https://secure.quantserve.com/quant.js"},callback)};Quantcast.prototype.page=function(page){var settings={event:"refresh",qacct:this.options.pCode};if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id)window._qevents[0].uid=id};Quantcast.prototype.track=function(track){var settings={event:"click",qacct:this.options.pCode};if(user.id())settings.uid=user.id();push(settings)}});require.register("segmentio-analytics.js-integrations/lib/rollbar.js",function(exports,require,module){var callback=require("callback");var clone=require("clone");var extend=require("extend");var integration=require("integration");var load=require("load-script");var onError=require("on-error");module.exports=exports=function(analytics){analytics.addIntegration(Rollbar)};var Rollbar=exports.Integration=integration("Rollbar").readyOnInitialize().assumesPageview().global("_rollbar").option("accessToken","").option("identify",true);Rollbar.prototype.initialize=function(page){var options=this.options;window._rollbar=window._rollbar||window._ratchet||[options.accessToken,options];onError(function(){window._rollbar.push.apply(window._rollbar,arguments)});this.load()};Rollbar.prototype.loaded=function(){return!!(window._rollbar&&window._rollbar.push!==Array.prototype.push)};Rollbar.prototype.load=function(callback){load("//d37gvrvc0wt4s1.cloudfront.net/js/1/rollbar.min.js",callback)};Rollbar.prototype.identify=function(identify){if(!this.options.identify)return;var traits=identify.traits();var rollbar=window._rollbar;var params=rollbar.shift?rollbar[1]=rollbar[1]||{}:rollbar.extraParams=rollbar.extraParams||{};params.person=params.person||{};extend(params.person,traits)}});require.register("segmentio-analytics.js-integrations/lib/saasquatch.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(SaaSquatch)};var SaaSquatch=exports.Integration=integration("SaaSquatch").readyOnInitialize().option("tenantAlias","").global("_sqh");SaaSquatch.prototype.initialize=function(page){};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.load=function(fn){load("//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js",fn)};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh=window._sqh||[];var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}});require.register("segmentio-analytics.js-integrations/lib/sentry.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Sentry)};var Sentry=exports.Integration=integration("Sentry").readyOnLoad().global("Raven").option("config","");Sentry.prototype.initialize=function(){var config=this.options.config;this.load(function(){window.Raven.config(config).install()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.load=function(callback){load("//cdn.ravenjs.com/1.1.10/native/raven.min.js",callback)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}});require.register("segmentio-analytics.js-integrations/lib/snapengage.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(SnapEngage)};var SnapEngage=exports.Integration=integration("SnapEngage").assumesPageview().readyOnLoad().global("SnapABug").option("apiKey","");SnapEngage.prototype.initialize=function(page){this.load()};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.load=function(callback){var key=this.options.apiKey;var url="//commondatastorage.googleapis.com/code.snapengage.com/js/"+key+".js";load(url,callback)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}});require.register("segmentio-analytics.js-integrations/lib/spinnakr.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Spinnakr)};var Spinnakr=exports.Integration=integration("Spinnakr").assumesPageview().readyOnLoad().global("_spinnakr_site_id").global("_spinnakr").option("siteId","");Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;this.load()};Spinnakr.prototype.loaded=function(){return!!window._spinnakr};Spinnakr.prototype.load=function(callback){load("//d3ojzyhbolvoi5.cloudfront.net/js/so.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/tapstream.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var slug=require("slug");var push=require("global-queue")("_tsq");module.exports=exports=function(analytics){analytics.addIntegration(Tapstream)};var Tapstream=exports.Integration=integration("Tapstream").assumesPageview().readyOnInitialize().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load()};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.load=function(callback){load("//cdn.tapstream.com/static/js/tapstream.js",callback)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}});require.register("segmentio-analytics.js-integrations/lib/trakio.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var clone=require("clone");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Trakio)};var Trakio=exports.Integration=integration("trak.io").assumesPageview().readyOnInitialize().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true);var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var self=this;var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.io.load=function(e){self.load();var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load()};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.load=function(callback){load("//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js",callback)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}});require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js",function(exports,require,module){var pixel=require("load-pixel")("//analytics.twitter.com/i/adsct");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(TwitterAds)};exports.load=pixel;var has=Object.prototype.hasOwnProperty;var TwitterAds=exports.Integration=integration("Twitter Ads").readyOnInitialize().option("events",{});TwitterAds.prototype.track=function(track){var events=this.options.events;var event=track.event();if(!has.call(events,event))return;return exports.load({txn_id:events[event],p_id:"Twitter"})}});require.register("segmentio-analytics.js-integrations/lib/usercycle.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_uc");module.exports=exports=function(analytics){analytics.addIntegration(Usercycle)};var Usercycle=exports.Integration=integration("USERcycle").assumesPageview().readyOnInitialize().global("_uc").option("key","");Usercycle.prototype.initialize=function(page){push("_key",this.options.key);this.load()};Usercycle.prototype.loaded=function(){return!!(window._uc&&window._uc.push!==Array.prototype.push)};Usercycle.prototype.load=function(callback){load("//api.usercycle.com/javascripts/track.js",callback)};Usercycle.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("uid",id);push("action","came_back",traits)};Usercycle.prototype.track=function(track){push("action",track.event(),track.properties({revenue:"revenue_amount"}))}});require.register("segmentio-analytics.js-integrations/lib/userfox.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_ufq");module.exports=exports=function(analytics){analytics.addIntegration(Userfox)};var Userfox=exports.Integration=integration("userfox").assumesPageview().readyOnInitialize().global("_ufq").option("clientId","");Userfox.prototype.initialize=function(page){window._ufq=[];this.load()};Userfox.prototype.loaded=function(){return!!(window._ufq&&window._ufq.push!==Array.prototype.push)};Userfox.prototype.load=function(callback){load("//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js",callback)};Userfox.prototype.identify=function(identify){var traits=identify.traits({created:"signup_date"});var email=identify.email();if(!email)return;push("init",{clientId:this.options.clientId,email:email});traits=convertDates(traits,formatDate);push("track",traits)};function formatDate(date){return Math.round(date.getTime()/1e3).toString()}});require.register("segmentio-analytics.js-integrations/lib/uservoice.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var clone=require("clone");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("UserVoice");var unix=require("to-unix-timestamp");module.exports=exports=function(analytics){analytics.addIntegration(UserVoice)};var UserVoice=exports.Integration=integration("UserVoice").assumesPageview().readyOnInitialize().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false);UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load()};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.load=function(callback){var key=this.options.apiKey;load("//widget.uservoice.com/"+key+".js",callback)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load()};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}});require.register("segmentio-analytics.js-integrations/lib/vero.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_veroq");module.exports=exports=function(analytics){analytics.addIntegration(Vero)};var Vero=exports.Integration=integration("Vero").assumesPageview().readyOnInitialize().global("_veroq").option("apiKey","");Vero.prototype.initialize=function(pgae){push("init",{api_key:this.options.apiKey});this.load()};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.load=function(callback){load("//d3qxef4rp70elm.cloudfront.net/m.js",callback)};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js",function(exports,require,module){var callback=require("callback");var each=require("each");var integration=require("integration");var tick=require("next-tick");var analytics;module.exports=exports=function(ajs){ajs.addIntegration(VWO);analytics=ajs};var VWO=exports.Integration=integration("Visual Website Optimizer").readyOnInitialize().option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay()};VWO.prototype.replay=function(){tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(callback){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return callback();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});callback(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}});require.register("segmentio-analytics.js-integrations/lib/webengage.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(WebEngage)};var WebEngage=exports.Integration=integration("WebEngage").assumesPageview().readyOnLoad().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","");WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;this.load()};WebEngage.prototype.loaded=function(){return!!window.webengage};WebEngage.prototype.load=function(fn){var path="/js/widget/webengage-min-v-4.0.js";load({https:"https://ssl.widgets.webengage.com"+path,http:"http://cdn.widgets.webengage.com"+path},fn)}});require.register("segmentio-analytics.js-integrations/lib/woopra.js",function(exports,require,module){var each=require("each");var extend=require("extend");var integration=require("integration");var isEmail=require("is-email");var load=require("load-script");var type=require("type");module.exports=exports=function(analytics){analytics.addIntegration(Woopra)};var Woopra=exports.Integration=integration("Woopra").readyOnLoad().global("woopra").option("domain","");Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");window.woopra.config({domain:this.options.domain});this.load()};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.load=function(callback){load("//static.woopra.com/js/w.js",callback)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){window.woopra.identify(identify.traits()).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Yandex)};var Yandex=exports.Integration=integration("Yandex Metrica").assumesPageview().readyOnInitialize().global("yandex_metrika_callbacks").global("Ya").option("counterId",null);Yandex.prototype.initialize=function(page){var id=this.options.counterId;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id})});this.load()};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};Yandex.prototype.load=function(callback){load("//mc.yandex.ru/metrika/watch.js",callback)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}});require.register("segmentio-canonical/index.js",function(exports,require,module){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}});require.register("segmentio-extend/index.js",function(exports,require,module){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}});require.register("camshaft-require-component/index.js",function(exports,require,module){module.exports=function(parent){function require(name,fallback){try{return parent(name)}catch(e){try{return parent(fallback||name+"-component")}catch(e2){throw e}}}for(var key in parent){require[key]=parent[key]}return require}});require.register("ianstormtaylor-to-camel-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-capital-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}});require.register("ianstormtaylor-to-constant-case/index.js",function(exports,require,module){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}});require.register("ianstormtaylor-to-dot-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}});require.register("ianstormtaylor-to-no-case/index.js",function(exports,require,module){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}});require.register("ianstormtaylor-to-pascal-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-sentence-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-slug-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}});require.register("ianstormtaylor-to-snake-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}});require.register("ianstormtaylor-to-space-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}});require.register("component-escape-regexp/index.js",function(exports,require,module){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}});require.register("ianstormtaylor-map/index.js",function(exports,require,module){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}});require.register("ianstormtaylor-title-case-minors/index.js",function(exports,require,module){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]});require.register("ianstormtaylor-to-title-case/index.js",function(exports,require,module){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-case/lib/index.js",function(exports,require,module){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}});require.register("ianstormtaylor-case/lib/cases.js",function(exports,require,module){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none});require.register("segmentio-obj-case/index.js",function(exports,require,module){var Case=require("case");var cases=[Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)
}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}});require.register("segmentio-facade/lib/index.js",function(exports,require,module){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page")});require.register("segmentio-facade/lib/alias.js",function(exports,require,module){var Facade=require("./facade");var component=require("require-component")(require);var inherit=component("inherit");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Facade.field("from");Alias.prototype.to=Facade.field("to")});require.register("segmentio-facade/lib/facade.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var isEnabled=component("./is-enabled");var objCase=component("obj-case");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=new Date(obj.timestamp);this.obj=obj}Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return clone(obj);obj=objCase(obj,fields.join("."));return clone(obj)};Facade.prototype.field=function(field){return clone(this.obj[field])};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.prototype.json=function(){return clone(this.obj)};Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;options=options[integration]||objCase(options,integration)||{};return typeof options==="boolean"?{}:clone(options)};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.options();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.userAgent=function(){};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.userId=Facade.field("userId");Facade.prototype.sessionId=Facade.field("sessionId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.ip=Facade.proxy("options.ip")});require.register("segmentio-facade/lib/group.js",function(exports,require,module){var Facade=require("./facade");var component=require("require-component")(require);var inherit=component("inherit");var newDate=component("new-date");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}});require.register("segmentio-facade/lib/page.js",function(exports,require,module){var component=require("require-component")(require);var Facade=component("./facade");var inherit=component("inherit");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}});require.register("segmentio-facade/lib/identify.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var Facade=component("./facade");var inherit=component("inherit");var isEmail=component("is-email");var newDate=component("new-date");var trim=component("trim");module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.proxy("traits.website");Identify.prototype.phone=Facade.proxy("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.avatar=Facade.proxy("traits.avatar")});require.register("segmentio-facade/lib/is-enabled.js",function(exports,require,module){var disabled={Salesforce:true,Marketo:true};module.exports=function(integration){return!disabled[integration]}});require.register("segmentio-facade/lib/track.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var Facade=component("./facade");var Identify=component("./identify");var inherit=component("inherit");var isEmail=component("is-email");var traverse=component("isodate-traverse");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.country=Facade.proxy("properties.country");Track.prototype.state=Facade.proxy("properties.state");Track.prototype.city=Facade.proxy("properties.city");Track.prototype.zip=Facade.proxy("properties.zip");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.orderId=Facade.proxy("properties.orderId");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=this.obj.properties.subtotal;var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;return total};Track.prototype.products=function(){var props=this.obj.properties||{};return props.products||[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return clone(traverse(ret))};Track.prototype.traits=function(){return this.proxy("options.traits")||{}};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");if(!revenue)return;if(typeof revenue==="number")return revenue;if(typeof revenue!=="string")return;revenue=revenue.replace(/\$/g,"");revenue=parseFloat(revenue);if(!isNaN(revenue))return revenue};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)}});require.register("segmentio-is-email/index.js",function(exports,require,module){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}});require.register("segmentio-is-meta/index.js",function(exports,require,module){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}});require.register("segmentio-isodate/index.js",function(exports,require,module){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,8,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;if(arr[8])arr[8]=(arr[8]+"00").substring(0,3);if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}});require.register("segmentio-isodate-traverse/index.js",function(exports,require,module){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input)){return object(input,strict)}else if(is.array(input)){return array(input,strict)}}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}});require.register("component-json-fallback/index.js",function(exports,require,module){if(typeof JSON!=="object"){JSON={}}(function(){"use strict";function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})();module.exports=JSON});require.register("segmentio-json/index.js",function(exports,require,module){module.exports="undefined"==typeof JSON?require("json-fallback"):JSON});require.register("segmentio-new-date/lib/index.js",function(exports,require,module){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}});require.register("segmentio-new-date/lib/milliseconds.js",function(exports,require,module){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}});require.register("segmentio-new-date/lib/seconds.js",function(exports,require,module){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}});require.register("segmentio-store.js/store.js",function(exports,require,module){(function(win){var store={},doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return JSON.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return JSON.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;if(typeof module!="undefined"&&module.exports){module.exports=store}else if(typeof define==="function"&&define.amd){define(store)}else{win.store=store}})(this.window||global)});require.register("segmentio-top-domain/index.js",function(exports,require,module){var url=require("url");module.exports=function(urlStr){var host=url.parse(urlStr).hostname,topLevel=host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i);return topLevel?topLevel[0]:host}});require.register("visionmedia-debug/index.js",function(exports,require,module){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}});require.register("visionmedia-debug/debug.js",function(exports,require,module){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}});require.register("yields-prevent/index.js",function(exports,require,module){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}});require.register("analytics/lib/index.js",function(exports,require,module){var Analytics=require("./analytics");var createIntegration=require("integration");var each=require("each");var Integrations=require("integrations");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION="1.3.8";each(Integrations,function(name,Integration){analytics.use(Integration)})});require.register("analytics/lib/analytics.js",function(exports,require,module){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;module.exports=Analytics;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;this._integrations={};user.load();group.load();var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});var ready=after(size(settings),function(){self._readied=true;self.emit("ready")});each(settings,function(name,opts){var Integration=self.Integrations[name];if(options.initialPageview&&opts.initialPageview===false){Integration.prototype.page=after(2,Integration.prototype.page)}var integration=new Integration(clone(opts));integration.once("ready",ready);integration.initialize();self._integrations[name]=integration});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",new Identify({options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",new Group({options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",new Track({properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,url:canonicalUrl(),search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);this._invoke("page",new Page({properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",new Alias({options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(){var canon=canonical();if(canon)return canon;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}});require.register("analytics/lib/cookie.js",function(exports,require,module){var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;
options=options||{};var domain="."+topDomain(window.location.href);if(domain===".localhost")domain="";defaults(options,{maxage:31536e6,path:"/",domain:domain});this._options=options};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie});require.register("analytics/lib/entity.js",function(exports,require,module){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options)}Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?cookie.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){cookie.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}});require.register("analytics/lib/group.js",function(exports,require,module){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group});require.register("analytics/lib/store.js",function(exports,require,module){var bind=require("bind");var defaults=require("defaults");var store=require("store");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store});require.register("analytics/lib/user.js",function(exports,require,module){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User});require.register("segmentio-analytics.js-integrations/lib/slugs.json",function(exports,require,module){module.exports=["adroll","adwords","amplitude","awesm","awesomatic","bing-ads","bronto","bugherd","bugsnag","chartbeat","churnbee","clicktale","clicky","comscore","crazy-egg","curebit","customerio","drip","errorception","evergage","facebook-ads","foxmetrics","gauges","get-satisfaction","google-analytics","google-tag-manager","gosquared","heap","hittail","hubspot","improvely","inspectlet","intercom","keen-io","kissmetrics","klaviyo","leadlander","livechat","lucky-orange","lytics","mixpanel","mojn","mouseflow","mousestats","olark","optimizely","perfect-audience","pingdom","preact","qualaroo","quantcast","rollbar","saasquatch","sentry","snapengage","spinnakr","tapstream","trakio","twitter-ads","usercycle","userfox","uservoice","vero","visual-website-optimizer","webengage","woopra","yandex-metrica"]});require.alias("avetisk-defaults/index.js","analytics/deps/defaults/index.js");require.alias("avetisk-defaults/index.js","defaults/index.js");require.alias("component-clone/index.js","analytics/deps/clone/index.js");require.alias("component-clone/index.js","clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-cookie/index.js","analytics/deps/cookie/index.js");require.alias("component-cookie/index.js","cookie/index.js");require.alias("component-each/index.js","analytics/deps/each/index.js");require.alias("component-each/index.js","each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-emitter/index.js","analytics/deps/emitter/index.js");require.alias("component-emitter/index.js","emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("component-event/index.js","analytics/deps/event/index.js");require.alias("component-event/index.js","event/index.js");require.alias("component-inherit/index.js","analytics/deps/inherit/index.js");require.alias("component-inherit/index.js","inherit/index.js");require.alias("component-object/index.js","analytics/deps/object/index.js");require.alias("component-object/index.js","object/index.js");require.alias("component-querystring/index.js","analytics/deps/querystring/index.js");require.alias("component-querystring/index.js","querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("component-url/index.js","analytics/deps/url/index.js");require.alias("component-url/index.js","url/index.js");require.alias("ianstormtaylor-bind/index.js","analytics/deps/bind/index.js");require.alias("ianstormtaylor-bind/index.js","bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","analytics/deps/callback/index.js");require.alias("ianstormtaylor-callback/index.js","callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-is/index.js","analytics/deps/is/index.js");require.alias("ianstormtaylor-is/index.js","is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-after/index.js","analytics/deps/after/index.js");require.alias("segmentio-after/index.js","after/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","analytics/deps/integration/lib/index.js");require.alias("segmentio-analytics.js-integration/lib/protos.js","analytics/deps/integration/lib/protos.js");require.alias("segmentio-analytics.js-integration/lib/events.js","analytics/deps/integration/lib/events.js");require.alias("segmentio-analytics.js-integration/lib/statics.js","analytics/deps/integration/lib/statics.js");require.alias("segmentio-analytics.js-integration/lib/index.js","analytics/deps/integration/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","integration/index.js");require.alias("avetisk-defaults/index.js","segmentio-analytics.js-integration/deps/defaults/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integration/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-emitter/index.js","segmentio-analytics.js-integration/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integration/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integration/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("segmentio-after/index.js","segmentio-analytics.js-integration/deps/after/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integration/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integration/deps/slug/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integration/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integration/deps/debug/debug.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integration/index.js");require.alias("segmentio-analytics.js-integrations/index.js","analytics/deps/integrations/index.js");require.alias("segmentio-analytics.js-integrations/lib/adroll.js","analytics/deps/integrations/lib/adroll.js");require.alias("segmentio-analytics.js-integrations/lib/adwords.js","analytics/deps/integrations/lib/adwords.js");require.alias("segmentio-analytics.js-integrations/lib/amplitude.js","analytics/deps/integrations/lib/amplitude.js");require.alias("segmentio-analytics.js-integrations/lib/awesm.js","analytics/deps/integrations/lib/awesm.js");require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js","analytics/deps/integrations/lib/awesomatic.js");require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js","analytics/deps/integrations/lib/bing-ads.js");require.alias("segmentio-analytics.js-integrations/lib/bronto.js","analytics/deps/integrations/lib/bronto.js");require.alias("segmentio-analytics.js-integrations/lib/bugherd.js","analytics/deps/integrations/lib/bugherd.js");require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js","analytics/deps/integrations/lib/bugsnag.js");require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js","analytics/deps/integrations/lib/chartbeat.js");require.alias("segmentio-analytics.js-integrations/lib/churnbee.js","analytics/deps/integrations/lib/churnbee.js");require.alias("segmentio-analytics.js-integrations/lib/clicktale.js","analytics/deps/integrations/lib/clicktale.js");require.alias("segmentio-analytics.js-integrations/lib/clicky.js","analytics/deps/integrations/lib/clicky.js");require.alias("segmentio-analytics.js-integrations/lib/comscore.js","analytics/deps/integrations/lib/comscore.js");require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js","analytics/deps/integrations/lib/crazy-egg.js");require.alias("segmentio-analytics.js-integrations/lib/curebit.js","analytics/deps/integrations/lib/curebit.js");require.alias("segmentio-analytics.js-integrations/lib/customerio.js","analytics/deps/integrations/lib/customerio.js");require.alias("segmentio-analytics.js-integrations/lib/drip.js","analytics/deps/integrations/lib/drip.js");require.alias("segmentio-analytics.js-integrations/lib/errorception.js","analytics/deps/integrations/lib/errorception.js");require.alias("segmentio-analytics.js-integrations/lib/evergage.js","analytics/deps/integrations/lib/evergage.js");require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js","analytics/deps/integrations/lib/facebook-ads.js");require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js","analytics/deps/integrations/lib/foxmetrics.js");require.alias("segmentio-analytics.js-integrations/lib/gauges.js","analytics/deps/integrations/lib/gauges.js");require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js","analytics/deps/integrations/lib/get-satisfaction.js");require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js","analytics/deps/integrations/lib/google-analytics.js");require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js","analytics/deps/integrations/lib/google-tag-manager.js");require.alias("segmentio-analytics.js-integrations/lib/gosquared.js","analytics/deps/integrations/lib/gosquared.js");require.alias("segmentio-analytics.js-integrations/lib/heap.js","analytics/deps/integrations/lib/heap.js");require.alias("segmentio-analytics.js-integrations/lib/hittail.js","analytics/deps/integrations/lib/hittail.js");require.alias("segmentio-analytics.js-integrations/lib/hubspot.js","analytics/deps/integrations/lib/hubspot.js");require.alias("segmentio-analytics.js-integrations/lib/improvely.js","analytics/deps/integrations/lib/improvely.js");require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js","analytics/deps/integrations/lib/inspectlet.js");require.alias("segmentio-analytics.js-integrations/lib/intercom.js","analytics/deps/integrations/lib/intercom.js");require.alias("segmentio-analytics.js-integrations/lib/keen-io.js","analytics/deps/integrations/lib/keen-io.js");require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js","analytics/deps/integrations/lib/kissmetrics.js");require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js","analytics/deps/integrations/lib/klaviyo.js");require.alias("segmentio-analytics.js-integrations/lib/leadlander.js","analytics/deps/integrations/lib/leadlander.js");require.alias("segmentio-analytics.js-integrations/lib/livechat.js","analytics/deps/integrations/lib/livechat.js");require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js","analytics/deps/integrations/lib/lucky-orange.js");require.alias("segmentio-analytics.js-integrations/lib/lytics.js","analytics/deps/integrations/lib/lytics.js");require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js","analytics/deps/integrations/lib/mixpanel.js");require.alias("segmentio-analytics.js-integrations/lib/mojn.js","analytics/deps/integrations/lib/mojn.js");require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js","analytics/deps/integrations/lib/mouseflow.js");require.alias("segmentio-analytics.js-integrations/lib/mousestats.js","analytics/deps/integrations/lib/mousestats.js");require.alias("segmentio-analytics.js-integrations/lib/olark.js","analytics/deps/integrations/lib/olark.js");require.alias("segmentio-analytics.js-integrations/lib/optimizely.js","analytics/deps/integrations/lib/optimizely.js");require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js","analytics/deps/integrations/lib/perfect-audience.js");require.alias("segmentio-analytics.js-integrations/lib/pingdom.js","analytics/deps/integrations/lib/pingdom.js");require.alias("segmentio-analytics.js-integrations/lib/preact.js","analytics/deps/integrations/lib/preact.js");require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js","analytics/deps/integrations/lib/qualaroo.js");require.alias("segmentio-analytics.js-integrations/lib/quantcast.js","analytics/deps/integrations/lib/quantcast.js");require.alias("segmentio-analytics.js-integrations/lib/rollbar.js","analytics/deps/integrations/lib/rollbar.js");require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js","analytics/deps/integrations/lib/saasquatch.js");require.alias("segmentio-analytics.js-integrations/lib/sentry.js","analytics/deps/integrations/lib/sentry.js");require.alias("segmentio-analytics.js-integrations/lib/snapengage.js","analytics/deps/integrations/lib/snapengage.js");require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js","analytics/deps/integrations/lib/spinnakr.js");require.alias("segmentio-analytics.js-integrations/lib/tapstream.js","analytics/deps/integrations/lib/tapstream.js");require.alias("segmentio-analytics.js-integrations/lib/trakio.js","analytics/deps/integrations/lib/trakio.js");require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js","analytics/deps/integrations/lib/twitter-ads.js");require.alias("segmentio-analytics.js-integrations/lib/usercycle.js","analytics/deps/integrations/lib/usercycle.js");require.alias("segmentio-analytics.js-integrations/lib/userfox.js","analytics/deps/integrations/lib/userfox.js");require.alias("segmentio-analytics.js-integrations/lib/uservoice.js","analytics/deps/integrations/lib/uservoice.js");require.alias("segmentio-analytics.js-integrations/lib/vero.js","analytics/deps/integrations/lib/vero.js");require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js","analytics/deps/integrations/lib/visual-website-optimizer.js");require.alias("segmentio-analytics.js-integrations/lib/webengage.js","analytics/deps/integrations/lib/webengage.js");require.alias("segmentio-analytics.js-integrations/lib/woopra.js","analytics/deps/integrations/lib/woopra.js");require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js","analytics/deps/integrations/lib/yandex-metrica.js");require.alias("segmentio-analytics.js-integrations/index.js","integrations/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integrations/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-domify/index.js","segmentio-analytics.js-integrations/deps/domify/index.js");require.alias("component-each/index.js","segmentio-analytics.js-integrations/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-once/index.js","segmentio-analytics.js-integrations/deps/once/index.js");require.alias("component-type/index.js","segmentio-analytics.js-integrations/deps/type/index.js");require.alias("component-url/index.js","segmentio-analytics.js-integrations/deps/url/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integrations/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integrations/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-analytics.js-integrations/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-alias/index.js","segmentio-analytics.js-integrations/deps/alias/index.js");require.alias("component-clone/index.js","segmentio-alias/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-type/index.js","segmentio-alias/deps/type/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integrations/deps/integration/lib/index.js");require.alias("segmentio-analytics.js-integration/lib/protos.js","segmentio-analytics.js-integrations/deps/integration/lib/protos.js");require.alias("segmentio-analytics.js-integration/lib/events.js","segmentio-analytics.js-integrations/deps/integration/lib/events.js");require.alias("segmentio-analytics.js-integration/lib/statics.js","segmentio-analytics.js-integrations/deps/integration/lib/statics.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integrations/deps/integration/index.js");require.alias("avetisk-defaults/index.js","segmentio-analytics.js-integration/deps/defaults/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integration/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-emitter/index.js","segmentio-analytics.js-integration/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integration/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integration/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("segmentio-after/index.js","segmentio-analytics.js-integration/deps/after/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integration/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integration/deps/slug/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integration/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integration/deps/debug/debug.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integration/index.js");require.alias("segmentio-canonical/index.js","segmentio-analytics.js-integrations/deps/canonical/index.js");require.alias("segmentio-convert-dates/index.js","segmentio-analytics.js-integrations/deps/convert-dates/index.js");require.alias("component-clone/index.js","segmentio-convert-dates/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-convert-dates/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-extend/index.js","segmentio-analytics.js-integrations/deps/extend/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-analytics.js-integrations/deps/facade/lib/index.js");require.alias("segmentio-facade/lib/alias.js","segmentio-analytics.js-integrations/deps/facade/lib/alias.js");require.alias("segmentio-facade/lib/facade.js","segmentio-analytics.js-integrations/deps/facade/lib/facade.js");require.alias("segmentio-facade/lib/group.js","segmentio-analytics.js-integrations/deps/facade/lib/group.js");require.alias("segmentio-facade/lib/page.js","segmentio-analytics.js-integrations/deps/facade/lib/page.js");require.alias("segmentio-facade/lib/identify.js","segmentio-analytics.js-integrations/deps/facade/lib/identify.js");require.alias("segmentio-facade/lib/is-enabled.js","segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js");require.alias("segmentio-facade/lib/track.js","segmentio-analytics.js-integrations/deps/facade/lib/track.js");require.alias("segmentio-facade/lib/index.js","segmentio-analytics.js-integrations/deps/facade/index.js");require.alias("camshaft-require-component/index.js","segmentio-facade/deps/require-component/index.js");require.alias("segmentio-isodate-traverse/index.js","segmentio-facade/deps/isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("component-clone/index.js","segmentio-facade/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-inherit/index.js","segmentio-facade/deps/inherit/index.js");require.alias("component-trim/index.js","segmentio-facade/deps/trim/index.js");require.alias("segmentio-is-email/index.js","segmentio-facade/deps/is-email/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","segmentio-facade/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","segmentio-facade/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-facade/index.js");require.alias("segmentio-global-queue/index.js","segmentio-analytics.js-integrations/deps/global-queue/index.js");require.alias("segmentio-is-email/index.js","segmentio-analytics.js-integrations/deps/is-email/index.js");require.alias("segmentio-load-date/index.js","segmentio-analytics.js-integrations/deps/load-date/index.js");require.alias("segmentio-load-script/index.js","segmentio-analytics.js-integrations/deps/load-script/index.js");require.alias("component-type/index.js","segmentio-load-script/deps/type/index.js");require.alias("segmentio-on-body/index.js","segmentio-analytics.js-integrations/deps/on-body/index.js");
require.alias("component-each/index.js","segmentio-on-body/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("segmentio-on-error/index.js","segmentio-analytics.js-integrations/deps/on-error/index.js");require.alias("segmentio-to-iso-string/index.js","segmentio-analytics.js-integrations/deps/to-iso-string/index.js");require.alias("segmentio-to-unix-timestamp/index.js","segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js");require.alias("segmentio-use-https/index.js","segmentio-analytics.js-integrations/deps/use-https/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integrations/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integrations/deps/slug/index.js");require.alias("visionmedia-batch/index.js","segmentio-analytics.js-integrations/deps/batch/index.js");require.alias("component-emitter/index.js","visionmedia-batch/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integrations/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integrations/deps/debug/debug.js");require.alias("segmentio-load-pixel/index.js","segmentio-analytics.js-integrations/deps/load-pixel/index.js");require.alias("segmentio-load-pixel/index.js","segmentio-analytics.js-integrations/deps/load-pixel/index.js");require.alias("component-querystring/index.js","segmentio-load-pixel/deps/querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("segmentio-substitute/index.js","segmentio-load-pixel/deps/substitute/index.js");require.alias("segmentio-substitute/index.js","segmentio-load-pixel/deps/substitute/index.js");require.alias("segmentio-substitute/index.js","segmentio-substitute/index.js");require.alias("segmentio-load-pixel/index.js","segmentio-load-pixel/index.js");require.alias("segmentio-canonical/index.js","analytics/deps/canonical/index.js");require.alias("segmentio-canonical/index.js","canonical/index.js");require.alias("segmentio-extend/index.js","analytics/deps/extend/index.js");require.alias("segmentio-extend/index.js","extend/index.js");require.alias("segmentio-facade/lib/index.js","analytics/deps/facade/lib/index.js");require.alias("segmentio-facade/lib/alias.js","analytics/deps/facade/lib/alias.js");require.alias("segmentio-facade/lib/facade.js","analytics/deps/facade/lib/facade.js");require.alias("segmentio-facade/lib/group.js","analytics/deps/facade/lib/group.js");require.alias("segmentio-facade/lib/page.js","analytics/deps/facade/lib/page.js");require.alias("segmentio-facade/lib/identify.js","analytics/deps/facade/lib/identify.js");require.alias("segmentio-facade/lib/is-enabled.js","analytics/deps/facade/lib/is-enabled.js");require.alias("segmentio-facade/lib/track.js","analytics/deps/facade/lib/track.js");require.alias("segmentio-facade/lib/index.js","analytics/deps/facade/index.js");require.alias("segmentio-facade/lib/index.js","facade/index.js");require.alias("camshaft-require-component/index.js","segmentio-facade/deps/require-component/index.js");require.alias("segmentio-isodate-traverse/index.js","segmentio-facade/deps/isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("component-clone/index.js","segmentio-facade/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-inherit/index.js","segmentio-facade/deps/inherit/index.js");require.alias("component-trim/index.js","segmentio-facade/deps/trim/index.js");require.alias("segmentio-is-email/index.js","segmentio-facade/deps/is-email/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","segmentio-facade/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","segmentio-facade/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-facade/index.js");require.alias("segmentio-is-email/index.js","analytics/deps/is-email/index.js");require.alias("segmentio-is-email/index.js","is-email/index.js");require.alias("segmentio-is-meta/index.js","analytics/deps/is-meta/index.js");require.alias("segmentio-is-meta/index.js","is-meta/index.js");require.alias("segmentio-isodate-traverse/index.js","analytics/deps/isodate-traverse/index.js");require.alias("segmentio-isodate-traverse/index.js","isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("segmentio-json/index.js","analytics/deps/json/index.js");require.alias("segmentio-json/index.js","json/index.js");require.alias("component-json-fallback/index.js","segmentio-json/deps/json-fallback/index.js");require.alias("segmentio-new-date/lib/index.js","analytics/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","analytics/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","analytics/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","analytics/deps/new-date/index.js");require.alias("segmentio-new-date/lib/index.js","new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/store.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/index.js");require.alias("segmentio-store.js/store.js","store/index.js");require.alias("segmentio-store.js/store.js","segmentio-store.js/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","top-domain/index.js");require.alias("component-url/index.js","segmentio-top-domain/deps/url/index.js");require.alias("segmentio-top-domain/index.js","segmentio-top-domain/index.js");require.alias("visionmedia-debug/index.js","analytics/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","analytics/deps/debug/debug.js");require.alias("visionmedia-debug/index.js","debug/index.js");require.alias("yields-prevent/index.js","analytics/deps/prevent/index.js");require.alias("yields-prevent/index.js","prevent/index.js");require.alias("analytics/lib/index.js","analytics/index.js");if(typeof exports=="object"){module.exports=require("analytics")}else if(typeof define=="function"&&define.amd){define([],function(){return require("analytics")})}else{this["analytics"]=require("analytics")}})(); |
src/components/buttons/InfoButton.js | dataloom/gallery | import React from 'react';
import styled from 'styled-components';
const InfoButton = styled.button`
border-radius: 3px;
background-color: #6124e2;
color: #ffffff;
font-family: 'Open Sans', sans-serif;
font-size: 14px;
padding: 10px;
width: ${props => (props.fullSize ? '100%' : 'fit-content')};
&:hover {
background-color: #8045ff;
cursor: pointer;
}
&:active {
background-color: #361876;
}
&:disabled {
background-color: #f0f0f7;
color: #b6bbc7;
border: none;
&:hover {
cursor: default;
}
}
&:focus {
outline: none;
}
`;
export default InfoButton;
|
src/svg-icons/notification/sms.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationSms = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9 11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z"/>
</SvgIcon>
);
NotificationSms = pure(NotificationSms);
NotificationSms.displayName = 'NotificationSms';
NotificationSms.muiName = 'SvgIcon';
export default NotificationSms;
|
packages/material-ui-icons/src/PlagiarismOutlined.js | callemall/material-ui | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm4 18H6V4h7v5h5v11z" /><path d="M9.03 11.03c-1.37 1.37-1.37 3.58 0 4.95 1.12 1.12 2.8 1.31 4.13.59l1.88 1.88 1.41-1.41-1.88-1.88c.71-1.33.53-3.01-.59-4.13-1.37-1.37-3.59-1.37-4.95 0zm3.53 3.53c-.59.59-1.54.59-2.12 0-.59-.59-.59-1.54 0-2.12.59-.59 1.54-.59 2.12 0 .59.59.59 1.53 0 2.12z" /></React.Fragment>
, 'PlagiarismOutlined');
|
js/jqwidgets/demos/react/app/notification/customicon/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxNotification from '../../../jqwidgets-react/react_jqxnotification.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
import JqxInput from '../../../jqwidgets-react/react_jqxinput.js';
import JqxTextArea from '../../../jqwidgets-react/react_jqxtextarea.js';
class App extends React.Component {
componentDidMount() {
this.refs.submit.on('click', () => {
this.refs.name.val('');
this.refs.email.val('');
this.refs.comment.val('');
this.refs.jqxNotification.open();
});
}
render() {
return (
<div>
<JqxNotification ref='jqxNotification'
width={'auto'}
position={'top-right'}
opacity={0.9}
template={null}
icon={{ width: 25, height: 25, url: '../../images/smiley.png', padding: 5 }}
>
<div>Thank you for your feedback!</div>
</JqxNotification>
<table style={{ marginLeft: 15, marginTop: 15 }}>
<tr>
<td className='label'>
Name:
</td>
<td>
<JqxInput ref='name' width={150} />
</td>
</tr>
<tr>
<td className='label'>
E-mail:
</td>
<td>
<JqxInput ref='email' width={150} />
</td>
</tr>
<tr>
<td className='label' style={{ verticalAlign: 'top' }}>
Comment:
</td>
<td>
<JqxTextArea ref='comment'
width={155} height={150}
/>
</td>
</tr>
<tr>
<td colSpan='2'>
</td>
</tr>
<tr>
<td colSpan='2' style={{ textAlign: 'cente' }}>
<JqxButton ref='submit' value='Submit comment' />
</td>
</tr>
</table>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
ajax/libs/reactive-coffee/0.0.6/reactive-coffee.min.js | CyrusSUEN/cdnjs | (function(){var 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,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,ab,bb,cb,db,eb,fb=[].slice,gb={}.hasOwnProperty,hb=function(a,b){function c(){this.constructor=a}for(var d in b)gb.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},ib=this;"undefined"==typeof exports?this.rx=P={}:P=exports,G=0,F=function(){return G+=1},J=function(a,b){var c;if(!(b in a))throw new Error("object has no key "+b);return c=a[b],delete a[b],c},H=function(a,b,c){var d,e,f,g;for(d=f=0,g=a.length;g>f;d=++f)if(e=a[d],c(e)&&(b-=1)<0)return[e,d];return[null,-1]},A=function(a,b){return H(a,0,b)},D=function(a){var b,c,d,e,f,g;if(null==a&&(a=[]),c=null!=Object.create?Object.create(null):{},_.isArray(a))for(e=0,f=a.length;f>e;e++)g=a[e],b=g[0],d=g[1],c[b]=d;else for(b in a)d=a[b],c[b]=d;return c},U=function(a){var b,c,d,e;for(b=0,d=0,e=a.length;e>d;d++)c=a[d],b+=c;return b},d=P.DepMgr=function(){function a(){this.uid2src={},this.buffering=!1,this.buffer=[]}return a.prototype.sub=function(a,b){return this.uid2src[a]=b},a.prototype.unsub=function(a){return J(this.uid2src,a)},a.prototype.transaction=function(a){var b,c,d,e,f;this.buffering=!0;try{c=a()}finally{for(f=this.buffer,d=0,e=f.length;e>d;d++)(b=f[d])();this.buffer=[],this.buffering=!1}return c},a}(),P._depMgr=x=new d,e=P.Ev=function(){function a(a){this.inits=a,this.subs=D()}return a.prototype.sub=function(a){var b,c,d,e,f;if(c=F(),null!=this.inits)for(f=this.inits(),d=0,e=f.length;e>d;d++)b=f[d],a(b);return this.subs[c]=a,x.sub(c,this),c},a.prototype.pub=function(a){var b,c,d,e,f=this;if(x.buffering)return x.buffer.push(function(){return f.pub(a)});d=this.subs,e=[];for(c in d)b=d[c],e.push(b(a));return e},a.prototype.unsub=function(a){return J(this.subs,a),x.unsub(a,this)},a.prototype.scoped=function(a,b){var c;c=this.sub(a);try{return b()}finally{this.unsub(c)}},a}(),P.skipFirst=function(a){var b;return b=!0,function(){var c;return c=1<=arguments.length?fb.call(arguments,0):[],b?b=!1:a.apply(null,c)}},q=P.Recorder=function(){function a(){this.stack=[],this.isMutating=!1,this.isIgnoring=!1,this.onMutationWarning=new e}return a.prototype.record=function(a,b){var c,d;this.stack.length>0&&!this.isMutating&&_(this.stack).last().addNestedBind(a),this.stack.push(a),d=this.isMutating,this.isMutating=!1,c=this.isIgnoring,this.isIgnoring=!1;try{return b()}finally{this.isIgnoring=c,this.isMutating=d,this.stack.pop()}},a.prototype.sub=function(a){var b,c;return this.stack.length>0&&!this.isIgnoring?(c=_(this.stack).last(),b=a(c)):void 0},a.prototype.addCleanup=function(a){return this.stack.length>0?_(this.stack).last().addCleanup(a):void 0},a.prototype.mutating=function(a){var b;this.stack.length>0&&(console.warn("Mutation to observable detected during a bind context"),this.onMutationWarning.pub(null)),b=this.isMutating,this.isMutating=!0;try{return a()}finally{this.isMutating=b}},a.prototype.ignoring=function(a){var b;b=this.isIgnoring,this.isIgnoring=!0;try{return a()}finally{this.isIgnoring=b}},a}(),P._recorder=O=new q,P.asyncBind=v=function(a,c){var d;return d=new b(c,a),d.refresh(),d},P.bind=w=function(a){return v(null,function(){return this.done(this.record(a))})},P.lagBind=C=function(a,b,c){var d;return d=null,v(b,function(){var b=this;return null!=d&&clearTimeout(d),d=setTimeout(function(){return b.done(b.record(c))},a)})},P.postLagBind=K=function(a,b){var c;return c=null,v(a,function(){var a,d,e,f=this;return e=this.record(b),d=e.val,a=e.ms,null!=c&&clearTimeout(c),c=setTimeout(function(){return f.done(d)},a)})},P.snap=function(a){return O.ignoring(a)},P.onDispose=function(a){return O.addCleanup(a)},P.autoSub=function(a,b){var c;return c=a.sub(b),P.onDispose(function(){return a.unsub(c)}),c},m=P.ObsCell=function(){function a(a){var b,c=this;this.x=a,this.x=null!=(b=this.x)?b:null,this.onSet=new e(function(){return[[null,c.x]]})}return a.prototype.get=function(){var a=this;return O.sub(function(b){return P.autoSub(a.onSet,function(){return b.refresh()})}),this.x},a}(),s=P.SrcCell=function(a){function b(){return ab=b.__super__.constructor.apply(this,arguments)}return hb(b,a),b.prototype.set=function(a){var b=this;return O.mutating(function(){var c;return b.x!==a?(c=b.x,b.x=a,b.onSet.pub([c,a]),c):void 0})},b}(m),b=P.DepCell=function(a){function b(a,c){this.body=a,b.__super__.constructor.call(this,null!=c?c:null),this.refreshing=!1,this.nestedBinds=[],this.cleanups=[]}return hb(b,a),b.prototype.refresh=function(){var a,b,c,d,e,f=this;return this.refreshing?void 0:(c=this.x,d=function(a){return f.x=a,f.onSet.pub([c,f.x])},e=null,b=!1,a={record:function(c){var g,h;if(!f.refreshing){if(f.disconnect(),g)throw new Error("this refresh has already recorded its dependencies");f.refreshing=!0,g=!0;try{h=O.record(f,function(){return c.call(a)})}finally{f.refreshing=!1}return b&&d(e),h}},done:function(a){return c!==a?f.refreshing?(b=!0,e=a):d(a):void 0}},this.body.call(a))},b.prototype.disconnect=function(){var a,b,c,d,e,f,g,h;for(g=this.cleanups,c=0,e=g.length;e>c;c++)(a=g[c])();for(h=this.nestedBinds,d=0,f=h.length;f>d;d++)b=h[d],b.disconnect();return this.nestedBinds=[],this.cleanups=[]},b.prototype.addNestedBind=function(a){return this.nestedBinds.push(a)},b.prototype.addCleanup=function(a){return this.cleanups.push(a)},b}(m),l=P.ObsArray=function(){function a(a,b){var c=this;this.xs=null!=a?a:[],this.diff=null!=b?b:P.basicDiff(),this.onChange=new e(function(){return[[0,[],c.xs]]}),this.indexed_=null}return a.prototype.all=function(){var a=this;return O.sub(function(b){return P.autoSub(a.onChange,function(){return b.refresh()})}),_.clone(this.xs)},a.prototype.raw=function(){var a=this;return O.sub(function(b){return P.autoSub(a.onChange,function(){return b.refresh()})}),this.xs},a.prototype.at=function(a){var b=this;return O.sub(function(c){return P.autoSub(b.onChange,function(b){var d,e,f;return e=b[0],f=b[1],d=b[2],e===a?c.refresh():void 0})}),this.xs[a]},a.prototype.length=function(){var a=this;return O.sub(function(b){return P.autoSub(a.onChange,function(a){var c,d,e;return d=a[0],e=a[1],c=a[2],e.length!==c.length?b.refresh():void 0})}),this.xs.length},a.prototype.map=function(a){var b;return b=new k,P.autoSub(this.onChange,function(c){var d,e,f;return e=c[0],f=c[1],d=c[2],b.realSplice(e,f.length,d.map(a))}),b},a.prototype.indexed=function(){var a=this;return null==this.indexed_&&(this.indexed_=new i,P.autoSub(this.onChange,function(b){var c,d,e;return d=b[0],e=b[1],c=b[2],a.indexed_.realSplice(d,e.length,c)})),this.indexed_},a.prototype.concat=function(a){return P.concat(this,a)},a.prototype.realSplice=function(a,b,c){var d;return d=this.xs.splice.apply(this.xs,[a,b].concat(c)),this.onChange.pub([a,d,c])},a.prototype._update=function(a,b){var c,d,e,f,g,h,i,j,k,l,m,n;for(null==b&&(b=this.diff),g=this.xs,e=[0,g.length,a],j=null,i=null!=b?null!=(m=I(g.length,a,b(g,a)))?m:[e]:[e],n=[],k=0,l=i.length;l>k;k++)h=i[k],f=h[0],d=h[1],c=h[2],n.push(this.realSplice(f,d,c));return n},a}(),r=P.SrcArray=function(a){function b(){return bb=b.__super__.constructor.apply(this,arguments)}return hb(b,a),b.prototype.spliceArray=function(a,b,c){var d=this;return O.mutating(function(){return d.realSplice(a,b,c)})},b.prototype.splice=function(){var a,b,c;return c=arguments[0],b=arguments[1],a=3<=arguments.length?fb.call(arguments,2):[],this.spliceArray(c,b,a)},b.prototype.insert=function(a,b){return this.splice(b,0,a)},b.prototype.remove=function(a){var b;return b=_(this.raw()).indexOf(a),b>=0?this.removeAt(b):void 0},b.prototype.removeAt=function(a){return this.splice(a,1)},b.prototype.push=function(a){return this.splice(this.length(),0,a)},b.prototype.put=function(a,b){return this.splice(a,1,b)},b.prototype.replace=function(a){return this.spliceArray(0,this.length(),a)},b.prototype.update=function(a){var b=this;return O.mutating(function(){return b._update(a)})},b}(l),k=P.MappedDepArray=function(a){function b(){return cb=b.__super__.constructor.apply(this,arguments)}return hb(b,a),b}(l),i=P.IndexedDepArray=function(a){function b(a,c){var d,f,g=this;null==a&&(a=[]),b.__super__.constructor.call(this,a,c),this.is=function(){var a,b,c,e;for(c=this.xs,e=[],d=a=0,b=c.length;b>a;d=++a)f=c[d],e.push(P.cell(d));return e}.call(this),this.onChange=new e(function(){return[[0,[],_.zip(g.xs,g.is)]]})}return hb(b,a),b.prototype.map=function(a){var b;return b=new j,P.autoSub(this.onChange,function(c){var d,e,f,g,h;return g=c[0],h=c[1],e=c[2],b.realSplice(g,h.length,function(){var b,c,g,h;for(h=[],b=0,c=e.length;c>b;b++)g=e[b],d=g[0],f=g[1],h.push(a(d,f));return h}())}),b},b.prototype.realSplice=function(a,b,c){var d,e,f,g,h,i,j,k,l;for(g=(j=this.xs).splice.apply(j,[a,b].concat(fb.call(c))),k=this.is.slice(a+b),f=h=0,i=k.length;i>h;f=++h)d=k[f],d.set(a+c.length+f);return e=function(){var b,e,f;for(f=[],d=b=0,e=c.length;e>=0?e>b:b>e;d=e>=0?++b:--b)f.push(P.cell(a+d));return f}(),(l=this.is).splice.apply(l,[a,b].concat(fb.call(e))),this.onChange.pub([a,g,_.zip(c,e)])},b}(l),j=P.IndexedMappedDepArray=function(a){function b(){return db=b.__super__.constructor.apply(this,arguments)}return hb(b,a),b}(i),a=P.DepArray=function(a){function b(a,c){var d=this;this.f=a,b.__super__.constructor.call(this,[],c),P.autoSub(w(function(){return d.f()}).onSet,function(a){var b,c;return b=a[0],c=a[1],d._update(c)})}return hb(b,a),b}(l),h=P.IndexedArray=function(a){function b(a){this.xs=a}return hb(b,a),b.prototype.map=function(a){var b;return b=new k,P.autoSub(this.xs.onChange,function(c){var d,e,f;return e=c[0],f=c[1],d=c[2],b.realSplice(e,f.length,d.map(a))}),b},b}(a),P.concat=function(){var a,b,c,d;return c=1<=arguments.length?fb.call(arguments,0):[],d=new k,a=function(){var a,d,e;for(e=[],a=0,d=c.length;d>a;a++)b=c[a],e.push(0);return e}(),c.map(function(b,c){return P.autoSub(b.onChange,function(b){var e,f,g,h;return f=b[0],g=b[1],e=b[2],h=U(a.slice(0,c)),a[c]+=e.length-g.length,d.realSplice(h+f,g.length,e)})}),d},g=P.FakeSrcCell=function(a){function b(a,b){this._getter=a,this._setter=b}return hb(b,a),b.prototype.get=function(){return this._getter()},b.prototype.set=function(a){return this._setter(a)},b}(s),f=P.FakeObsCell=function(a){function b(a){this._getter=a}return hb(b,a),b.prototype.get=function(){return this._getter()},b}(m),u=P.MapEntryCell=function(a){function b(a,b){this._map=a,this._key=b}return hb(b,a),b.prototype.get=function(){return this._map.get(this._key)},b.prototype.set=function(a){return this._map.put(this._key,a)},b}(g),o=P.ObsMapEntryCell=function(a){function b(a,b){this._map=a,this._key=b}return hb(b,a),b.prototype.get=function(){return this._map.get(this._key)},b}(f),n=P.ObsMap=function(){function a(a){this.x=null!=a?a:{},this.onAdd=new e(function(){var b,c,d;d=[];for(b in a)c=a[b],d.push([b,c]);return d}),this.onRemove=new e,this.onChange=new e}return a.prototype.get=function(a){var b=this;return O.sub(function(c){return P.autoSub(b.onAdd,function(b){var d,e;return d=b[0],e=b[1],a===d?c.refresh():void 0})}),O.sub(function(c){return P.autoSub(b.onChange,function(b){var d,e,f;return e=b[0],d=b[1],f=b[2],a===e?c.refresh():void 0})}),O.sub(function(c){return P.autoSub(b.onRemove,function(b){var d,e;return e=b[0],d=b[1],a===e?c.refresh():void 0})}),this.x[a]},a.prototype.all=function(){var a=this;return O.sub(function(b){return P.autoSub(a.onAdd,function(){return b.refresh()})}),O.sub(function(b){return P.autoSub(a.onChange,function(){return b.refresh()})}),O.sub(function(b){return P.autoSub(a.onRemove,function(){return b.refresh()})}),_.clone(this.x)},a.prototype.realPut=function(a,b){var c;return a in this.x?(c=this.x[a],this.x[a]=b,this.onChange.pub([a,c,b]),c):(this.x[a]=b,void this.onAdd.pub([a,b]))},a.prototype.realRemove=function(a){var b;return b=J(this.x,a),this.onRemove.pub([a,b]),b},a.prototype.cell=function(a){return new o(this,a)},a}(),t=P.SrcMap=function(a){function b(){return eb=b.__super__.constructor.apply(this,arguments)}return hb(b,a),b.prototype.put=function(a,b){var c=this;return O.mutating(function(){return c.realPut(a,b)})},b.prototype.remove=function(a){var b=this;return O.mutating(function(){return b.realRemove(a)})},b.prototype.cell=function(a){return new u(this,a)},b}(n),c=P.DepMap=function(a){function c(a){this.f=a,c.__super__.constructor.call(this),P.autoSub(new b(this.f).onSet,function(a){var b,c,d,e,f;c=a[0],e=a[1];for(b in c)d=c[b],b in e||this.realRemove(b);f=[];for(b in e)d=e[b],f.push(this.x[b]!==d?this.realPut(b,d):void 0);return f})}return hb(c,a),c}(n),P.liftSpec=function(a){var b,c,d;return _.object(function(){var e,f,g,h;for(g=Object.getOwnPropertyNames(a),h=[],e=0,f=g.length;f>e;e++)b=g[e],d=a[b],null!=d&&(d instanceof P.ObsMap||d instanceof P.ObsCell||d instanceof P.ObsArray)||(c=_.isFunction(d)?null:_.isArray(d)?"array":"cell",h.push([b,{type:c,val:d}]));return h}())},P.lift=function(a,b){var c,d;null==b&&(b=P.liftSpec(a));for(c in b)d=b[c],a[c]=function(){switch(d.type){case"cell":return P.cell(a[c]);case"array":return P.array(a[c]);case"map":return P.map(a[c]);default:return a[c]}}();return a},P.unlift=function(a){var b,c;return _.object(function(){var d;d=[];for(b in a)c=a[b],d.push([b,c instanceof P.ObsCell?c.get():c instanceof P.ObsArray?c.all():c]);return d}())},P.reactify=function(a,b){var c,d,e,f;return _.isArray(a)?(c=P.array(_.clone(a)),Object.defineProperties(a,_.object(function(){var b,e,f,g;for(f=_.functions(c),g=[],b=0,e=f.length;e>b;b++)d=f[b],"length"!==d&&g.push(function(b){var d,e,f;return d=a[b],e=function(){var e,f,g;return e=1<=arguments.length?fb.call(arguments,0):[],null!=d&&(f=d.call.apply(d,[a].concat(fb.call(e)))),(g=c[b]).call.apply(g,[c].concat(fb.call(e))),f},f={configurable:!0,enumerable:!1,value:e,writable:!0},[b,f]}(d));return g}())),a):Object.defineProperties(a,_.object(function(){var a;a=[];for(e in b)f=b[e],a.push(function(a,b){var c,d,e,f,g;switch(c=null,b.type){case"cell":d=P.cell(null!=(f=b.val)?f:null),c={configurable:!0,enumerable:!0,get:function(){return d.get()},set:function(a){return d.set(a)}};break;case"array":e=P.reactify(null!=(g=b.val)?g:[]),c={configurable:!0,enumerable:!0,get:function(){return e.raw(),e},set:function(a){return e.splice.apply(e,[0,e.length].concat(fb.call(a))),e}};break;default:throw new Error("Unknown observable type: "+type)}return[a,c]}(e,f));return a}()))},P.autoReactify=function(a){var b,c,d;return P.reactify(a,_.object(function(){var e,f,g,h;for(g=Object.getOwnPropertyNames(a),h=[],e=0,f=g.length;f>e;e++)b=g[e],d=a[b],d instanceof n||d instanceof m||d instanceof l||(c=_.isFunction(d)?null:_.isArray(d)?"array":"cell",h.push([b,{type:c,val:d}]));return h}()))},_.extend(P,{cell:function(a){return new s(a)},array:function(a,b){return new r(a,b)},map:function(a){return new t(a)}}),P.flatten=function(b){return new a(function(){var a;return _(function(){var c,d,e;for(e=[],c=0,d=b.length;d>c;c++)a=b[c],e.push(a instanceof l?a.raw():a instanceof m?a.get():a);return e}()).chain().flatten(!0).filter(function(a){return null!=a}).value()})},B=function(a){var b;return b=_.flatten(a),P.cellToArray(w(function(){return _.flatten(a)}))},P.cellToArray=function(b,c){return new a(function(){return b.get()},c)},P.basicDiff=function(a){return null==a&&(a=P.smartUidify),function(b,c){var d,e,f,g,h,i,j;for(e=D(function(){var c,e,g;for(g=[],d=c=0,e=b.length;e>c;d=++c)f=b[d],g.push([a(f),d]);return g}()),j=[],g=0,h=c.length;h>g;g++)f=c[g],j.push(null!=(i=e[a(f)])?i:-1);return j}},P.uidify=function(a){var b;return null!=(b=a.__rxUid)?b:Object.defineProperty(a,"__rxUid",{enumerable:!1,value:F()}).__rxUid},P.smartUidify=function(a){return _.isObject(a)?P.uidify(a):JSON.stringify(a)},I=function(a,b,c){var d,e,f,g,h,i;if(g=function(){var a,b,d;for(d=[],a=0,b=c.length;b>a;a++)e=c[a],e>=0&&d.push(e);return d}(),_.some(function(){var a,b,c;for(c=[],e=a=0,b=g.length-1;b>=0?b>a:a>b;e=b>=0?++a:--a)c.push(g[e+1]-g[e]<=0);return c}()))return null;for(i=[],f=-1,e=0;e<c.length;){for(;e<c.length&&c[e]===f+1;)f+=1,e+=1;for(h={index:e,count:0,additions:[]};e<c.length&&-1===c[e];)h.additions.push(b[e]),e+=1;d=e===c.length?a:c[e],h.count=d-(f+1),(h.count>0||h.additions.length>0)&&i.push([h.index,h.count,h.additions]),f=d,e+=1}return i},P.transaction=function(a){return x.transaction(a)},$.fn.rx=function(a){var b,c,d,e;return d=this.data("rx-map"),null==d&&this.data("rx-map",d=D()),a in d?d[a]:d[a]=function(){var d=this;switch(a){case"focused":return c=P.cell(this.is(":focus")),this.focus(function(){return c.set(!0)}),this.blur(function(){return c.set(!1)}),c;case"val":return e=P.cell(this.val()),this.change(function(){return e.set(d.val())}),this.on("input",function(){return e.set(d.val())}),e;case"checked":return b=P.cell(this.is(":checked")),this.change(function(){return b.set(d.is(":checked"))}),b;default:throw new Error("Unknown reactive property type")}}.call(this)},"undefined"==typeof exports?this.rxt=Q={}:Q=exports,p=Q.RawHtml=function(){function a(a){this.html=a}return a}(),z=["blur","change","click","dblclick","error","focus","focusin","focusout","hover","keydown","keypress","keyup","load","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","ready","resize","scroll","select","submit","toggle","unload"],T=Q.specialAttrs={init:function(a,b){return b.call(a)}},X=function(a){return T[a]=function(b,c){return b[a](function(a){return c.call(b,a)})}};for(Y=0,Z=z.length;Z>Y;Y++)y=z[Y],X(y);N=["async","autofocus","checked","location","multiple","readOnly","selected","selectedIndex","tagName","nodeName","nodeType","ownerDocument","defaultChecked","defaultSelected"],M=_.object(function(){var a,b,c;for(c=[],a=0,b=N.length;b>a;a++)L=N[a],c.push([L,null]);return c}()),S=function(a,b,c){return"value"===b?a.val(c):b in M?a.prop(b,c):a.attr(b,c)},R=function(a,b,c,d){return null==d&&(d=_.identity),c instanceof m?P.autoSub(c.onSet,function(c){var e,f;return f=c[0],e=c[1],S(a,b,d(e))}):S(a,b,d(c))},Q.mktag=E=function(a){return function(b,c){var d,e,f,g,h,i,j,k,n,o;n=null==b&&null==c?[{},null]:null!=c?[b,c]:_.isString(b)||b instanceof Element||b instanceof p||b instanceof $||_.isArray(b)||b instanceof m||b instanceof l?[{},b]:[b,null],d=n[0],e=n[1],f=$("<"+a+"/>"),o=_.omit(d,_.keys(T));for(h in o)k=o[h],R(f,h,k);null!=e&&(i=function(a){var b,c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)if(b=a[d],_.isString(b))f.push(document.createTextNode(b));else if(b instanceof Element)f.push(b);else if(b instanceof p){if(c=$(b.html),1!==c.length)throw new Error("RawHtml must wrap a single element");f.push(c[0])}else{if(!(b instanceof $))throw new Error("Unknown element type in array: "+b.constructor.name+" (must be string, Element, RawHtml, or jQuery objects)");if(1!==b.length)throw new Error("jQuery object must wrap a single element");f.push(b[0])}return f},j=function(a){var b;if(f.html(""),!_.isArray(a)){if(_.isString(a)||a instanceof Element||a instanceof p||a instanceof $)return j([a]);throw new Error("Unknown type for element contents: "+a.constructor.name+" (accepted types: string, Element, RawHtml, jQuery object of single element, or array of the aforementioned)")}b=i(a),f.append(b)},e instanceof l?P.autoSub(e.onChange,function(a){var b,c,d,e;return c=a[0],d=a[1],b=a[2],f.contents().slice(c,c+d.length).remove(),e=i(b),c===f.contents().length?f.append(e):f.contents().eq(c).before(e)}):e instanceof m?P.autoSub(e.onSet,function(a){var b,c;return b=a[0],c=a[1],j(c)}):j(e));for(g in d)g in T&&T[g](f,d[g],d,e);return f}},W=["html","head","title","base","link","meta","style","script","noscript","body","body","section","nav","article","aside","h1","h2","h3","h4","h5","h6","h1","h6","header","footer","address","main","main","p","hr","pre","blockquote","ol","ul","li","dl","dt","dd","dd","figure","figcaption","div","a","em","strong","small","s","cite","q","dfn","abbr","data","time","code","var","samp","kbd","sub","sup","i","b","u","mark","ruby","rt","rp","bdi","bdo","span","br","wbr","ins","del","img","iframe","embed","object","param","object","video","audio","source","video","audio","track","video","audio","canvas","map","area","area","map","svg","math","table","caption","colgroup","col","tbody","thead","tfoot","tr","td","th","form","fieldset","legend","fieldset","label","input","button","select","datalist","optgroup","option","select","datalist","textarea","keygen","output","progress","meter","details","summary","details","menuitem","menu"],Q.tags=_.object(function(){var a,b,c;for(c=[],a=0,b=W.length;b>a;a++)V=W[a],c.push([V,Q.mktag(V)]);return c}()),Q.rawHtml=function(a){return new p(a)},Q.importTags=function(a){return _(null!=a?a:ib).extend(Q.tags)},Q.cast=function(a,b){var c,d,e;return _.object(function(){var f;f=[];for(c in a)e=a[c],d=function(){switch(b[c]){case"array":if(e instanceof P.ObsArray)return e;if(_.isArray(e))return new P.DepArray(function(){return e});if(e instanceof P.ObsCell)return new P.DepArray(function(){return e.get()});throw new Error("Cannot cast to array: "+e.constructor.name);case"cell":return e instanceof P.ObsCell?e:w(function(){return e});default:return e}}(),f.push([c,d]);return f}())},Q.cssify=function(a){var b,c;return function(){var d;d=[];for(b in a)c=a[b],null!=c&&d.push(""+_.str.dasherize(b)+": "+(_.isNumber(c)?c+"px":c)+";");return d}().join(" ")},T.style=function(a,b){return R(a,"style",b,function(a){return _.isString(a)?a:Q.cssify(a)})},Q.smushClasses=function(a){return _(a).chain().flatten().compact().value().join(" ").replace(/\s+/," ").trim()},T["class"]=function(a,b){return R(a,"class",b,function(a){return _.isString(a)?a:Q.smushClasses(a)})}}).call(this); |
example/src/main.js | xontab/react-forms-component | import React from 'react';
import ReactDOM from 'react-dom';
import Samples from './Samples';
ReactDOM.render((
<Samples />
), document.getElementById('root')); |
src/components/search_bar.js | auldsyababua/react-tube | import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super (props);
this.state = { term:'' }
}
//line 11 sets state of component with new search term
//line 12 fires the callback function 'onSearchTermChange'
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
render() {
return (
<div className='search-bar'>
< input
value = {this.state.term}
//whenever input value changes, onInputChange is called (line 20)
//with new value passed in. onChange happens after onInputChange method.
onChange = {(event) => this.onInputChange(event.target.value)} />
</div>
)
}
}
export default SearchBar; |
React Fundamentals/EXAM_19.11.2017/exam-app/src/index.js | NikiStanchev/SoftUni | import React from 'react';
import ReactDOM from 'react-dom';
import './style/bootstrap.min.css'
import './style/site.css'
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter as Router } from 'react-router-dom';
import '../node_modules/toastr/build/toastr.min.css'
ReactDOM.render((
<Router>
<App />
</Router>), document.getElementById('root'));
registerServiceWorker();
|
src/routes/NotifList/index.js | addityasingh/build-notification-app | import React from 'react'
import NotifListView from './components/NotifListView'
export default (store) => ({
path : 'home',
getComponent (nextState, cb) {
require.ensure([], () => {
const state = store.getState()
cb(null, () => <NotifListView {...state.user} />)
}, 'home')
},
onEnter: (nextState, replace, cb) => {
const { user } = store.getState()
if(!user && !Object.keys(user).length) {
replace('/')
}
cb()
}
}) |
client/test/components/access/SignUpForm.spec.js | andela-eefekemo/DMS | /* global expect jest test */
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import { SignUpForm } from '../../../components/access/SignUpForm';
describe('SignUpForm Component', () => {
const spy = jest.fn();
beforeEach(() => {
global.Materialize = { toast: jest.fn() };
});
afterEach(() => {
spy.mockReset();
});
const props = {
match: {
path: ''
},
access: {
isAuthenticated: false
},
history: {
push: spy
},
signUpUser: jest.fn(() => {
return Promise.resolve();
})
};
const component = shallow(
<SignUpForm {...props} />);
test('should match the SignUpForm snapshot', () => {
const tree = toJson(component);
expect(component.find('input').length).toEqual(5);
expect(tree).toMatchSnapshot();
});
test('it should set state when onChange function is called', () => {
component.instance().onChange(
{ target: { value: '[email protected]', name: 'email' } });
component.instance().onChange(
{ target: { value: 'eguono', name: 'password' } });
component.instance().onChange(
{ target: { value: 'eguono', name: 'firstName' } });
component.instance().onChange(
{ target: { value: 'eguono', name: 'lastName' } });
component.instance().onChange(
{ target: { value: 'eguono', name: 'confirmPassword' } });
expect(component.state('email')).toEqual('[email protected]');
expect(component.state('password')).toEqual('eguono');
expect(component.state('firstName')).toEqual('eguono');
expect(component.state('lastName')).toEqual('eguono');
expect(component.state('confirmPassword')).toEqual('eguono');
const newspy = jest.spyOn(component.instance(), 'onSubmit');
component.instance().onSubmit();
expect(newspy).toHaveBeenCalled();
});
test(
'it should submit fields in state when onSubmit function is called', () => {
jest.spyOn(component.instance(), 'onSubmit');
component.instance().onChange(
{ target: { value: '[email protected]', name: 'email' } });
component.instance().onChange(
{ target: { value: 'eguono', name: 'password' } });
component.find('#signup-button').simulate('click');
expect(component.find('#signup-button').length).toEqual(1);
expect(component.instance().onSubmit.mock.calls.length).toEqual(2);
});
});
|
ajax/libs/inferno-router/3.1.2/inferno-router.js | wout/cdnjs |
/*!
* Inferno.Router v3.1.2
* (c) 2017 Dominic Gannaway'
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('inferno-create-element'), require('inferno-component'), require('inferno'), require('path-to-regexp')) :
typeof define === 'function' && define.amd ? define(['exports', 'inferno-create-element', 'inferno-component', 'inferno', 'path-to-regexp'], factory) :
(factory((global.Inferno = global.Inferno || {}, global.Inferno.Router = global.Inferno.Router || {}),global.Inferno.createElement,global.Inferno.Component,global.Inferno));
}(this, (function (exports,createElement,Component,Inferno) { 'use strict';
createElement = 'default' in createElement ? createElement['default'] : createElement;
Component = 'default' in Component ? Component['default'] : Component;
var Inferno__default = 'default' in Inferno ? Inferno['default'] : Inferno;
// This should be boolean and not reference to window.document
var isBrowser = !!(typeof window !== 'undefined' && window.document);
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
// this is MUCH faster than .constructor === Array and instanceof Array
// in Node 7 and the later versions of V8, slower in older versions though
var isArray = Array.isArray;
function isString(o) {
return typeof o === 'string';
}
function warning(message) {
// tslint:disable-next-line:no-console
console.warn(message);
}
function combineFrom(first, second) {
var out = {};
if (first) {
for (var key in first) {
out[key] = first[key];
}
}
if (second) {
for (var key$1 in second) {
out[key$1] = second[key$1];
}
}
return out;
}
var emptyObject = {};
function decode(val) {
return typeof val !== 'string' ? val : decodeURIComponent(val);
}
function isEmpty(children) {
return !children || !(isArray(children) ? children : Object.keys(children)).length;
}
function flatten(oldArray) {
var newArray = [];
flattenArray(oldArray, newArray);
return newArray;
}
function getURLString(location) {
return isString(location) ? location : (location.pathname + location.search);
}
/**
* Maps a querystring to an object
* Supports arrays and utf-8 characters
* @param search
* @returns {any}
*/
function mapSearchParams(search) {
if (search === '') {
return {};
}
// Create an object with no prototype
var map = Object.create(null);
var fragments = search.split('&');
for (var i = 0, len = fragments.length; i < len; i++) {
var fragment = fragments[i];
var ref = fragment.split('=').map(mapFragment).map(decodeURIComponent);
var k = ref[0];
var v = ref[1];
if (map[k]) {
map[k] = isArray(map[k]) ? map[k] : [map[k]];
map[k].push(v);
}
else {
map[k] = v;
}
}
return map;
}
/**
* Gets the relevant part of the URL for matching
* @param fullURL
* @param partURL
* @returns {string}
*/
function toPartialURL(fullURL, partURL) {
if (fullURL.indexOf(partURL) === 0) {
return fullURL.substr(partURL.length);
}
return fullURL;
}
/**
* Simulates ... operator by returning first argument
* with the keys in the second argument excluded
* @param _args
* @param excluded
* @returns {{}}
*/
function rest(_args, excluded) {
var t = {};
for (var p in _args) {
if (excluded.indexOf(p) < 0) {
t[p] = _args[p];
}
}
return t;
}
/**
* Sorts an array according to its `path` prop length
* @param a
* @param b
* @returns {number}
*/
function pathRankSort(a, b) {
var aAttr = a.props || emptyObject;
var bAttr = b.props || emptyObject;
var diff = rank(bAttr.path) - rank(aAttr.path);
return diff || ((bAttr.path && aAttr.path) ? (bAttr.path.length - aAttr.path.length) : 0);
}
/**
* Helper function for parsing querystring arrays
*/
function mapFragment(p, isVal) {
return decodeURIComponent(isVal | 0 ? p : p.replace('[]', ''));
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function rank(url) {
if ( url === void 0 ) url = '';
return (strip(url).match(/\/+/g) || '').length;
}
function flattenArray(oldArray, newArray) {
for (var i = 0, len = oldArray.length; i < len; i++) {
var item = oldArray[i];
if (isArray(item)) {
flattenArray(item, newArray);
}
else {
newArray.push(item);
}
}
}
var resolvedPromise = Promise.resolve();
var Route = (function (Component$$1) {
function Route(props, context) {
var this$1 = this;
Component$$1.call(this, props, context);
this._onComponentResolved = function (error, component) {
this$1.setState({
asyncComponent: component
});
};
this.state = {
asyncComponent: null
};
}
if ( Component$$1 ) Route.__proto__ = Component$$1;
Route.prototype = Object.create( Component$$1 && Component$$1.prototype );
Route.prototype.constructor = Route;
Route.prototype.componentWillMount = function componentWillMount () {
var this$1 = this;
var ref = this.props;
var onEnter = ref.onEnter;
var ref$1 = this.context;
var router = ref$1.router;
if (onEnter) {
resolvedPromise.then(function () {
onEnter({ props: this$1.props, router: router });
});
}
var ref$2 = this.props;
var getComponent = ref$2.getComponent;
if (getComponent) {
resolvedPromise.then(function () {
getComponent({ props: this$1.props, router: router }, this$1._onComponentResolved);
});
}
};
Route.prototype.onLeave = function onLeave (trigger) {
if ( trigger === void 0 ) trigger = false;
var ref = this.props;
var onLeave = ref.onLeave;
var ref$1 = this.context;
var router = ref$1.router;
if (onLeave && trigger) {
onLeave({ props: this.props, router: router });
}
};
Route.prototype.onEnter = function onEnter (nextProps) {
var onEnter = nextProps.onEnter;
var ref = this.context;
var router = ref.router;
if (this.props.path !== nextProps.path && onEnter) {
onEnter({ props: nextProps, router: router });
}
};
Route.prototype.getComponent = function getComponent (nextProps) {
var getComponent = nextProps.getComponent;
var ref = this.context;
var router = ref.router;
if (this.props.path !== nextProps.path && getComponent) {
getComponent({ props: nextProps, router: router }, this._onComponentResolved);
}
};
Route.prototype.componentWillUnmount = function componentWillUnmount () {
this.onLeave(true);
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps) {
this.getComponent(nextProps);
this.onEnter(nextProps);
this.onLeave(this.props.path !== nextProps.path);
};
Route.prototype.render = function render (_args) {
var component = _args.component;
var children = _args.children;
var props = rest(_args, ['component', 'children', 'path', 'getComponent']);
var ref = this.state;
var asyncComponent = ref.asyncComponent;
var resolvedComponent = component || asyncComponent;
if (!resolvedComponent) {
return !isArray(children) ? children : null;
}
return createElement(resolvedComponent, props, children);
};
return Route;
}(Component));
/**
* Helper function for parsing plain route configurations
* based on react-router createRoutes handler.
*
* currently supported keys:
* - path
* - component
* - childRoutes
* - indexRoute
*
* Usage example:
* const routes = createRoutes([
* {
* path : '/',
* component : App,
* indexRoute : {
* component : Home,
* },
* childRoutes : [
* {
* path : 'films/',
* component : Films,
* childRoutes : {
* path : 'detail/:id',
* component : FilmDetail,
* }
* },
* {
* path : '/*',
* component : NoMatch
* }
* ]
* }
* ]);
*
* Usage on Router JSX
* <Router history={browserHistory} children={routes} />
*/
var handleIndexRoute = function (indexRouteNode) { return createElement(Route, indexRouteNode); };
var handleChildRoute = function (childRouteNode) { return handleRouteNode(childRouteNode); };
var handleChildRoutes = function (childRouteNodes) { return childRouteNodes.map(handleChildRoute); };
function handleRouteNode(routeConfigNode) {
if (routeConfigNode.indexRoute && !routeConfigNode.childRoutes) {
return createElement(Route, routeConfigNode);
}
// create deep copy of config
var node = {};
for (var key in routeConfigNode) {
node[key] = routeConfigNode[key];
}
node.children = [];
// handle index route config
if (node.indexRoute) {
node.children.push(handleIndexRoute(node.indexRoute));
delete node.indexRoute;
}
// handle child routes config
if (node.childRoutes) {
var nodes = isArray(node.childRoutes) ? node.childRoutes : [node.childRoutes];
(ref = node.children).push.apply(ref, handleChildRoutes(nodes));
delete node.childRoutes;
}
// cleanup to match native rendered result
if (node.children.length === 1) {
node.children = node.children[0];
}
if ((isArray(node.children) && node.children.length === 0) ||
(!isArray(node.children) && Object.keys(node.children).length === 0)) {
delete node.children;
}
return createElement(Route, node);
var ref;
}
var createRoutes = function (routeConfig) { return routeConfig.map(handleRouteNode); };
var __rest = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
{ t[p] = s[p]; } }
if (s != null && typeof Object.getOwnPropertySymbols === "function")
{ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0)
{ t[p[i]] = s[p[i]]; } } }
return t;
};
function renderLink(classNm, children, otherProps) {
return Inferno.createVNode(2 /* HtmlElement */, 'a', classNm, children, otherProps);
}
function Link(props, ref) {
var router = ref.router;
var activeClassName = props.activeClassName;
var activeStyle = props.activeStyle;
var className = props.className;
var onClick = props.onClick;
var children = props.children;
var to = props.to;
var otherProps = __rest(props, ["activeClassName", "activeStyle", "className", "onClick", "children", "to"]);
var classNm;
if (className) {
classNm = className;
}
if (!router) {
{
warning('<Link/> component used outside of <Router/>. Fallback to <a> tag.');
}
otherProps.href = to;
otherProps.onClick = onClick;
return renderLink(classNm, children, otherProps);
}
otherProps.href = isBrowser ? router.createHref({ pathname: to }) : router.location.baseUrl ? router.location.baseUrl + to : to;
if (router.location.pathname === to) {
if (activeClassName) {
classNm = (className ? className + ' ' : '') + activeClassName;
}
if (activeStyle) {
otherProps.style = combineFrom(props.style, activeStyle);
}
}
otherProps.onclick = function navigate(e) {
if (e.button !== 0 || e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) {
return;
}
e.preventDefault();
if (typeof onClick === 'function') {
onClick(e);
}
router.push(to, e.target.textContent);
};
return renderLink(classNm, children, otherProps);
}
function IndexLink(props) {
props.to = '/';
return Inferno.createVNode(8 /* ComponentFunction */, Link, null, null, props);
}
var IndexRoute = (function (Route$$1) {
function IndexRoute(props, context) {
Route$$1.call(this, props, context);
props.path = '/';
}
if ( Route$$1 ) IndexRoute.__proto__ = Route$$1;
IndexRoute.prototype = Object.create( Route$$1 && Route$$1.prototype );
IndexRoute.prototype.constructor = IndexRoute;
return IndexRoute;
}(Route));
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var index$5 = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/**
* Expose `pathToRegexp`.
*/
var index$2 = pathToRegexp$1;
var parse_1 = parse;
var compile_1 = compile;
var tokensToFunction_1 = tokensToFunction;
var tokensToRegExp_1 = tokensToRegExp;
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g');
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse (str, options) {
var tokens = [];
var key = 0;
var index = 0;
var path = '';
var defaultDelimiter = options && options.delimiter || '/';
var res;
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0];
var escaped = res[1];
var offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
continue
}
var next = str[index];
var prefix = res[2];
var name = res[3];
var capture = res[4];
var group = res[5];
var modifier = res[6];
var asterisk = res[7];
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
}
var partial = prefix != null && next != null && next !== prefix;
var repeat = modifier === '+' || modifier === '*';
var optional = modifier === '?' || modifier === '*';
var delimiter = res[2] || defaultDelimiter;
var pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
});
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index);
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path);
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile (str, options) {
return tokensToFunction(parse(str, options))
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty (str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk (str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length);
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
}
}
return function (obj, opts) {
var path = '';
var data = obj || {};
var options = opts || {};
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue
}
var value = data[token.name];
var segment;
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix;
}
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (index$5(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j]);
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment;
}
continue
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value);
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment;
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup (group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
function attachKeys (re, keys) {
re.keys = keys;
return re
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags (options) {
return options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
function regexpToRegexp (path, keys) {
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null
});
}
}
return attachKeys(path, keys)
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function arrayToRegexp (path, keys, options) {
var parts = [];
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp$1(path[i], keys, options).source);
}
var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
return attachKeys(regexp, keys)
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function stringToRegexp (path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp (tokens, keys, options) {
if (!index$5(keys)) {
options = /** @type {!Object} */ (keys || options);
keys = [];
}
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var route = '';
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
} else {
var prefix = escapeString(token.prefix);
var capture = '(?:' + token.pattern + ')';
keys.push(token);
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*';
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?';
} else {
capture = prefix + '(' + capture + ')?';
}
} else {
capture = prefix + '(' + capture + ')';
}
route += capture;
}
}
var delimiter = escapeString(options.delimiter || '/');
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
}
if (end) {
route += '$';
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
}
return attachKeys(new RegExp('^' + route, flags(options)), keys)
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp$1 (path, keys, options) {
if (!index$5(keys)) {
options = /** @type {!Object} */ (keys || options);
keys = [];
}
options = options || {};
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */ (keys))
}
if (index$5(path)) {
return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
}
return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
}
index$2.parse = parse_1;
index$2.compile = compile_1;
index$2.tokensToFunction = tokensToFunction_1;
index$2.tokensToRegExp = tokensToRegExp_1;
var index$4 = Object.freeze({
default: index$2,
__moduleExports: index$2,
parse: parse_1,
compile: compile_1,
tokensToFunction: tokensToFunction_1,
tokensToRegExp: tokensToRegExp_1
});
var pathToRegExp$1 = ( index$4 && index$2 ) || index$4;
var index$1 = createCommonjsModule(function (module) {
/**
* Expose `pathToRegexp` as ES6 module
*/
module.exports = pathToRegExp$1;
module.exports.parse = pathToRegExp$1.parse;
module.exports.compile = pathToRegExp$1.compile;
module.exports.tokensToFunction = pathToRegExp$1.tokensToFunction;
module.exports.tokensToRegExp = pathToRegExp$1.tokensToRegExp;
module.exports['default'] = module.exports;
});
var cache = new Map();
/**
* Returns a node containing only the matched components
* @param routes
* @param currentURL
* @returns {*}
*/
function match(routes, currentURL) {
var location = getURLString(currentURL);
return matchRoutes(toArray(routes), encodeURI(location), '/');
}
/**
* Go through every route and create a new node
* with the matched components
* @param _routes
* @param currentURL
* @param parentPath
* @param redirect
* @returns {object}
*/
function matchRoutes(_routes, currentURL, parentPath, redirect) {
if ( currentURL === void 0 ) currentURL = '/';
if ( parentPath === void 0 ) parentPath = '/';
if ( redirect === void 0 ) redirect = false;
var routes = isArray(_routes) ? flatten(_routes) : toArray(_routes);
var ref = currentURL.split('?');
var pathToMatch = ref[0]; if ( pathToMatch === void 0 ) pathToMatch = '/';
var search = ref[1]; if ( search === void 0 ) search = '';
var params = mapSearchParams(search);
routes.sort(pathRankSort);
for (var i = 0, len = routes.length; i < len; i++) {
var route = routes[i];
var props = route.props || emptyObject;
var routePath = props.from || props.path || '/';
var location = parentPath + toPartialURL(routePath, parentPath).replace(/\/\//g, '/');
var isLast = isEmpty(props.children);
var matchBase = matchPath(isLast, location, pathToMatch);
if (matchBase) {
var children = props.children;
if (props.from) {
redirect = props.to;
}
if (children) {
var matchChild = matchRoutes(children, currentURL, location, redirect);
if (matchChild) {
if (matchChild.redirect) {
return {
location: location,
redirect: matchChild.redirect
};
}
children = matchChild.matched;
var childProps = children.props.params;
for (var key in childProps) {
params[key] = childProps[key];
}
}
else {
children = null;
}
}
var matched = Inferno__default.cloneVNode(route, {
params: combineFrom(params, matchBase.params),
children: children
});
return {
location: location,
redirect: redirect,
matched: matched
};
}
}
}
/**
* Converts path to a regex, if a match is found then we extract params from it
* @param end
* @param routePath
* @param pathToMatch
* @returns {any}
*/
function matchPath(end, routePath, pathToMatch) {
var key = routePath + "|" + end;
var regexp = cache.get(key);
if (regexp === void 0) {
var keys = [];
regexp = { pattern: index$1(routePath, keys, { end: end }), keys: keys };
cache.set(key, regexp);
}
var m = regexp.pattern.exec(pathToMatch);
if (!m) {
return null;
}
var path = m[0];
var params = Object.create(null);
for (var i = 1, len = m.length; i < len; i += 1) {
params[regexp.keys[i - 1].name] = decode(m[i]);
}
return {
path: path === '' ? '/' : path,
params: params
};
}
var Redirect = (function (Route$$1) {
function Redirect(props, context) {
Route$$1.call(this, props, context);
if (!props.to) {
props.to = '/';
}
}
if ( Route$$1 ) Redirect.__proto__ = Route$$1;
Redirect.prototype = Object.create( Route$$1 && Route$$1.prototype );
Redirect.prototype.constructor = Redirect;
return Redirect;
}(Route));
var RouterContext = (function (Component$$1) {
function RouterContext(props, context) {
Component$$1.call(this, props, context);
{
if (!props.location || !props.matched) {
throw new TypeError('"inferno-router" requires a "location" and "matched" props passed');
}
}
}
if ( Component$$1 ) RouterContext.__proto__ = Component$$1;
RouterContext.prototype = Object.create( Component$$1 && Component$$1.prototype );
RouterContext.prototype.constructor = RouterContext;
RouterContext.prototype.getChildContext = function getChildContext () {
return {
router: this.props.router || {
location: {
baseUrl: this.props.baseUrl,
pathname: this.props.location
}
}
};
};
RouterContext.prototype.render = function render (props) {
return props.matched;
};
return RouterContext;
}(Component));
function createrRouter(history) {
if (!history) {
throw new TypeError('Inferno: Error "inferno-router" requires a history prop passed');
}
return {
createHref: history.createHref,
listen: history.listen,
push: history.push,
replace: history.replace,
isActive: function isActive(url) {
return matchPath(true, url, this.url);
},
get location() {
return history.location.pathname !== 'blank' ? history.location : {
pathname: '/',
search: ''
};
},
get url() {
return this.location.pathname + this.location.search;
}
};
}
var Router = (function (Component$$1) {
function Router(props, context) {
Component$$1.call(this, props, context);
this.router = createrRouter(props.history);
this.state = {
url: props.url || this.router.url
};
}
if ( Component$$1 ) Router.__proto__ = Component$$1;
Router.prototype = Object.create( Component$$1 && Component$$1.prototype );
Router.prototype.constructor = Router;
Router.prototype.componentWillMount = function componentWillMount () {
var this$1 = this;
if (this.router) {
this.unlisten = this.router.listen(function () {
this$1.routeTo(this$1.router.url);
});
}
};
Router.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps) {
var this$1 = this;
this.setState({ url: nextProps.url }, this.props.onUpdate ? function () { return this$1.props.onUpdate(); } : void 0);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
if (this.unlisten) {
this.unlisten();
}
};
Router.prototype.routeTo = function routeTo (url) {
var this$1 = this;
this.setState({ url: url }, this.props.onUpdate ? function () { return this$1.props.onUpdate(); } : void 0);
};
Router.prototype.render = function render (props) {
var this$1 = this;
var hit = match(props.children, this.state.url);
if (hit.redirect) {
setTimeout(function () {
this$1.router.replace(hit.redirect);
}, 0);
return null;
}
return Inferno.createVNode(4 /* ComponentClass */, RouterContext, null, null, {
location: this.state.url,
matched: hit.matched,
router: this.router
});
};
return Router;
}(Component));
var index = {
Route: Route,
IndexRoute: IndexRoute,
Redirect: Redirect,
IndexRedirect: Redirect,
Router: Router,
RouterContext: RouterContext,
Link: Link,
IndexLink: IndexLink,
match: match,
createRoutes: createRoutes
};
exports.Route = Route;
exports.IndexRoute = IndexRoute;
exports.Redirect = Redirect;
exports.IndexRedirect = Redirect;
exports.Router = Router;
exports.RouterContext = RouterContext;
exports.Link = Link;
exports.IndexLink = IndexLink;
exports.match = match;
exports.createRoutes = createRoutes;
exports['default'] = index;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
src/svg-icons/image/hdr-off.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageHdrOff = (props) => (
<SvgIcon {...props}>
<path d="M17.5 15v-2h1.1l.9 2H21l-.9-2.1c.5-.2.9-.8.9-1.4v-1c0-.8-.7-1.5-1.5-1.5H16v4.9l1.1 1.1h.4zm0-4.5h2v1h-2v-1zm-4.5 0v.4l1.5 1.5v-1.9c0-.8-.7-1.5-1.5-1.5h-1.9l1.5 1.5h.4zm-3.5-1l-7-7-1.1 1L6.9 9h-.4v2h-2V9H3v6h1.5v-2.5h2V15H8v-4.9l1.5 1.5V15h3.4l7.6 7.6 1.1-1.1-12.1-12z"/>
</SvgIcon>
);
ImageHdrOff = pure(ImageHdrOff);
ImageHdrOff.displayName = 'ImageHdrOff';
ImageHdrOff.muiName = 'SvgIcon';
export default ImageHdrOff;
|
Docker/KlusterKiteMonitoring/klusterkite-web/src/components/ConfigurationOperations/ReadyOperations.js | KlusterKite/KlusterKite | import React from 'react';
import Relay from 'react-relay'
import Icon from 'react-fa';
import delay from 'lodash/delay'
import Modal from '../Form/Modal'
import CreateMigrationMutation from './mutations/CreateMigrationMutation';
import SetObsoleteMutation from './mutations/SetObsoleteMutation';
import './styles.css';
export class ReadyOperations extends React.Component {
constructor(props) {
super(props);
this.state = {
isUpdating: false,
updateSuccessful: false,
isSettingObsolete: false,
setObsoleteSuccessful: false,
isChangingState: false,
showConfirmationUpdate: false,
showConfirmationObsolete: false,
};
}
static propTypes = {
configurationId: React.PropTypes.string.isRequired,
configurationInnerId: React.PropTypes.number.isRequired,
currentState: React.PropTypes.string.isRequired,
onForceFetch: React.PropTypes.func.isRequired,
canCreateMigration: React.PropTypes.bool.isRequired,
onStartMigration: React.PropTypes.func.isRequired,
currentMigration: React.PropTypes.object,
operationIsInProgress: React.PropTypes.bool,
resourceInNonSourcePosition: React.PropTypes.bool,
resourceIsObsolete: React.PropTypes.bool,
};
onStartMigrationConfirmRequest = () => {
this.setState({
showConfirmationUpdate: true
});
};
onStartMigrationCancel = () => {
this.setState({
showConfirmationUpdate: false
});
};
onStartMigration = () => {
if (!this.state.isStartingMigration){
this.setState({
isStartingMigration: true,
setStableSuccessful: false,
isChangingState: true
});
Relay.Store.commitUpdate(
new CreateMigrationMutation(
{
configurationId: this.props.configurationInnerId,
}),
{
onSuccess: (response) => {
console.log('response', response);
if (response.klusterKiteNodeApi_klusterKiteNodesApi_clusterManagement_migrationCreate.errors &&
response.klusterKiteNodeApi_klusterKiteNodesApi_clusterManagement_migrationCreate.errors.edges) {
const messages = this.getErrorMessagesFromEdge(response.klusterKiteNodeApi_klusterKiteNodesApi_clusterManagement_migrationCreate.errors.edges);
this.setState({
isStartingMigration: false,
setStableErrors: messages
});
} else {
console.log('result create migration', response.klusterKiteNodeApi_klusterKiteNodesApi_clusterManagement_migrationCreate.result);
// total success
this.setState({
isStartingMigration: false,
setStableErrors: null,
setStableSuccessful: true,
showConfirmationUpdate: false
});
this.props.onStartMigration();
}
},
onFailure: (transaction) => {
this.setState({
isStartingMigration: false
});
console.log(transaction)},
},
);
}
};
goToMigration = () => {
this.props.onStartMigration();
};
onSetObsoleteConfirmation = () => {
this.setState({
showConfirmationObsolete: true
});
};
onSetObsoleteCancel = () => {
this.setState({
showConfirmationObsolete: false
});
};
onSetObsolete = () => {
if (!this.state.isRollbacking){
console.log('set obsolete');
this.setState({
isRollbacking: true,
rollbackSuccessful: false,
isChangingState: true
});
Relay.Store.commitUpdate(
new SetObsoleteMutation(
{
configurationId: this.props.configurationInnerId,
}),
{
onSuccess: (response) => {
console.log('response', response);
if (response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_setObsolete.errors &&
response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_setObsolete.errors.edges) {
const messages = this.getErrorMessagesFromEdge(response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_setObsolete.errors.edges);
this.setState({
isRollbacking: false,
rollbackErrors: messages
});
} else {
console.log('result set obsolete', response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_setObsolete);
// total success
this.setState({
isRollbacking: false,
rollbackErrors: null,
rollbackSuccessful: true,
showConfirmationObsolete: false,
});
this.refetchAfterDelay(5000);
}
},
onFailure: (transaction) => {
this.setState({
isRollbacking: false
});
console.log(transaction)},
},
);
}
};
/**
* Refetches data from GraphQL server after a delay
* @param delayTime {number} Delay in ms
*/
refetchAfterDelay = (delayTime) => {
delay(() => {
this.props.onForceFetch();
}, delayTime);
delay(() => {
this.setState({
isChangingState: false
});
}, delayTime + 1000);
};
getErrorMessagesFromEdge = (edges) => {
return edges.map(x => x.node).map(x => x.message);
};
render() {
let startMigrationClassName = '';
if (this.state.isStartingMigration) {
startMigrationClassName += ' fa-spin';
}
let setObsoleteClassName = '';
if (this.state.isRollbacking) {
setObsoleteClassName += ' fa-spin';
}
const shouldBeAbleToCreateMigration = this.props.currentState && this.props.currentState === 'Ready' && this.props.canCreateMigration && !this.state.isChangingState;
let cantCreateMigrationReason = null;
if (shouldBeAbleToCreateMigration && !this.props.canCreateMigration)
{
if (this.props.operationIsInProgress) {
cantCreateMigrationReason = 'Operation is in progress';
}
if (this.props.resourceInNonSourcePosition) {
cantCreateMigrationReason = 'At least one resource is not in Source position';
}
if (this.props.resourceIsObsolete) {
cantCreateMigrationReason = 'At least one node is obsolete';
}
}
return (
<div>
{this.state.setStableErrors && this.state.setStableErrors.map((error, index) => {
return (
<div className="alert alert-danger" role="alert" key={`error-${index}`}>
<span className="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
{' '}
{error}
</div>
);
})
}
{this.state.setStableSuccessful && !this.state.isChangingState &&
<div>
<div className="alert alert-success" role="alert">
<span className="glyphicon glyphicon-ok" aria-hidden="true"></span>
{' '}
Update cluster successful!
</div>
</div>
}
{this.state.rollbackErrors && this.state.rollbackErrors.map((error, index) => {
return (
<div className="alert alert-danger" role="alert" key={`error-${index}`}>
<span className="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
{' '}
{error}
</div>
);
})
}
{this.state.rollbackSuccessful && !this.state.isChangingState &&
<div>
<div className="alert alert-success" role="alert">
<span className="glyphicon glyphicon-ok" aria-hidden="true"></span>
{' '}
Set obsolete successful!
</div>
</div>
}
{shouldBeAbleToCreateMigration && !this.props.canCreateMigration &&
<div>
<div className="alert alert-warning" role="alert">
<span className="glyphicon glyphicon-alert" aria-hidden="true"></span>
{' '}
Can't create migration: {cantCreateMigrationReason || 'Reason unknown'}
</div>
</div>
}
{shouldBeAbleToCreateMigration && this.props.canCreateMigration &&
<button className="btn btn-primary" type="button" onClick={this.onStartMigrationConfirmRequest}>
<Icon name="wrench" className={startMigrationClassName}/>{' '}Start migration
</button>
}
{this.props.currentState && this.props.currentState === 'Ready' && this.props.currentMigration &&
<button className="btn btn-primary" type="button" onClick={this.goToMigration}>
<Icon name="wrench" />{' '}Manage migration
</button>
}
{this.props.currentState && this.props.currentState === 'Ready' && !this.state.isChangingState &&
<button className="btn btn-danger btn-margined" type="button" onClick={this.onSetObsoleteConfirmation}>
<Icon name="trash" className={setObsoleteClassName}/>{' '}Set obsolete
</button>
}
{this.state.isChangingState &&
<div className="alert alert-warning" role="alert">
<span className="glyphicon glyphicon-time" aria-hidden="true"></span>
{' '}
Please wait, expecting server reply…
</div>
}
{this.state.showConfirmationUpdate &&
<Modal title="Are you sure?" confirmText="Start migration"
onCancel={this.onStartMigrationCancel.bind(this)}
onConfirm={this.onStartMigration.bind(this)}
confirmClass="primary"
>
Are you ready to start migration?
</Modal>
}
{this.state.showConfirmationObsolete &&
<Modal title="Are you sure?" confirmText="Set obsolete"
onCancel={this.onSetObsoleteCancel.bind(this)}
onConfirm={this.onSetObsolete.bind(this)}
>
You will not be able to use this configuration after obsoleting it.
</Modal>
}
</div>
);
}
}
export default ReadyOperations
|
public/app/components/application.js | vincent-tr/mylife-home-ui | 'use strict';
import React from 'react';
const Application = ({ children }) => (
<div>
{ children }
</div>
);
Application.propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.node),
React.PropTypes.node
])
};
export default Application;
|
app/javascript/mastodon/features/introduction/index.js | imas/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ReactSwipeableViews from 'react-swipeable-views';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { closeOnboarding } from '../../actions/onboarding';
import screenHello from '../../../images/screen_hello.svg';
import screenFederation from '../../../images/screen_federation.svg';
import screenInteractions from '../../../images/screen_interactions.svg';
import logoTransparent from '../../../images/logo_transparent.svg';
import { disableSwiping } from 'mastodon/initial_state';
const FrameWelcome = ({ domain, onNext }) => (
<div className='introduction__frame'>
<div className='introduction__illustration' style={{ background: `url(${logoTransparent}) no-repeat center center / auto 80%` }}>
<img src={screenHello} alt='' />
</div>
<div className='introduction__text introduction__text--centered'>
<h3><FormattedMessage id='introduction.welcome.headline' defaultMessage='First steps' /></h3>
<p><FormattedMessage id='introduction.welcome.text' defaultMessage="Welcome to the fediverse! In a few moments, you'll be able to broadcast messages and talk to your friends across a wide variety of servers. But this server, {domain}, is special—it hosts your profile, so remember its name." values={{ domain: <code>{domain}</code> }} /></p>
</div>
<div className='introduction__action'>
<button className='button' onClick={onNext}><FormattedMessage id='introduction.welcome.action' defaultMessage="Let's go!" /></button>
</div>
</div>
);
FrameWelcome.propTypes = {
domain: PropTypes.string.isRequired,
onNext: PropTypes.func.isRequired,
};
const FrameFederation = ({ onNext }) => (
<div className='introduction__frame'>
<div className='introduction__illustration'>
<img src={screenFederation} alt='' />
</div>
<div className='introduction__text introduction__text--columnized'>
<div>
<h3><FormattedMessage id='introduction.federation.home.headline' defaultMessage='Home' /></h3>
<p><FormattedMessage id='introduction.federation.home.text' defaultMessage='Posts from people you follow will appear in your home feed. You can follow anyone on any server!' /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.federation.local.headline' defaultMessage='Local' /></h3>
<p><FormattedMessage id='introduction.federation.local.text' defaultMessage='Public posts from people on the same server as you will appear in the local timeline.' /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.federation.federated.headline' defaultMessage='Federated' /></h3>
<p><FormattedMessage id='introduction.federation.federated.text' defaultMessage='Public posts from other servers of the fediverse will appear in the federated timeline.' /></p>
</div>
</div>
<div className='introduction__action'>
<button className='button' onClick={onNext}><FormattedMessage id='introduction.federation.action' defaultMessage='Next' /></button>
</div>
</div>
);
FrameFederation.propTypes = {
onNext: PropTypes.func.isRequired,
};
const FrameInteractions = ({ onNext }) => (
<div className='introduction__frame'>
<div className='introduction__illustration'>
<img src={screenInteractions} alt='' />
</div>
<div className='introduction__text introduction__text--columnized'>
<div>
<h3><FormattedMessage id='introduction.interactions.reply.headline' defaultMessage='Reply' /></h3>
<p><FormattedMessage id='introduction.interactions.reply.text' defaultMessage="You can reply to other people's and your own toots, which will chain them together in a conversation." /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.interactions.reblog.headline' defaultMessage='Boost' /></h3>
<p><FormattedMessage id='introduction.interactions.reblog.text' defaultMessage="You can share other people's toots with your followers by boosting them." /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.interactions.favourite.headline' defaultMessage='Favourite' /></h3>
<p><FormattedMessage id='introduction.interactions.favourite.text' defaultMessage='You can save a toot for later, and let the author know that you liked it, by favouriting it.' /></p>
</div>
</div>
<div className='introduction__action'>
<button className='button' onClick={onNext}><FormattedMessage id='introduction.interactions.action' defaultMessage='Finish toot-orial!' /></button>
</div>
</div>
);
FrameInteractions.propTypes = {
onNext: PropTypes.func.isRequired,
};
export default @connect(state => ({ domain: state.getIn(['meta', 'domain']) }))
class Introduction extends React.PureComponent {
static propTypes = {
domain: PropTypes.string.isRequired,
dispatch: PropTypes.func.isRequired,
};
state = {
currentIndex: 0,
};
componentWillMount () {
this.pages = [
<FrameWelcome domain={this.props.domain} onNext={this.handleNext} />,
<FrameFederation onNext={this.handleNext} />,
<FrameInteractions onNext={this.handleFinish} />,
];
}
componentDidMount() {
window.addEventListener('keyup', this.handleKeyUp);
}
componentWillUnmount() {
window.addEventListener('keyup', this.handleKeyUp);
}
handleDot = (e) => {
const i = Number(e.currentTarget.getAttribute('data-index'));
e.preventDefault();
this.setState({ currentIndex: i });
}
handlePrev = () => {
this.setState(({ currentIndex }) => ({
currentIndex: Math.max(0, currentIndex - 1),
}));
}
handleNext = () => {
const { pages } = this;
this.setState(({ currentIndex }) => ({
currentIndex: Math.min(currentIndex + 1, pages.length - 1),
}));
}
handleSwipe = (index) => {
this.setState({ currentIndex: index });
}
handleFinish = () => {
this.props.dispatch(closeOnboarding());
}
handleKeyUp = ({ key }) => {
switch (key) {
case 'ArrowLeft':
this.handlePrev();
break;
case 'ArrowRight':
this.handleNext();
break;
}
}
render () {
const { currentIndex } = this.state;
const { pages } = this;
return (
<div className='introduction'>
<ReactSwipeableViews index={currentIndex} onChangeIndex={this.handleSwipe} disabled={disableSwiping} className='introduction__pager'>
{pages.map((page, i) => (
<div key={i} className={classNames('introduction__frame-wrapper', { 'active': i === currentIndex })}>{page}</div>
))}
</ReactSwipeableViews>
<div className='introduction__dots'>
{pages.map((_, i) => (
<div
key={`dot-${i}`}
role='button'
tabIndex='0'
data-index={i}
onClick={this.handleDot}
className={classNames('introduction__dot', { active: i === currentIndex })}
/>
))}
</div>
</div>
);
}
}
|
src/containers/DevTools.js | oldsaratov/postcards-spa | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q' >
<LogMonitor />
</DockMonitor>
);
|
app/containers/HomePage/HomePage.js | mfi-dev/jag-kiosk | import React from 'react'
import LinkBox from '../../components/LinkBox'
import './HomePage.styl'
class HomePage extends React.Component {
render () {
return (
<div className='Page'>
<div className='Seal'>
<img src='assets/images/jag-seal.png' />
</div>
<nav className='MainMenu'>
<LinkBox link='/early-years' title='Early Years' />
<LinkBox link='/modern-era' title='Modern Era' />
<LinkBox link='/todays-force' title="Today's Force" />
</nav>
</div>
)
}
}
export default HomePage
|
ajax/libs/ionic/0.9.17-alpha/js/ionic.js | gereon/cdnjs | /*!
* Copyright 2013 Drifty Co.
* http://drifty.com/
*
* Ionic, v0.9.17
* A powerful HTML5 mobile app framework.
* http://ionicframework.com/
*
* By @maxlynch, @helloimben, @adamdbradley <3
*
* Licensed under the MIT license. Please see LICENSE for more information.
*
*/;
// Create namespaces
window.ionic = {
controllers: {},
views: {},
version: '0.9.17'
};;
(function(ionic) {
var bezierCoord = function (x,y) {
if(!x) x=0;
if(!y) y=0;
return {x: x, y: y};
};
function B1(t) { return t*t*t; }
function B2(t) { return 3*t*t*(1-t); }
function B3(t) { return 3*t*(1-t)*(1-t); }
function B4(t) { return (1-t)*(1-t)*(1-t); }
ionic.Animator = {
// Quadratic bezier solver
getQuadraticBezier: function(percent,C1,C2,C3,C4) {
var pos = new bezierCoord();
pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent);
pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent);
return pos;
},
// Cubic bezier solver from https://github.com/arian/cubic-bezier (MIT)
getCubicBezier: function(x1, y1, x2, y2, duration) {
// Precision
epsilon = (1000 / 60 / duration) / 4;
var curveX = function(t){
var v = 1 - t;
return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t;
};
var curveY = function(t){
var v = 1 - t;
return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t;
};
var derivativeCurveX = function(t){
var v = 1 - t;
return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2;
};
return function(t) {
var x = t, t0, t1, t2, x2, d2, i;
// First try a few iterations of Newton's method -- normally very fast.
for (t2 = x, i = 0; i < 8; i++){
x2 = curveX(t2) - x;
if (Math.abs(x2) < epsilon) return curveY(t2);
d2 = derivativeCurveX(t2);
if (Math.abs(d2) < 1e-6) break;
t2 = t2 - x2 / d2;
}
t0 = 0, t1 = 1, t2 = x;
if (t2 < t0) return curveY(t0);
if (t2 > t1) return curveY(t1);
// Fallback to the bisection method for reliability.
while (t0 < t1){
x2 = curveX(t2);
if (Math.abs(x2 - x) < epsilon) return curveY(t2);
if (x > x2) t0 = t2;
else t1 = t2;
t2 = (t1 - t0) * 0.5 + t0;
}
// Failure
return curveY(t2);
};
},
animate: function(element, className, fn) {
return {
leave: function() {
var endFunc = function() {
element.classList.remove('leave');
element.classList.remove('leave-active');
element.removeEventListener('webkitTransitionEnd', endFunc);
element.removeEventListener('transitionEnd', endFunc);
};
element.addEventListener('webkitTransitionEnd', endFunc);
element.addEventListener('transitionEnd', endFunc);
element.classList.add('leave');
element.classList.add('leave-active');
return this;
},
enter: function() {
var endFunc = function() {
element.classList.remove('enter');
element.classList.remove('enter-active');
element.removeEventListener('webkitTransitionEnd', endFunc);
element.removeEventListener('transitionEnd', endFunc);
};
element.addEventListener('webkitTransitionEnd', endFunc);
element.addEventListener('transitionEnd', endFunc);
element.classList.add('enter');
element.classList.add('enter-active');
return this;
}
};
}
};
})(ionic);
;
(function(ionic) {
ionic.DomUtil = {
getTextBounds: function(textNode) {
if(document.createRange) {
var range = document.createRange();
range.selectNodeContents(textNode);
if(range.getBoundingClientRect) {
var rect = range.getBoundingClientRect();
var sx = window.scrollX;
var sy = window.scrollY;
return {
top: rect.top + sy,
left: rect.left + sx,
right: rect.left + sx + rect.width,
bottom: rect.top + sy + rect.height,
width: rect.width,
height: rect.height
};
}
}
return null;
},
getChildIndex: function(element, type) {
if(type) {
var ch = element.parentNode.children;
var c;
for(var i = 0, k = 0, j = ch.length; i < j; i++) {
c = ch[i];
if(c.nodeName && c.nodeName.toLowerCase() == type) {
if(c == element) {
return k;
}
k++;
}
}
}
return Array.prototype.slice.call(element.parentNode.children).indexOf(element);
},
swapNodes: function(src, dest) {
dest.parentNode.insertBefore(src, dest);
},
/**
* {returns} the closest parent matching the className
*/
getParentWithClass: function(e, className) {
while(e.parentNode) {
if(e.parentNode.classList && e.parentNode.classList.contains(className)) {
return e.parentNode;
}
e = e.parentNode;
}
return null;
},
/**
* {returns} the closest parent or self matching the className
*/
getParentOrSelfWithClass: function(e, className) {
while(e) {
if(e.classList && e.classList.contains(className)) {
return e;
}
e = e.parentNode;
}
return null;
}
};
})(window.ionic);
;
/**
* ion-events.js
*
* Author: Max Lynch <[email protected]>
*
* Framework events handles various mobile browser events, and
* detects special events like tap/swipe/etc. and emits them
* as custom events that can be used in an app.
*
* Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys!
*/
(function(ionic) {
// Custom event polyfill
if(!window.CustomEvent) {
(function() {
var CustomEvent;
CustomEvent = function(event, params) {
var evt;
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
}
ionic.EventController = {
VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'],
// Trigger a new event
trigger: function(eventType, data) {
var event = new CustomEvent(eventType, { detail: data });
// Make sure to trigger the event on the given target, or dispatch it from
// the window if we don't have an event target
data && data.target && data.target.dispatchEvent(event) || window.dispatchEvent(event);
},
// Bind an event
on: function(type, callback, element) {
var e = element || window;
// Bind a gesture if it's a virtual event
for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) {
if(type == this.VIRTUALIZED_EVENTS[i]) {
var gesture = new ionic.Gesture(element);
gesture.on(type, callback);
return gesture;
}
}
// Otherwise bind a normal event
e.addEventListener(type, callback);
},
off: function(type, callback, element) {
element.removeEventListener(type, callback);
},
// Register for a new gesture event on the given element
onGesture: function(type, callback, element) {
var gesture = new ionic.Gesture(element);
gesture.on(type, callback);
return gesture;
},
// Unregister a previous gesture event
offGesture: function(gesture, type, callback) {
gesture.off(type, callback);
},
handlePopState: function(event) {
},
};
// Map some convenient top-level functions for event handling
ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); };
ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); };
ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); };
ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); };
ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); };
})(window.ionic);
;
/**
* Simple gesture controllers with some common gestures that emit
* gesture events.
*
* Ported from github.com/EightMedia/ionic.Gestures.js - thanks!
*/
(function(ionic) {
/**
* ionic.Gestures
* use this to create instances
* @param {HTMLElement} element
* @param {Object} options
* @returns {ionic.Gestures.Instance}
* @constructor
*/
ionic.Gesture = function(element, options) {
return new ionic.Gestures.Instance(element, options || {});
};
ionic.Gestures = {};
// default settings
ionic.Gestures.defaults = {
// add styles and attributes to the element to prevent the browser from doing
// its native behavior. this doesnt prevent the scrolling, but cancels
// the contextmenu, tap highlighting etc
// set to false to disable this
stop_browser_behavior: {
// this also triggers onselectstart=false for IE
userSelect: 'none',
// this makes the element blocking in IE10 >, you could experiment with the value
// see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241
touchAction: 'none',
touchCallout: 'none',
contentZooming: 'none',
userDrag: 'none',
tapHighlightColor: 'rgba(0,0,0,0)'
}
// more settings are defined per gesture at gestures.js
};
// detect touchevents
ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled;
ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window);
// dont use mouseevents on mobile devices
ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i;
ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX);
// eventtypes per touchevent (start, move, end)
// are filled by ionic.Gestures.event.determineEventTypes on setup
ionic.Gestures.EVENT_TYPES = {};
// direction defines
ionic.Gestures.DIRECTION_DOWN = 'down';
ionic.Gestures.DIRECTION_LEFT = 'left';
ionic.Gestures.DIRECTION_UP = 'up';
ionic.Gestures.DIRECTION_RIGHT = 'right';
// pointer type
ionic.Gestures.POINTER_MOUSE = 'mouse';
ionic.Gestures.POINTER_TOUCH = 'touch';
ionic.Gestures.POINTER_PEN = 'pen';
// touch event defines
ionic.Gestures.EVENT_START = 'start';
ionic.Gestures.EVENT_MOVE = 'move';
ionic.Gestures.EVENT_END = 'end';
// hammer document where the base events are added at
ionic.Gestures.DOCUMENT = window.document;
// plugins namespace
ionic.Gestures.plugins = {};
// if the window events are set...
ionic.Gestures.READY = false;
/**
* setup events to detect gestures on the document
*/
function setup() {
if(ionic.Gestures.READY) {
return;
}
// find what eventtypes we add listeners to
ionic.Gestures.event.determineEventTypes();
// Register all gestures inside ionic.Gestures.gestures
for(var name in ionic.Gestures.gestures) {
if(ionic.Gestures.gestures.hasOwnProperty(name)) {
ionic.Gestures.detection.register(ionic.Gestures.gestures[name]);
}
}
// Add touch events on the document
ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect);
ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect);
// ionic.Gestures is ready...!
ionic.Gestures.READY = true;
}
/**
* create new hammer instance
* all methods should return the instance itself, so it is chainable.
* @param {HTMLElement} element
* @param {Object} [options={}]
* @returns {ionic.Gestures.Instance}
* @constructor
*/
ionic.Gestures.Instance = function(element, options) {
var self = this;
// A null element was passed into the instance, which means
// whatever lookup was done to find this element failed to find it
// so we can't listen for events on it.
if(element === null) {
console.error('Null element passed to gesture (element does not exist). Not listening for gesture');
return;
}
// setup ionic.GesturesJS window events and register all gestures
// this also sets up the default options
setup();
this.element = element;
// start/stop detection option
this.enabled = true;
// merge options
this.options = ionic.Gestures.utils.extend(
ionic.Gestures.utils.extend({}, ionic.Gestures.defaults),
options || {});
// add some css to the element to prevent the browser from doing its native behavoir
if(this.options.stop_browser_behavior) {
ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
}
// start detection on touchstart
ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) {
if(self.enabled) {
ionic.Gestures.detection.startDetect(self, ev);
}
});
// return instance
return this;
};
ionic.Gestures.Instance.prototype = {
/**
* bind events to the instance
* @param {String} gesture
* @param {Function} handler
* @returns {ionic.Gestures.Instance}
*/
on: function onEvent(gesture, handler){
var gestures = gesture.split(' ');
for(var t=0; t<gestures.length; t++) {
this.element.addEventListener(gestures[t], handler, false);
}
return this;
},
/**
* unbind events to the instance
* @param {String} gesture
* @param {Function} handler
* @returns {ionic.Gestures.Instance}
*/
off: function offEvent(gesture, handler){
var gestures = gesture.split(' ');
for(var t=0; t<gestures.length; t++) {
this.element.removeEventListener(gestures[t], handler, false);
}
return this;
},
/**
* trigger gesture event
* @param {String} gesture
* @param {Object} eventData
* @returns {ionic.Gestures.Instance}
*/
trigger: function triggerEvent(gesture, eventData){
// create DOM event
var event = ionic.Gestures.DOCUMENT.createEvent('Event');
event.initEvent(gesture, true, true);
event.gesture = eventData;
// trigger on the target if it is in the instance element,
// this is for event delegation tricks
var element = this.element;
if(ionic.Gestures.utils.hasParent(eventData.target, element)) {
element = eventData.target;
}
element.dispatchEvent(event);
return this;
},
/**
* enable of disable hammer.js detection
* @param {Boolean} state
* @returns {ionic.Gestures.Instance}
*/
enable: function enable(state) {
this.enabled = state;
return this;
}
};
/**
* this holds the last move event,
* used to fix empty touchend issue
* see the onTouch event for an explanation
* @type {Object}
*/
var last_move_event = null;
/**
* when the mouse is hold down, this is true
* @type {Boolean}
*/
var enable_detect = false;
/**
* when touch events have been fired, this is true
* @type {Boolean}
*/
var touch_triggered = false;
ionic.Gestures.event = {
/**
* simple addEventListener
* @param {HTMLElement} element
* @param {String} type
* @param {Function} handler
*/
bindDom: function(element, type, handler) {
var types = type.split(' ');
for(var t=0; t<types.length; t++) {
element.addEventListener(types[t], handler, false);
}
},
/**
* touch events with mouse fallback
* @param {HTMLElement} element
* @param {String} eventType like ionic.Gestures.EVENT_MOVE
* @param {Function} handler
*/
onTouch: function onTouch(element, eventType, handler) {
var self = this;
this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
var sourceEventType = ev.type.toLowerCase();
// onmouseup, but when touchend has been fired we do nothing.
// this is for touchdevices which also fire a mouseup on touchend
if(sourceEventType.match(/mouse/) && touch_triggered) {
return;
}
// mousebutton must be down or a touch event
else if( sourceEventType.match(/touch/) || // touch events are always on screen
sourceEventType.match(/pointerdown/) || // pointerevents touch
(sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
){
enable_detect = true;
}
// mouse isn't pressed
else if(sourceEventType.match(/mouse/) && ev.which !== 1) {
enable_detect = false;
}
// we are in a touch event, set the touch triggered bool to true,
// this for the conflicts that may occur on ios and android
if(sourceEventType.match(/touch|pointer/)) {
touch_triggered = true;
}
// count the total touches on the screen
var count_touches = 0;
// when touch has been triggered in this detection session
// and we are now handling a mouse event, we stop that to prevent conflicts
if(enable_detect) {
// update pointerevent
if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) {
count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);
}
// touch
else if(sourceEventType.match(/touch/)) {
count_touches = ev.touches.length;
}
// mouse
else if(!touch_triggered) {
count_touches = sourceEventType.match(/up/) ? 0 : 1;
}
// if we are in a end event, but when we remove one touch and
// we still have enough, set eventType to move
if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) {
eventType = ionic.Gestures.EVENT_MOVE;
}
// no touches, force the end event
else if(!count_touches) {
eventType = ionic.Gestures.EVENT_END;
}
// store the last move event
if(count_touches || last_move_event === null) {
last_move_event = ev;
}
// trigger the handler
handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev));
// remove pointerevent from list
if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) {
count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);
}
}
//debug(sourceEventType +" "+ eventType);
// on the end we reset everything
if(!count_touches) {
last_move_event = null;
enable_detect = false;
touch_triggered = false;
ionic.Gestures.PointerEvent.reset();
}
});
},
/**
* we have different events for each device/browser
* determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant
*/
determineEventTypes: function determineEventTypes() {
// determine the eventtype we want to set
var types;
// pointerEvents magic
if(ionic.Gestures.HAS_POINTEREVENTS) {
types = ionic.Gestures.PointerEvent.getEvents();
}
// on Android, iOS, blackberry, windows mobile we dont want any mouseevents
else if(ionic.Gestures.NO_MOUSEEVENTS) {
types = [
'touchstart',
'touchmove',
'touchend touchcancel'];
}
// for non pointer events browsers and mixed browsers,
// like chrome on windows8 touch laptop
else {
types = [
'touchstart mousedown',
'touchmove mousemove',
'touchend touchcancel mouseup'];
}
ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0];
ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1];
ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2];
},
/**
* create touchlist depending on the event
* @param {Object} ev
* @param {String} eventType used by the fakemultitouch plugin
*/
getTouchList: function getTouchList(ev/*, eventType*/) {
// get the fake pointerEvent touchlist
if(ionic.Gestures.HAS_POINTEREVENTS) {
return ionic.Gestures.PointerEvent.getTouchList();
}
// get the touchlist
else if(ev.touches) {
return ev.touches;
}
// make fake touchlist from mouse position
else {
ev.indentifier = 1;
return [ev];
}
},
/**
* collect event data for ionic.Gestures js
* @param {HTMLElement} element
* @param {String} eventType like ionic.Gestures.EVENT_MOVE
* @param {Object} eventData
*/
collectEventData: function collectEventData(element, eventType, touches, ev) {
// find out pointerType
var pointerType = ionic.Gestures.POINTER_TOUCH;
if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {
pointerType = ionic.Gestures.POINTER_MOUSE;
}
return {
center : ionic.Gestures.utils.getCenter(touches),
timeStamp : new Date().getTime(),
target : ev.target,
touches : touches,
eventType : eventType,
pointerType : pointerType,
srcEvent : ev,
/**
* prevent the browser default actions
* mostly used to disable scrolling of the browser
*/
preventDefault: function() {
if(this.srcEvent.preventManipulation) {
this.srcEvent.preventManipulation();
}
if(this.srcEvent.preventDefault) {
//this.srcEvent.preventDefault();
}
},
/**
* stop bubbling the event up to its parents
*/
stopPropagation: function() {
this.srcEvent.stopPropagation();
},
/**
* immediately stop gesture detection
* might be useful after a swipe was detected
* @return {*}
*/
stopDetect: function() {
return ionic.Gestures.detection.stopDetect();
}
};
}
};
ionic.Gestures.PointerEvent = {
/**
* holds all pointers
* @type {Object}
*/
pointers: {},
/**
* get a list of pointers
* @returns {Array} touchlist
*/
getTouchList: function() {
var self = this;
var touchlist = [];
// we can use forEach since pointerEvents only is in IE10
Object.keys(self.pointers).sort().forEach(function(id) {
touchlist.push(self.pointers[id]);
});
return touchlist;
},
/**
* update the position of a pointer
* @param {String} type ionic.Gestures.EVENT_END
* @param {Object} pointerEvent
*/
updatePointer: function(type, pointerEvent) {
if(type == ionic.Gestures.EVENT_END) {
this.pointers = {};
}
else {
pointerEvent.identifier = pointerEvent.pointerId;
this.pointers[pointerEvent.pointerId] = pointerEvent;
}
return Object.keys(this.pointers).length;
},
/**
* check if ev matches pointertype
* @param {String} pointerType ionic.Gestures.POINTER_MOUSE
* @param {PointerEvent} ev
*/
matchType: function(pointerType, ev) {
if(!ev.pointerType) {
return false;
}
var types = {};
types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE);
types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH);
types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN);
return types[pointerType];
},
/**
* get events
*/
getEvents: function() {
return [
'pointerdown MSPointerDown',
'pointermove MSPointerMove',
'pointerup pointercancel MSPointerUp MSPointerCancel'
];
},
/**
* reset the list
*/
reset: function() {
this.pointers = {};
}
};
ionic.Gestures.utils = {
/**
* extend method,
* also used for cloning when dest is an empty object
* @param {Object} dest
* @param {Object} src
* @parm {Boolean} merge do a merge
* @returns {Object} dest
*/
extend: function extend(dest, src, merge) {
for (var key in src) {
if(dest[key] !== undefined && merge) {
continue;
}
dest[key] = src[key];
}
return dest;
},
/**
* find if a node is in the given parent
* used for event delegation tricks
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @returns {boolean} has_parent
*/
hasParent: function(node, parent) {
while(node){
if(node == parent) {
return true;
}
node = node.parentNode;
}
return false;
},
/**
* get the center of all the touches
* @param {Array} touches
* @returns {Object} center
*/
getCenter: function getCenter(touches) {
var valuesX = [], valuesY = [];
for(var t= 0,len=touches.length; t<len; t++) {
valuesX.push(touches[t].pageX);
valuesY.push(touches[t].pageY);
}
return {
pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
};
},
/**
* calculate the velocity between two points
* @param {Number} delta_time
* @param {Number} delta_x
* @param {Number} delta_y
* @returns {Object} velocity
*/
getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
return {
x: Math.abs(delta_x / delta_time) || 0,
y: Math.abs(delta_y / delta_time) || 0
};
},
/**
* calculate the angle between two coordinates
* @param {Touch} touch1
* @param {Touch} touch2
* @returns {Number} angle
*/
getAngle: function getAngle(touch1, touch2) {
var y = touch2.pageY - touch1.pageY,
x = touch2.pageX - touch1.pageX;
return Math.atan2(y, x) * 180 / Math.PI;
},
/**
* angle to direction define
* @param {Touch} touch1
* @param {Touch} touch2
* @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT
*/
getDirection: function getDirection(touch1, touch2) {
var x = Math.abs(touch1.pageX - touch2.pageX),
y = Math.abs(touch1.pageY - touch2.pageY);
if(x >= y) {
return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;
}
else {
return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;
}
},
/**
* calculate the distance between two touches
* @param {Touch} touch1
* @param {Touch} touch2
* @returns {Number} distance
*/
getDistance: function getDistance(touch1, touch2) {
var x = touch2.pageX - touch1.pageX,
y = touch2.pageY - touch1.pageY;
return Math.sqrt((x*x) + (y*y));
},
/**
* calculate the scale factor between two touchLists (fingers)
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start
* @param {Array} end
* @returns {Number} scale
*/
getScale: function getScale(start, end) {
// need two fingers...
if(start.length >= 2 && end.length >= 2) {
return this.getDistance(end[0], end[1]) /
this.getDistance(start[0], start[1]);
}
return 1;
},
/**
* calculate the rotation degrees between two touchLists (fingers)
* @param {Array} start
* @param {Array} end
* @returns {Number} rotation
*/
getRotation: function getRotation(start, end) {
// need two fingers
if(start.length >= 2 && end.length >= 2) {
return this.getAngle(end[1], end[0]) -
this.getAngle(start[1], start[0]);
}
return 0;
},
/**
* boolean if the direction is vertical
* @param {String} direction
* @returns {Boolean} is_vertical
*/
isVertical: function isVertical(direction) {
return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN);
},
/**
* stop browser default behavior with css props
* @param {HtmlElement} element
* @param {Object} css_props
*/
stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) {
var prop,
vendors = ['webkit','khtml','moz','Moz','ms','o',''];
if(!css_props || !element.style) {
return;
}
// with css properties for modern browsers
for(var i = 0; i < vendors.length; i++) {
for(var p in css_props) {
if(css_props.hasOwnProperty(p)) {
prop = p;
// vender prefix at the property
if(vendors[i]) {
prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
// set the style
element.style[prop] = css_props[p];
}
}
}
// also the disable onselectstart
if(css_props.userSelect == 'none') {
element.onselectstart = function() {
return false;
};
}
}
};
ionic.Gestures.detection = {
// contains all registred ionic.Gestures.gestures in the correct order
gestures: [],
// data of the current ionic.Gestures.gesture detection session
current: null,
// the previous ionic.Gestures.gesture session data
// is a full clone of the previous gesture.current object
previous: null,
// when this becomes true, no gestures are fired
stopped: false,
/**
* start ionic.Gestures.gesture detection
* @param {ionic.Gestures.Instance} inst
* @param {Object} eventData
*/
startDetect: function startDetect(inst, eventData) {
// already busy with a ionic.Gestures.gesture detection on an element
if(this.current) {
return;
}
this.stopped = false;
this.current = {
inst : inst, // reference to ionic.GesturesInstance we're working for
startEvent : ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc
lastEvent : false, // last eventData
name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc
};
this.detect(eventData);
},
/**
* ionic.Gestures.gesture detection
* @param {Object} eventData
*/
detect: function detect(eventData) {
if(!this.current || this.stopped) {
return;
}
// extend event data with calculations about scale, distance etc
eventData = this.extendEventData(eventData);
// instance options
var inst_options = this.current.inst.options;
// call ionic.Gestures.gesture handlers
for(var g=0,len=this.gestures.length; g<len; g++) {
var gesture = this.gestures[g];
// only when the instance options have enabled this gesture
if(!this.stopped && inst_options[gesture.name] !== false) {
// if a handler returns false, we stop with the detection
if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
this.stopDetect();
break;
}
}
}
// store as previous event event
if(this.current) {
this.current.lastEvent = eventData;
}
// endevent, but not the last touch, so dont stop
if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) {
this.stopDetect();
}
return eventData;
},
/**
* clear the ionic.Gestures.gesture vars
* this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected
* to stop other ionic.Gestures.gestures from being fired
*/
stopDetect: function stopDetect() {
// clone current data to the store as the previous gesture
// used for the double tap gesture, since this is an other gesture detect session
this.previous = ionic.Gestures.utils.extend({}, this.current);
// reset the current
this.current = null;
// stopped!
this.stopped = true;
},
/**
* extend eventData for ionic.Gestures.gestures
* @param {Object} ev
* @returns {Object} ev
*/
extendEventData: function extendEventData(ev) {
var startEv = this.current.startEvent;
// if the touches change, set the new touches over the startEvent touches
// this because touchevents don't have all the touches on touchstart, or the
// user must place his fingers at the EXACT same time on the screen, which is not realistic
// but, sometimes it happens that both fingers are touching at the EXACT same time
if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
// extend 1 level deep to get the touchlist with the touch objects
startEv.touches = [];
for(var i=0,len=ev.touches.length; i<len; i++) {
startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i]));
}
}
var delta_time = ev.timeStamp - startEv.timeStamp,
delta_x = ev.center.pageX - startEv.center.pageX,
delta_y = ev.center.pageY - startEv.center.pageY,
velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y);
ionic.Gestures.utils.extend(ev, {
deltaTime : delta_time,
deltaX : delta_x,
deltaY : delta_y,
velocityX : velocity.x,
velocityY : velocity.y,
distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center),
angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center),
direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center),
scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches),
rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches),
startEvent : startEv
});
return ev;
},
/**
* register new gesture
* @param {Object} gesture object, see gestures.js for documentation
* @returns {Array} gestures
*/
register: function register(gesture) {
// add an enable gesture options if there is no given
var options = gesture.defaults || {};
if(options[gesture.name] === undefined) {
options[gesture.name] = true;
}
// extend ionic.Gestures default options with the ionic.Gestures.gesture options
ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true);
// set its index
gesture.index = gesture.index || 1000;
// add ionic.Gestures.gesture to the list
this.gestures.push(gesture);
// sort the list by index
this.gestures.sort(function(a, b) {
if (a.index < b.index) {
return -1;
}
if (a.index > b.index) {
return 1;
}
return 0;
});
return this.gestures;
}
};
ionic.Gestures.gestures = ionic.Gestures.gestures || {};
/**
* Custom gestures
* ==============================
*
* Gesture object
* --------------------
* The object structure of a gesture:
*
* { name: 'mygesture',
* index: 1337,
* defaults: {
* mygesture_option: true
* }
* handler: function(type, ev, inst) {
* // trigger gesture event
* inst.trigger(this.name, ev);
* }
* }
* @param {String} name
* this should be the name of the gesture, lowercase
* it is also being used to disable/enable the gesture per instance config.
*
* @param {Number} [index=1000]
* the index of the gesture, where it is going to be in the stack of gestures detection
* like when you build an gesture that depends on the drag gesture, it is a good
* idea to place it after the index of the drag gesture.
*
* @param {Object} [defaults={}]
* the default settings of the gesture. these are added to the instance settings,
* and can be overruled per instance. you can also add the name of the gesture,
* but this is also added by default (and set to true).
*
* @param {Function} handler
* this handles the gesture detection of your custom gesture and receives the
* following arguments:
*
* @param {Object} eventData
* event data containing the following properties:
* timeStamp {Number} time the event occurred
* target {HTMLElement} target element
* touches {Array} touches (fingers, pointers, mouse) on the screen
* pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH
* center {Object} center position of the touches. contains pageX and pageY
* deltaTime {Number} the total time of the touches in the screen
* deltaX {Number} the delta on x axis we haved moved
* deltaY {Number} the delta on y axis we haved moved
* velocityX {Number} the velocity on the x
* velocityY {Number} the velocity on y
* angle {Number} the angle we are moving
* direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT
* distance {Number} the distance we haved moved
* scale {Number} scaling of the touches, needs 2 touches
* rotation {Number} rotation of the touches, needs 2 touches *
* eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END
* srcEvent {Object} the source event, like TouchStart or MouseDown *
* startEvent {Object} contains the same properties as above,
* but from the first touch. this is used to calculate
* distances, deltaTime, scaling etc
*
* @param {ionic.Gestures.Instance} inst
* the instance we are doing the detection for. you can get the options from
* the inst.options object and trigger the gesture event by calling inst.trigger
*
*
* Handle gestures
* --------------------
* inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current
* detection sessionic. It has the following properties
* @param {String} name
* contains the name of the gesture we have detected. it has not a real function,
* only to check in other gestures if something is detected.
* like in the drag gesture we set it to 'drag' and in the swipe gesture we can
* check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name
*
* @readonly
* @param {ionic.Gestures.Instance} inst
* the instance we do the detection for
*
* @readonly
* @param {Object} startEvent
* contains the properties of the first gesture detection in this sessionic.
* Used for calculations about timing, distance, etc.
*
* @readonly
* @param {Object} lastEvent
* contains all the properties of the last gesture detect in this sessionic.
*
* after the gesture detection session has been completed (user has released the screen)
* the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous,
* this is usefull for gestures like doubletap, where you need to know if the
* previous gesture was a tap
*
* options that have been set by the instance can be received by calling inst.options
*
* You can trigger a gesture event by calling inst.trigger("mygesture", event).
* The first param is the name of your gesture, the second the event argument
*
*
* Register gestures
* --------------------
* When an gesture is added to the ionic.Gestures.gestures object, it is auto registered
* at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register
* manually and pass your gesture object as a param
*
*/
/**
* Hold
* Touch stays at the same place for x time
* @events hold
*/
ionic.Gestures.gestures.Hold = {
name: 'hold',
index: 10,
defaults: {
hold_timeout : 500,
hold_threshold : 1
},
timer: null,
handler: function holdGesture(ev, inst) {
switch(ev.eventType) {
case ionic.Gestures.EVENT_START:
// clear any running timers
clearTimeout(this.timer);
// set the gesture so we can check in the timeout if it still is
ionic.Gestures.detection.current.name = this.name;
// set timer and if after the timeout it still is hold,
// we trigger the hold event
this.timer = setTimeout(function() {
if(ionic.Gestures.detection.current.name == 'hold') {
inst.trigger('hold', ev);
}
}, inst.options.hold_timeout);
break;
// when you move or end we clear the timer
case ionic.Gestures.EVENT_MOVE:
if(ev.distance > inst.options.hold_threshold) {
clearTimeout(this.timer);
}
break;
case ionic.Gestures.EVENT_END:
clearTimeout(this.timer);
break;
}
}
};
/**
* Tap/DoubleTap
* Quick touch at a place or double at the same place
* @events tap, doubletap
*/
ionic.Gestures.gestures.Tap = {
name: 'tap',
index: 100,
defaults: {
tap_max_touchtime : 250,
tap_max_distance : 10,
tap_always : true,
doubletap_distance : 20,
doubletap_interval : 300
},
handler: function tapGesture(ev, inst) {
if(ev.eventType == ionic.Gestures.EVENT_END) {
// previous gesture, for the double tap since these are two different gesture detections
var prev = ionic.Gestures.detection.previous,
did_doubletap = false;
// when the touchtime is higher then the max touch time
// or when the moving distance is too much
if(ev.deltaTime > inst.options.tap_max_touchtime ||
ev.distance > inst.options.tap_max_distance) {
return;
}
// check if double tap
if(prev && prev.name == 'tap' &&
(ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
ev.distance < inst.options.doubletap_distance) {
inst.trigger('doubletap', ev);
did_doubletap = true;
}
// do a single tap
if(!did_doubletap || inst.options.tap_always) {
ionic.Gestures.detection.current.name = 'tap';
inst.trigger(ionic.Gestures.detection.current.name, ev);
}
}
}
};
/**
* Swipe
* triggers swipe events when the end velocity is above the threshold
* @events swipe, swipeleft, swiperight, swipeup, swipedown
*/
ionic.Gestures.gestures.Swipe = {
name: 'swipe',
index: 40,
defaults: {
// set 0 for unlimited, but this can conflict with transform
swipe_max_touches : 1,
swipe_velocity : 0.7
},
handler: function swipeGesture(ev, inst) {
if(ev.eventType == ionic.Gestures.EVENT_END) {
// max touches
if(inst.options.swipe_max_touches > 0 &&
ev.touches.length > inst.options.swipe_max_touches) {
return;
}
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if(ev.velocityX > inst.options.swipe_velocity ||
ev.velocityY > inst.options.swipe_velocity) {
// trigger swipe events
inst.trigger(this.name, ev);
inst.trigger(this.name + ev.direction, ev);
}
}
}
};
/**
* Drag
* Move with x fingers (default 1) around on the page. Blocking the scrolling when
* moving left and right is a good practice. When all the drag events are blocking
* you disable scrolling on that area.
* @events drag, drapleft, dragright, dragup, dragdown
*/
ionic.Gestures.gestures.Drag = {
name: 'drag',
index: 50,
defaults: {
drag_min_distance : 10,
// Set correct_for_drag_min_distance to true to make the starting point of the drag
// be calculated from where the drag was triggered, not from where the touch started.
// Useful to avoid a jerk-starting drag, which can make fine-adjustments
// through dragging difficult, and be visually unappealing.
correct_for_drag_min_distance : true,
// set 0 for unlimited, but this can conflict with transform
drag_max_touches : 1,
// prevent default browser behavior when dragging occurs
// be careful with it, it makes the element a blocking element
// when you are using the drag gesture, it is a good practice to set this true
drag_block_horizontal : true,
drag_block_vertical : true,
// drag_lock_to_axis keeps the drag gesture on the axis that it started on,
// It disallows vertical directions if the initial direction was horizontal, and vice versa.
drag_lock_to_axis : false,
// drag lock only kicks in when distance > drag_lock_min_distance
// This way, locking occurs only when the distance has become large enough to reliably determine the direction
drag_lock_min_distance : 25
},
triggered: false,
handler: function dragGesture(ev, inst) {
// current gesture isnt drag, but dragged is true
// this means an other gesture is busy. now call dragend
if(ionic.Gestures.detection.current.name != this.name && this.triggered) {
inst.trigger(this.name +'end', ev);
this.triggered = false;
return;
}
// max touches
if(inst.options.drag_max_touches > 0 &&
ev.touches.length > inst.options.drag_max_touches) {
return;
}
switch(ev.eventType) {
case ionic.Gestures.EVENT_START:
this.triggered = false;
break;
case ionic.Gestures.EVENT_MOVE:
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if(ev.distance < inst.options.drag_min_distance &&
ionic.Gestures.detection.current.name != this.name) {
return;
}
// we are dragging!
if(ionic.Gestures.detection.current.name != this.name) {
ionic.Gestures.detection.current.name = this.name;
if (inst.options.correct_for_drag_min_distance) {
// When a drag is triggered, set the event center to drag_min_distance pixels from the original event center.
// Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0.
// It might be useful to save the original start point somewhere
var factor = Math.abs(inst.options.drag_min_distance/ev.distance);
ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor;
ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor;
// recalculate event data using new start point
ev = ionic.Gestures.detection.extendEventData(ev);
}
}
// lock drag to axis?
if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) {
ev.drag_locked_to_axis = true;
}
var last_direction = ionic.Gestures.detection.current.lastEvent.direction;
if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
// keep direction on the axis that the drag gesture started on
if(ionic.Gestures.utils.isVertical(last_direction)) {
ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;
}
else {
ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;
}
}
// first time, trigger dragstart event
if(!this.triggered) {
inst.trigger(this.name +'start', ev);
this.triggered = true;
}
// trigger normal event
inst.trigger(this.name, ev);
// direction event, like dragdown
inst.trigger(this.name + ev.direction, ev);
// block the browser events
if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) ||
(inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) {
ev.preventDefault();
}
break;
case ionic.Gestures.EVENT_END:
// trigger dragend
if(this.triggered) {
inst.trigger(this.name +'end', ev);
}
this.triggered = false;
break;
}
}
};
/**
* Transform
* User want to scale or rotate with 2 fingers
* @events transform, pinch, pinchin, pinchout, rotate
*/
ionic.Gestures.gestures.Transform = {
name: 'transform',
index: 45,
defaults: {
// factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
transform_min_scale : 0.01,
// rotation in degrees
transform_min_rotation : 1,
// prevent default browser behavior when two touches are on the screen
// but it makes the element a blocking element
// when you are using the transform gesture, it is a good practice to set this true
transform_always_block : false
},
triggered: false,
handler: function transformGesture(ev, inst) {
// current gesture isnt drag, but dragged is true
// this means an other gesture is busy. now call dragend
if(ionic.Gestures.detection.current.name != this.name && this.triggered) {
inst.trigger(this.name +'end', ev);
this.triggered = false;
return;
}
// atleast multitouch
if(ev.touches.length < 2) {
return;
}
// prevent default when two fingers are on the screen
if(inst.options.transform_always_block) {
ev.preventDefault();
}
switch(ev.eventType) {
case ionic.Gestures.EVENT_START:
this.triggered = false;
break;
case ionic.Gestures.EVENT_MOVE:
var scale_threshold = Math.abs(1-ev.scale);
var rotation_threshold = Math.abs(ev.rotation);
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if(scale_threshold < inst.options.transform_min_scale &&
rotation_threshold < inst.options.transform_min_rotation) {
return;
}
// we are transforming!
ionic.Gestures.detection.current.name = this.name;
// first time, trigger dragstart event
if(!this.triggered) {
inst.trigger(this.name +'start', ev);
this.triggered = true;
}
inst.trigger(this.name, ev); // basic transform event
// trigger rotate event
if(rotation_threshold > inst.options.transform_min_rotation) {
inst.trigger('rotate', ev);
}
// trigger pinch event
if(scale_threshold > inst.options.transform_min_scale) {
inst.trigger('pinch', ev);
inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev);
}
break;
case ionic.Gestures.EVENT_END:
// trigger dragend
if(this.triggered) {
inst.trigger(this.name +'end', ev);
}
this.triggered = false;
break;
}
}
};
/**
* Touch
* Called as first, tells the user has touched the screen
* @events touch
*/
ionic.Gestures.gestures.Touch = {
name: 'touch',
index: -Infinity,
defaults: {
// call preventDefault at touchstart, and makes the element blocking by
// disabling the scrolling of the page, but it improves gestures like
// transforming and dragging.
// be careful with using this, it can be very annoying for users to be stuck
// on the page
prevent_default: false,
// disable mouse events, so only touch (or pen!) input triggers events
prevent_mouseevents: false
},
handler: function touchGesture(ev, inst) {
if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) {
ev.stopDetect();
return;
}
if(inst.options.prevent_default) {
ev.preventDefault();
}
if(ev.eventType == ionic.Gestures.EVENT_START) {
inst.trigger(this.name, ev);
}
}
};
/**
* Release
* Called as last, tells the user has released the screen
* @events release
*/
ionic.Gestures.gestures.Release = {
name: 'release',
index: Infinity,
handler: function releaseGesture(ev, inst) {
if(ev.eventType == ionic.Gestures.EVENT_END) {
inst.trigger(this.name, ev);
}
}
};
})(window.ionic);
;
(function(ionic) {
ionic.Platform = {
detect: function() {
var platforms = [];
this._checkPlatforms(platforms);
var classify = function() {
if(!document.body) { return; }
for(var i = 0; i < platforms.length; i++) {
document.body.classList.add('platform-' + platforms[i]);
}
};
document.addEventListener( "DOMContentLoaded", function(){
classify();
});
classify();
},
_checkPlatforms: function(platforms) {
if(this.isCordova()) {
platforms.push('cordova');
}
if(this.isIOS7()) {
platforms.push('ios7');
}
if(this.isIPad()) {
platforms.push('ipad');
}
if(this.isAndroid()) {
platforms.push('android');
}
},
// Check if we are running in Cordova, which will have
// window.device available.
isCordova: function() {
return (window.cordova || window.PhoneGap || window.phonegap);
//&& /^file:\/{3}[^\/]/i.test(window.location.href)
//&& /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
},
isIPad: function() {
return navigator.userAgent.toLowerCase().indexOf('ipad') >= 0;
},
isIOS7: function() {
if(!window.device) {
return false;
}
return parseFloat(window.device.version) >= 7.0;
},
isAndroid: function() {
if(!window.device) {
return navigator.userAgent.toLowerCase().indexOf('android') >= 0;
}
return device.platform === "Android";
}
};
ionic.Platform.detect();
})(window.ionic);
;
(function(window, document, ionic) {
'use strict';
// From the man himself, Mr. Paul Irish.
// The requestAnimationFrame polyfill
window.rAF = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// Ionic CSS polyfills
ionic.CSS = {};
(function() {
var d = document.createElement('div');
var keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform',
'-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform'];
for(var i = 0; i < keys.length; i++) {
if(d.style[keys[i]] !== undefined) {
ionic.CSS.TRANSFORM = keys[i];
break;
}
}
})();
// polyfill use to simulate native "tap"
function inputTapPolyfill(ele, e) {
if(ele.type === "radio") {
ele.checked = !ele.checked;
ionic.trigger('click', {
target: ele
});
} else if(ele.type === "checkbox") {
ele.checked = !ele.checked;
ionic.trigger('change', {
target: ele
});
} else if(ele.type === "submit" || ele.type === "button") {
ionic.trigger('click', {
target: ele
});
} else {
ele.focus();
}
e.stopPropagation();
e.preventDefault();
return false;
}
function tapPolyfill(e) {
// if the source event wasn't from a touch event then don't use this polyfill
if(!e.gesture || e.gesture.pointerType !== "touch" || !e.gesture.srcEvent) return;
// An internal Ionic indicator for angular directives that contain
// elements that normally need poly behavior, but are already processed
// (like the radio directive that has a radio button in it, but handles
// the tap stuff itself). This is in contrast to preventDefault which will
// mess up other operations like change events and such
if(e.alreadyHandled) {
return;
}
e = e.gesture.srcEvent; // evaluate the actual source event, not the created event by gestures.js
var ele = e.target;
while(ele) {
if( ele.tagName === "INPUT" || ele.tagName === "TEXTAREA" || ele.tagName === "SELECT" ) {
return inputTapPolyfill(ele, e);
} else if( ele.tagName === "LABEL" ) {
if(ele.control) {
return inputTapPolyfill(ele.control, e);
}
} else if( ele.tagName === "A" || ele.tagName === "BUTTON" ) {
ionic.trigger('click', {
target: ele
});
e.stopPropagation();
e.preventDefault();
return false;
}
ele = ele.parentElement;
}
// they didn't tap one of the above elements
// if the currently active element is an input, and they tapped outside
// of the current input, then unset its focus (blur) so the keyboard goes away
var activeElement = document.activeElement;
if(activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.tagName === "SELECT")) {
activeElement.blur();
e.stopPropagation();
e.preventDefault();
return false;
}
}
// global tap event listener polyfill for HTML elements that were "tapped" by the user
ionic.on("tap", tapPolyfill, window);
})(this, document, ionic);
;
(function(ionic) {
/**
* Various utilities used throughout Ionic
*
* Some of these are adopted from underscore.js and backbone.js, both also MIT licensed.
*/
ionic.Utils = {
arrayMove: function (arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length;
while ((k--) + 1) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr;
},
/**
* Return a function that will be called with the given context
*/
proxy: function(func, context) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(Array.prototype.slice.call(arguments)));
};
},
/**
* Only call a function once in the given interval.
*
* @param func {Function} the function to call
* @param wait {int} how long to wait before/after to allow function calls
* @param immediate {boolean} whether to call immediately or after the wait interval
*/
debounce: function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
return function() {
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) result = func.apply(context, args);
return result;
};
},
/**
* Throttle the given fun, only allowing it to be
* called at most every `wait` ms.
*/
throttle: function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
// Borrowed from Backbone.js's extend
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
inherit: function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
ionic.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) ionic.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
},
// Extend adapted from Underscore.js
extend: function(obj) {
var args = Array.prototype.slice.call(arguments, 1);
for(var i = 0; i < args.length; i++) {
var source = args[i];
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
}
return obj;
}
};
// Bind a few of the most useful functions to the ionic scope
ionic.inherit = ionic.Utils.inherit;
ionic.extend = ionic.Utils.extend;
ionic.throttle = ionic.Utils.throttle;
ionic.proxy = ionic.Utils.proxy;
ionic.debounce = ionic.Utils.debounce;
})(window.ionic);
;
(function(ionic) {
'use strict';
ionic.views.View = function() {
this.initialize.apply(this, arguments);
};
ionic.views.View.inherit = ionic.inherit;
ionic.extend(ionic.views.View.prototype, {
initialize: function() {}
});
})(window.ionic);
;
/*
* Scroller
* http://github.com/zynga/scroller
*
* Copyright 2011, Zynga Inc.
* Licensed under the MIT License.
* https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt
*
* Based on the work of: Unify Project (unify-project.org)
* http://unify-project.org
* Copyright 2011, Deutsche Telekom AG
* License: MIT + Apache (V2)
*/
/**
* Generic animation class with support for dropped frames both optional easing and duration.
*
* Optional duration is useful when the lifetime is defined by another condition than time
* e.g. speed of an animating object, etc.
*
* Dropped frame logic allows to keep using the same updater logic independent from the actual
* rendering. This eases a lot of cases where it might be pretty complex to break down a state
* based on the pure time difference.
*/
(function(global) {
var time = Date.now || function() {
return +new Date();
};
var desiredFrames = 60;
var millisecondsPerSecond = 1000;
var running = {};
var counter = 1;
// Create namespaces
if (!global.core) {
global.core = { effect : {} };
} else if (!core.effect) {
core.effect = {};
}
core.effect.Animate = {
/**
* A requestAnimationFrame wrapper / polyfill.
*
* @param callback {Function} The callback to be invoked before the next repaint.
* @param root {HTMLElement} The root element for the repaint
*/
requestAnimationFrame: (function() {
// Check for request animation Frame support
var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame;
var isNative = !!requestFrame;
if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) {
isNative = false;
}
if (isNative) {
return function(callback, root) {
requestFrame(callback, root)
};
}
var TARGET_FPS = 60;
var requests = {};
var requestCount = 0;
var rafHandle = 1;
var intervalHandle = null;
var lastActive = +new Date();
return function(callback, root) {
var callbackHandle = rafHandle++;
// Store callback
requests[callbackHandle] = callback;
requestCount++;
// Create timeout at first request
if (intervalHandle === null) {
intervalHandle = setInterval(function() {
var time = +new Date();
var currentRequests = requests;
// Reset data structure before executing callbacks
requests = {};
requestCount = 0;
for(var key in currentRequests) {
if (currentRequests.hasOwnProperty(key)) {
currentRequests[key](time);
lastActive = time;
}
}
// Disable the timeout when nothing happens for a certain
// period of time
if (time - lastActive > 2500) {
clearInterval(intervalHandle);
intervalHandle = null;
}
}, 1000 / TARGET_FPS);
}
return callbackHandle;
};
})(),
/**
* Stops the given animation.
*
* @param id {Integer} Unique animation ID
* @return {Boolean} Whether the animation was stopped (aka, was running before)
*/
stop: function(id) {
var cleared = running[id] != null;
if (cleared) {
running[id] = null;
}
return cleared;
},
/**
* Whether the given animation is still running.
*
* @param id {Integer} Unique animation ID
* @return {Boolean} Whether the animation is still running
*/
isRunning: function(id) {
return running[id] != null;
},
/**
* Start the animation.
*
* @param stepCallback {Function} Pointer to function which is executed on every step.
* Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }`
* @param verifyCallback {Function} Executed before every animation step.
* Signature of the method should be `function() { return continueWithAnimation; }`
* @param completedCallback {Function}
* Signature of the method should be `function(droppedFrames, finishedAnimation) {}`
* @param duration {Integer} Milliseconds to run the animation
* @param easingMethod {Function} Pointer to easing function
* Signature of the method should be `function(percent) { return modifiedValue; }`
* @param root {Element ? document.body} Render root, when available. Used for internal
* usage of requestAnimationFrame.
* @return {Integer} Identifier of animation. Can be used to stop it any time.
*/
start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) {
var start = time();
var lastFrame = start;
var percent = 0;
var dropCounter = 0;
var id = counter++;
if (!root) {
root = document.body;
}
// Compacting running db automatically every few new animations
if (id % 20 === 0) {
var newRunning = {};
for (var usedId in running) {
newRunning[usedId] = true;
}
running = newRunning;
}
// This is the internal step method which is called every few milliseconds
var step = function(virtual) {
// Normalize virtual value
var render = virtual !== true;
// Get current time
var now = time();
// Verification is executed before next animation step
if (!running[id] || (verifyCallback && !verifyCallback(id))) {
running[id] = null;
completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false);
return;
}
// For the current rendering to apply let's update omitted steps in memory.
// This is important to bring internal state variables up-to-date with progress in time.
if (render) {
var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1;
for (var j = 0; j < Math.min(droppedFrames, 4); j++) {
step(true);
dropCounter++;
}
}
// Compute percent value
if (duration) {
percent = (now - start) / duration;
if (percent > 1) {
percent = 1;
}
}
// Execute step callback, then...
var value = easingMethod ? easingMethod(percent) : percent;
if ((stepCallback(value, now, render) === false || percent === 1) && render) {
running[id] = null;
completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null);
} else if (render) {
lastFrame = now;
core.effect.Animate.requestAnimationFrame(step, root);
}
};
// Mark as running
running[id] = true;
// Init first step
core.effect.Animate.requestAnimationFrame(step, root);
// Return unique animation ID
return id;
}
};
})(this);
/*
* Scroller
* http://github.com/zynga/scroller
*
* Copyright 2011, Zynga Inc.
* Licensed under the MIT License.
* https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt
*
* Based on the work of: Unify Project (unify-project.org)
* http://unify-project.org
* Copyright 2011, Deutsche Telekom AG
* License: MIT + Apache (V2)
*/
var Scroller;
(function(ionic) {
var NOOP = function(){};
// Easing Equations (c) 2003 Robert Penner, all rights reserved.
// Open source under the BSD License.
/**
* @param pos {Number} position between 0 (start of effect) and 1 (end of effect)
**/
var easeOutCubic = function(pos) {
return (Math.pow((pos - 1), 3) + 1);
};
/**
* @param pos {Number} position between 0 (start of effect) and 1 (end of effect)
**/
var easeInOutCubic = function(pos) {
if ((pos /= 0.5) < 1) {
return 0.5 * Math.pow(pos, 3);
}
return 0.5 * (Math.pow((pos - 2), 3) + 2);
};
/**
* A pure logic 'component' for 'virtual' scrolling/zooming.
*/
ionic.views.Scroll = ionic.views.View.inherit({
initialize: function(options) {
var self = this;
this.__container = options.el;
this.__content = options.el.firstElementChild;
this.options = {
/** Disable scrolling on x-axis by default */
scrollingX: false,
scrollbarX: true,
/** Enable scrolling on y-axis */
scrollingY: true,
scrollbarY: true,
/** The minimum size the scrollbars scale to while scrolling */
minScrollbarSizeX: 5,
minScrollbarSizeY: 5,
/** Scrollbar fading after scrolling */
scrollbarsFade: true,
scrollbarFadeDelay: 300,
/** The initial fade delay when the pane is resized or initialized */
scrollbarResizeFadeDelay: 1000,
/** Enable animations for deceleration, snap back, zooming and scrolling */
animating: true,
/** duration for animations triggered by scrollTo/zoomTo */
animationDuration: 250,
/** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */
bouncing: true,
/** Enable locking to the main axis if user moves only slightly on one of them at start */
locking: true,
/** Enable pagination mode (switching between full page content panes) */
paging: false,
/** Enable snapping of content to a configured pixel grid */
snapping: false,
/** Enable zooming of content via API, fingers and mouse wheel */
zooming: false,
/** Minimum zoom level */
minZoom: 0.5,
/** Maximum zoom level */
maxZoom: 3,
/** Multiply or decrease scrolling speed **/
speedMultiplier: 1,
/** Callback that is fired on the later of touch end or deceleration end,
provided that another scrolling action has not begun. Used to know
when to fade out a scrollbar. */
scrollingComplete: NOOP,
/** This configures the amount of change applied to deceleration when reaching boundaries **/
penetrationDeceleration : 0.03,
/** This configures the amount of change applied to acceleration when reaching boundaries **/
penetrationAcceleration : 0.08,
// The ms interval for triggering scroll events
scrollEventInterval: 50
};
for (var key in options) {
this.options[key] = options[key];
}
this.hintResize = ionic.debounce(function() {
self.resize();
}, 1000, true);
this.triggerScrollEvent = ionic.throttle(function() {
ionic.trigger('scroll', {
scrollTop: self.__scrollTop,
scrollLeft: self.__scrollLeft,
target: self.__container
});
}, this.options.scrollEventInterval);
this.triggerScrollEndEvent = function() {
ionic.trigger('scrollend', {
scrollTop: self.__scrollTop,
scrollLeft: self.__scrollLeft,
target: self.__container
});
};
// Get the render update function, initialize event handlers,
// and calculate the size of the scroll container
this.__callback = this.getRenderFn();
this.__initEventHandlers();
this.__createScrollbars();
this.resize();
// Fade them out
this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay);
},
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: STATUS
---------------------------------------------------------------------------
*/
/** {Boolean} Whether only a single finger is used in touch handling */
__isSingleTouch: false,
/** {Boolean} Whether a touch event sequence is in progress */
__isTracking: false,
/** {Boolean} Whether a deceleration animation went to completion. */
__didDecelerationComplete: false,
/**
* {Boolean} Whether a gesture zoom/rotate event is in progress. Activates when
* a gesturestart event happens. This has higher priority than dragging.
*/
__isGesturing: false,
/**
* {Boolean} Whether the user has moved by such a distance that we have enabled
* dragging mode. Hint: It's only enabled after some pixels of movement to
* not interrupt with clicks etc.
*/
__isDragging: false,
/**
* {Boolean} Not touching and dragging anymore, and smoothly animating the
* touch sequence using deceleration.
*/
__isDecelerating: false,
/**
* {Boolean} Smoothly animating the currently configured change
*/
__isAnimating: false,
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: DIMENSIONS
---------------------------------------------------------------------------
*/
/** {Integer} Available outer left position (from document perspective) */
__clientLeft: 0,
/** {Integer} Available outer top position (from document perspective) */
__clientTop: 0,
/** {Integer} Available outer width */
__clientWidth: 0,
/** {Integer} Available outer height */
__clientHeight: 0,
/** {Integer} Outer width of content */
__contentWidth: 0,
/** {Integer} Outer height of content */
__contentHeight: 0,
/** {Integer} Snapping width for content */
__snapWidth: 100,
/** {Integer} Snapping height for content */
__snapHeight: 100,
/** {Integer} Height to assign to refresh area */
__refreshHeight: null,
/** {Boolean} Whether the refresh process is enabled when the event is released now */
__refreshActive: false,
/** {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */
__refreshActivate: null,
/** {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */
__refreshDeactivate: null,
/** {Function} Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */
__refreshStart: null,
/** {Number} Zoom level */
__zoomLevel: 1,
/** {Number} Scroll position on x-axis */
__scrollLeft: 0,
/** {Number} Scroll position on y-axis */
__scrollTop: 0,
/** {Integer} Maximum allowed scroll position on x-axis */
__maxScrollLeft: 0,
/** {Integer} Maximum allowed scroll position on y-axis */
__maxScrollTop: 0,
/* {Number} Scheduled left position (final position when animating) */
__scheduledLeft: 0,
/* {Number} Scheduled top position (final position when animating) */
__scheduledTop: 0,
/* {Number} Scheduled zoom level (final scale when animating) */
__scheduledZoom: 0,
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: LAST POSITIONS
---------------------------------------------------------------------------
*/
/** {Number} Left position of finger at start */
__lastTouchLeft: null,
/** {Number} Top position of finger at start */
__lastTouchTop: null,
/** {Date} Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */
__lastTouchMove: null,
/** {Array} List of positions, uses three indexes for each state: left, top, timestamp */
__positions: null,
/*
---------------------------------------------------------------------------
INTERNAL FIELDS :: DECELERATION SUPPORT
---------------------------------------------------------------------------
*/
/** {Integer} Minimum left scroll position during deceleration */
__minDecelerationScrollLeft: null,
/** {Integer} Minimum top scroll position during deceleration */
__minDecelerationScrollTop: null,
/** {Integer} Maximum left scroll position during deceleration */
__maxDecelerationScrollLeft: null,
/** {Integer} Maximum top scroll position during deceleration */
__maxDecelerationScrollTop: null,
/** {Number} Current factor to modify horizontal scroll position with on every step */
__decelerationVelocityX: null,
/** {Number} Current factor to modify vertical scroll position with on every step */
__decelerationVelocityY: null,
/** {String} the browser-specific property to use for transforms */
__transformProperty: null,
__perspectiveProperty: null,
/** {Object} scrollbar indicators */
__indicatorX: null,
__indicatorY: null,
/** Timeout for scrollbar fading */
__scrollbarFadeTimeout: null,
/** {Boolean} whether we've tried to wait for size already */
__didWaitForSize: null,
__sizerTimeout: null,
__initEventHandlers: function() {
var self = this;
// Event Handler
var container = this.__container;
if ('ontouchstart' in window) {
container.addEventListener("touchstart", function(e) {
// Don't react if initial down happens on a form element
if (e.target.tagName.match(/input|textarea|select/i)) {
return;
}
self.doTouchStart(e.touches, e.timeStamp);
e.preventDefault();
}, false);
document.addEventListener("touchmove", function(e) {
if(e.defaultPrevented) {
return;
}
self.doTouchMove(e.touches, e.timeStamp);
}, false);
document.addEventListener("touchend", function(e) {
self.doTouchEnd(e.timeStamp);
}, false);
} else {
var mousedown = false;
container.addEventListener("mousedown", function(e) {
// Don't react if initial down happens on a form element
if (e.target.tagName.match(/input|textarea|select/i)) {
return;
}
self.doTouchStart([{
pageX: e.pageX,
pageY: e.pageY
}], e.timeStamp);
mousedown = true;
}, false);
document.addEventListener("mousemove", function(e) {
if (!mousedown || e.defaultPrevented) {
return;
}
self.doTouchMove([{
pageX: e.pageX,
pageY: e.pageY
}], e.timeStamp);
mousedown = true;
}, false);
document.addEventListener("mouseup", function(e) {
if (!mousedown) {
return;
}
self.doTouchEnd(e.timeStamp);
mousedown = false;
}, false);
}
},
/** Create a scroll bar div with the given direction **/
__createScrollbar: function(direction) {
var bar = document.createElement('div'),
indicator = document.createElement('div');
indicator.className = 'scroll-bar-indicator';
if(direction == 'h') {
bar.className = 'scroll-bar scroll-bar-h';
} else {
bar.className = 'scroll-bar scroll-bar-v';
}
bar.appendChild(indicator);
return bar;
},
__createScrollbars: function() {
var indicatorX, indicatorY;
if(this.options.scrollingX) {
indicatorX = {
el: this.__createScrollbar('h'),
sizeRatio: 1
};
indicatorX.indicator = indicatorX.el.children[0];
if(this.options.scrollbarX) {
this.__container.appendChild(indicatorX.el);
}
this.__indicatorX = indicatorX;
}
if(this.options.scrollingY) {
indicatorY = {
el: this.__createScrollbar('v'),
sizeRatio: 1
};
indicatorY.indicator = indicatorY.el.children[0];
if(this.options.scrollbarY) {
this.__container.appendChild(indicatorY.el);
}
this.__indicatorY = indicatorY;
}
},
__resizeScrollbars: function() {
var self = this;
// Bring the scrollbars in to show the content change
self.__fadeScrollbars('in');
// Update horiz bar
if(self.__indicatorX) {
var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20);
if(width > self.__contentWidth) {
width = 0;
}
self.__indicatorX.size = width;
self.__indicatorX.minScale = this.options.minScrollbarSizeX / width;
self.__indicatorX.indicator.style.width = width + 'px';
self.__indicatorX.maxPos = self.__clientWidth - width;
self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1;
}
// Update vert bar
if(self.__indicatorY) {
var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20);
if(height > self.__contentHeight) {
height = 0;
}
self.__indicatorY.size = height;
self.__indicatorY.minScale = this.options.minScrollbarSizeY / height;
self.__indicatorY.maxPos = self.__clientHeight - height;
self.__indicatorY.indicator.style.height = height + 'px';
self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1;
}
},
/**
* Move and scale the scrollbars as the page scrolls.
*/
__repositionScrollbars: function() {
var self = this, width, heightScale,
widthDiff, heightDiff,
x, y,
xstop = 0, ystop = 0;
if(self.__indicatorX) {
// Handle the X scrollbar
// Don't go all the way to the right if we have a vertical scrollbar as well
if(self.__indicatorY) xstop = 10;
x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0,
// The the difference between the last content X position, and our overscrolled one
widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop);
if(self.__scrollLeft < 0) {
widthScale = Math.max(self.__indicatorX.minScale,
(self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size);
// Stay at left
x = 0;
// Make sure scale is transformed from the left/center origin point
self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center';
} else if(widthDiff > 0) {
widthScale = Math.max(self.__indicatorX.minScale,
(self.__indicatorX.size - widthDiff) / self.__indicatorX.size);
// Stay at the furthest x for the scrollable viewport
x = self.__indicatorX.maxPos - xstop;
// Make sure scale is transformed from the right/center origin point
self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center';
} else {
// Normal motion
x = Math.min(self.__maxScrollLeft, Math.max(0, x));
widthScale = 1;
}
self.__indicatorX.indicator.style[self.__transformProperty] = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')';
}
if(self.__indicatorY) {
y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0;
// Don't go all the way to the right if we have a vertical scrollbar as well
if(self.__indicatorX) ystop = 10;
heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop);
if(self.__scrollTop < 0) {
heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size);
// Stay at top
y = 0;
// Make sure scale is transformed from the center/top origin point
self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top';
} else if(heightDiff > 0) {
heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size);
// Stay at bottom of scrollable viewport
y = self.__indicatorY.maxPos - ystop;
// Make sure scale is transformed from the center/bottom origin point
self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom';
} else {
// Normal motion
y = Math.min(self.__maxScrollTop, Math.max(0, y));
heightScale = 1;
}
self.__indicatorY.indicator.style[self.__transformProperty] = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')';
}
},
__fadeScrollbars: function(direction, delay) {
var self = this;
if(!this.options.scrollbarsFade) {
return;
}
var className = 'scroll-bar-fade-out';
if(self.options.scrollbarsFade === true) {
clearTimeout(self.__scrollbarFadeTimeout);
if(direction == 'in') {
if(self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); }
if(self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); }
} else {
self.__scrollbarFadeTimeout = setTimeout(function() {
if(self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); }
if(self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); }
}, delay || self.options.scrollbarFadeDelay);
}
}
},
__scrollingComplete: function() {
var self = this;
self.options.scrollingComplete();
self.__fadeScrollbars('out');
},
resize: function() {
// Update Scroller dimensions for changed content
// Add padding to bottom of content
this.setDimensions(
this.__container.clientWidth,
this.__container.clientHeight,
Math.max(this.__content.scrollWidth, this.__content.offsetWidth),
Math.max(this.__content.scrollHeight, this.__content.offsetHeight+20));
},
/*
---------------------------------------------------------------------------
PUBLIC API
---------------------------------------------------------------------------
*/
getRenderFn: function() {
var self = this;
var content = this.__content;
var docStyle = document.documentElement.style;
var engine;
if ('MozAppearance' in docStyle) {
engine = 'gecko';
} else if ('WebkitAppearance' in docStyle) {
engine = 'webkit';
} else if (typeof navigator.cpuClass === 'string') {
engine = 'trident';
}
var vendorPrefix = {
trident: 'ms',
gecko: 'Moz',
webkit: 'Webkit',
presto: 'O'
}[engine];
var helperElem = document.createElement("div");
var undef;
var perspectiveProperty = vendorPrefix + "Perspective";
var transformProperty = vendorPrefix + "Transform";
var transformOriginProperty = vendorPrefix + 'TransformOrigin';
self.__perspectiveProperty = transformProperty;
self.__transformProperty = transformProperty;
self.__transformOriginProperty = transformOriginProperty;
if (helperElem.style[perspectiveProperty] !== undef) {
return function(left, top, zoom) {
content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0)';
self.__repositionScrollbars();
self.triggerScrollEvent();
};
} else if (helperElem.style[transformProperty] !== undef) {
return function(left, top, zoom) {
content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px)';
self.__repositionScrollbars();
self.triggerScrollEvent();
};
} else {
return function(left, top, zoom) {
content.style.marginLeft = left ? (-left/zoom) + 'px' : '';
content.style.marginTop = top ? (-top/zoom) + 'px' : '';
content.style.zoom = zoom || '';
self.__repositionScrollbars();
self.triggerScrollEvent();
};
}
},
/**
* Configures the dimensions of the client (outer) and content (inner) elements.
* Requires the available space for the outer element and the outer size of the inner element.
* All values which are falsy (null or zero etc.) are ignored and the old value is kept.
*
* @param clientWidth {Integer ? null} Inner width of outer element
* @param clientHeight {Integer ? null} Inner height of outer element
* @param contentWidth {Integer ? null} Outer width of inner element
* @param contentHeight {Integer ? null} Outer height of inner element
*/
setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) {
var self = this;
// Only update values which are defined
if (clientWidth === +clientWidth) {
self.__clientWidth = clientWidth;
}
if (clientHeight === +clientHeight) {
self.__clientHeight = clientHeight;
}
if (contentWidth === +contentWidth) {
self.__contentWidth = contentWidth;
}
if (contentHeight === +contentHeight) {
self.__contentHeight = contentHeight;
}
// Refresh maximums
self.__computeScrollMax();
self.__resizeScrollbars();
// Refresh scroll position
self.scrollTo(self.__scrollLeft, self.__scrollTop, true);
},
/**
* Sets the client coordinates in relation to the document.
*
* @param left {Integer ? 0} Left position of outer element
* @param top {Integer ? 0} Top position of outer element
*/
setPosition: function(left, top) {
var self = this;
self.__clientLeft = left || 0;
self.__clientTop = top || 0;
},
/**
* Configures the snapping (when snapping is active)
*
* @param width {Integer} Snapping width
* @param height {Integer} Snapping height
*/
setSnapSize: function(width, height) {
var self = this;
self.__snapWidth = width;
self.__snapHeight = height;
},
/**
* Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever
* the user event is released during visibility of this zone. This was introduced by some apps on iOS like
* the official Twitter client.
*
* @param height {Integer} Height of pull-to-refresh zone on top of rendered list
* @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release.
* @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled.
* @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh.
*/
activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) {
var self = this;
self.__refreshHeight = height;
self.__refreshActivate = activateCallback;
self.__refreshDeactivate = deactivateCallback;
self.__refreshStart = startCallback;
},
/**
* Starts pull-to-refresh manually.
*/
triggerPullToRefresh: function() {
// Use publish instead of scrollTo to allow scrolling to out of boundary position
// We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled
this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true);
if (this.__refreshStart) {
this.__refreshStart();
}
},
/**
* Signalizes that pull-to-refresh is finished.
*/
finishPullToRefresh: function() {
var self = this;
self.__refreshActive = false;
if (self.__refreshDeactivate) {
self.__refreshDeactivate();
}
self.scrollTo(self.__scrollLeft, self.__scrollTop, true);
},
/**
* Returns the scroll position and zooming values
*
* @return {Map} `left` and `top` scroll position and `zoom` level
*/
getValues: function() {
var self = this;
return {
left: self.__scrollLeft,
top: self.__scrollTop,
zoom: self.__zoomLevel
};
},
/**
* Returns the maximum scroll values
*
* @return {Map} `left` and `top` maximum scroll values
*/
getScrollMax: function() {
var self = this;
return {
left: self.__maxScrollLeft,
top: self.__maxScrollTop
};
},
/**
* Zooms to the given level. Supports optional animation. Zooms
* the center when no coordinates are given.
*
* @param level {Number} Level to zoom to
* @param animate {Boolean ? false} Whether to use animation
* @param originLeft {Number ? null} Zoom in at given left coordinate
* @param originTop {Number ? null} Zoom in at given top coordinate
*/
zoomTo: function(level, animate, originLeft, originTop) {
var self = this;
if (!self.options.zooming) {
throw new Error("Zooming is not enabled!");
}
// Stop deceleration
if (self.__isDecelerating) {
core.effect.Animate.stop(self.__isDecelerating);
self.__isDecelerating = false;
}
var oldLevel = self.__zoomLevel;
// Normalize input origin to center of viewport if not defined
if (originLeft == null) {
originLeft = self.__clientWidth / 2;
}
if (originTop == null) {
originTop = self.__clientHeight / 2;
}
// Limit level according to configuration
level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);
// Recompute maximum values while temporary tweaking maximum scroll ranges
self.__computeScrollMax(level);
// Recompute left and top coordinates based on new zoom level
var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft;
var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop;
// Limit x-axis
if (left > self.__maxScrollLeft) {
left = self.__maxScrollLeft;
} else if (left < 0) {
left = 0;
}
// Limit y-axis
if (top > self.__maxScrollTop) {
top = self.__maxScrollTop;
} else if (top < 0) {
top = 0;
}
// Push values out
self.__publish(left, top, level, animate);
},
/**
* Zooms the content by the given factor.
*
* @param factor {Number} Zoom by given factor
* @param animate {Boolean ? false} Whether to use animation
* @param originLeft {Number ? 0} Zoom in at given left coordinate
* @param originTop {Number ? 0} Zoom in at given top coordinate
*/
zoomBy: function(factor, animate, originLeft, originTop) {
var self = this;
self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop);
},
/**
* Scrolls to the given position. Respect limitations and snapping automatically.
*
* @param left {Number?null} Horizontal scroll position, keeps current if value is <code>null</code>
* @param top {Number?null} Vertical scroll position, keeps current if value is <code>null</code>
* @param animate {Boolean?false} Whether the scrolling should happen using an animation
* @param zoom {Number?null} Zoom level to go to
*/
scrollTo: function(left, top, animate, zoom) {
var self = this;
// Stop deceleration
if (self.__isDecelerating) {
core.effect.Animate.stop(self.__isDecelerating);
self.__isDecelerating = false;
}
// Correct coordinates based on new zoom level
if (zoom != null && zoom !== self.__zoomLevel) {
if (!self.options.zooming) {
throw new Error("Zooming is not enabled!");
}
left *= zoom;
top *= zoom;
// Recompute maximum values while temporary tweaking maximum scroll ranges
self.__computeScrollMax(zoom);
} else {
// Keep zoom when not defined
zoom = self.__zoomLevel;
}
if (!self.options.scrollingX) {
left = self.__scrollLeft;
} else {
if (self.options.paging) {
left = Math.round(left / self.__clientWidth) * self.__clientWidth;
} else if (self.options.snapping) {
left = Math.round(left / self.__snapWidth) * self.__snapWidth;
}
}
if (!self.options.scrollingY) {
top = self.__scrollTop;
} else {
if (self.options.paging) {
top = Math.round(top / self.__clientHeight) * self.__clientHeight;
} else if (self.options.snapping) {
top = Math.round(top / self.__snapHeight) * self.__snapHeight;
}
}
// Limit for allowed ranges
left = Math.max(Math.min(self.__maxScrollLeft, left), 0);
top = Math.max(Math.min(self.__maxScrollTop, top), 0);
// Don't animate when no change detected, still call publish to make sure
// that rendered position is really in-sync with internal data
if (left === self.__scrollLeft && top === self.__scrollTop) {
animate = false;
}
// Publish new values
self.__publish(left, top, zoom, animate);
},
/**
* Scroll by the given offset
*
* @param left {Number ? 0} Scroll x-axis by given offset
* @param top {Number ? 0} Scroll x-axis by given offset
* @param animate {Boolean ? false} Whether to animate the given change
*/
scrollBy: function(left, top, animate) {
var self = this;
var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;
var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;
self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);
},
/*
---------------------------------------------------------------------------
EVENT CALLBACKS
---------------------------------------------------------------------------
*/
/**
* Mouse wheel handler for zooming support
*/
doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) {
var self = this;
var change = wheelDelta > 0 ? 0.97 : 1.03;
return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop);
},
/**
* Touch start handler for scrolling support
*/
doTouchStart: function(touches, timeStamp) {
this.hintResize();
// Array-like check is enough here
if (touches.length == null) {
throw new Error("Invalid touch list: " + touches);
}
if (timeStamp instanceof Date) {
timeStamp = timeStamp.valueOf();
}
if (typeof timeStamp !== "number") {
throw new Error("Invalid timestamp value: " + timeStamp);
}
var self = this;
self.__fadeScrollbars('in');
// Reset interruptedAnimation flag
self.__interruptedAnimation = true;
// Stop deceleration
if (self.__isDecelerating) {
core.effect.Animate.stop(self.__isDecelerating);
self.__isDecelerating = false;
self.__interruptedAnimation = true;
}
// Stop animation
if (self.__isAnimating) {
core.effect.Animate.stop(self.__isAnimating);
self.__isAnimating = false;
self.__interruptedAnimation = true;
}
// Use center point when dealing with two fingers
var currentTouchLeft, currentTouchTop;
var isSingleTouch = touches.length === 1;
if (isSingleTouch) {
currentTouchLeft = touches[0].pageX;
currentTouchTop = touches[0].pageY;
} else {
currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
}
// Store initial positions
self.__initialTouchLeft = currentTouchLeft;
self.__initialTouchTop = currentTouchTop;
// Store current zoom level
self.__zoomLevelStart = self.__zoomLevel;
// Store initial touch positions
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
// Store initial move time stamp
self.__lastTouchMove = timeStamp;
// Reset initial scale
self.__lastScale = 1;
// Reset locking flags
self.__enableScrollX = !isSingleTouch && self.options.scrollingX;
self.__enableScrollY = !isSingleTouch && self.options.scrollingY;
// Reset tracking flag
self.__isTracking = true;
// Reset deceleration complete flag
self.__didDecelerationComplete = false;
// Dragging starts directly with two fingers, otherwise lazy with an offset
self.__isDragging = !isSingleTouch;
// Some features are disabled in multi touch scenarios
self.__isSingleTouch = isSingleTouch;
// Clearing data structure
self.__positions = [];
},
/**
* Touch move handler for scrolling support
*/
doTouchMove: function(touches, timeStamp, scale) {
// Array-like check is enough here
if (touches.length == null) {
throw new Error("Invalid touch list: " + touches);
}
if (timeStamp instanceof Date) {
timeStamp = timeStamp.valueOf();
}
if (typeof timeStamp !== "number") {
throw new Error("Invalid timestamp value: " + timeStamp);
}
var self = this;
// Ignore event when tracking is not enabled (event might be outside of element)
if (!self.__isTracking) {
return;
}
var currentTouchLeft, currentTouchTop;
// Compute move based around of center of fingers
if (touches.length === 2) {
currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
} else {
currentTouchLeft = touches[0].pageX;
currentTouchTop = touches[0].pageY;
}
var positions = self.__positions;
// Are we already is dragging mode?
if (self.__isDragging) {
// Compute move distance
var moveX = currentTouchLeft - self.__lastTouchLeft;
var moveY = currentTouchTop - self.__lastTouchTop;
// Read previous scroll position and zooming
var scrollLeft = self.__scrollLeft;
var scrollTop = self.__scrollTop;
var level = self.__zoomLevel;
// Work with scaling
if (scale != null && self.options.zooming) {
var oldLevel = level;
// Recompute level based on previous scale and new scale
level = level / self.__lastScale * scale;
// Limit level according to configuration
level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);
// Only do further compution when change happened
if (oldLevel !== level) {
// Compute relative event position to container
var currentTouchLeftRel = currentTouchLeft - self.__clientLeft;
var currentTouchTopRel = currentTouchTop - self.__clientTop;
// Recompute left and top coordinates based on new zoom level
scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel;
scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel;
// Recompute max scroll values
self.__computeScrollMax(level);
}
}
if (self.__enableScrollX) {
scrollLeft -= moveX * this.options.speedMultiplier;
var maxScrollLeft = self.__maxScrollLeft;
if (scrollLeft > maxScrollLeft || scrollLeft < 0) {
// Slow down on the edges
if (self.options.bouncing) {
scrollLeft += (moveX / 2 * this.options.speedMultiplier);
} else if (scrollLeft > maxScrollLeft) {
scrollLeft = maxScrollLeft;
} else {
scrollLeft = 0;
}
}
}
// Compute new vertical scroll position
if (self.__enableScrollY) {
scrollTop -= moveY * this.options.speedMultiplier;
var maxScrollTop = self.__maxScrollTop;
if (scrollTop > maxScrollTop || scrollTop < 0) {
// Slow down on the edges
if (self.options.bouncing) {
scrollTop += (moveY / 2 * this.options.speedMultiplier);
// Support pull-to-refresh (only when only y is scrollable)
if (!self.__enableScrollX && self.__refreshHeight != null) {
if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) {
self.__refreshActive = true;
if (self.__refreshActivate) {
self.__refreshActivate();
}
} else if (self.__refreshActive && scrollTop > -self.__refreshHeight) {
self.__refreshActive = false;
if (self.__refreshDeactivate) {
self.__refreshDeactivate();
}
}
}
} else if (scrollTop > maxScrollTop) {
scrollTop = maxScrollTop;
} else {
scrollTop = 0;
}
}
}
// Keep list from growing infinitely (holding min 10, max 20 measure points)
if (positions.length > 60) {
positions.splice(0, 30);
}
// Track scroll movement for decleration
positions.push(scrollLeft, scrollTop, timeStamp);
// Sync scroll position
self.__publish(scrollLeft, scrollTop, level);
// Otherwise figure out whether we are switching into dragging mode now.
} else {
var minimumTrackingForScroll = self.options.locking ? 3 : 0;
var minimumTrackingForDrag = 5;
var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft);
var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop);
self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll;
self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll;
positions.push(self.__scrollLeft, self.__scrollTop, timeStamp);
self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag);
if (self.__isDragging) {
self.__interruptedAnimation = false;
}
}
// Update last touch positions and time stamp for next event
self.__lastTouchLeft = currentTouchLeft;
self.__lastTouchTop = currentTouchTop;
self.__lastTouchMove = timeStamp;
self.__lastScale = scale;
},
/**
* Touch end handler for scrolling support
*/
doTouchEnd: function(timeStamp) {
if (timeStamp instanceof Date) {
timeStamp = timeStamp.valueOf();
}
if (typeof timeStamp !== "number") {
throw new Error("Invalid timestamp value: " + timeStamp);
}
var self = this;
// Ignore event when tracking is not enabled (no touchstart event on element)
// This is required as this listener ('touchmove') sits on the document and not on the element itself.
if (!self.__isTracking) {
return;
}
// Not touching anymore (when two finger hit the screen there are two touch end events)
self.__isTracking = false;
// Be sure to reset the dragging flag now. Here we also detect whether
// the finger has moved fast enough to switch into a deceleration animation.
if (self.__isDragging) {
// Reset dragging flag
self.__isDragging = false;
// Start deceleration
// Verify that the last move detected was in some relevant time frame
if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) {
// Then figure out what the scroll position was about 100ms ago
var positions = self.__positions;
var endPos = positions.length - 1;
var startPos = endPos;
// Move pointer to position measured 100ms ago
for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) {
startPos = i;
}
// If start and stop position is identical in a 100ms timeframe,
// we cannot compute any useful deceleration.
if (startPos !== endPos) {
// Compute relative movement between these two points
var timeOffset = positions[endPos] - positions[startPos];
var movedLeft = self.__scrollLeft - positions[startPos - 2];
var movedTop = self.__scrollTop - positions[startPos - 1];
// Based on 50ms compute the movement to apply for each render step
self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60);
self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60);
// How much velocity is required to start the deceleration
var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1;
// Verify that we have enough velocity to start deceleration
if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) {
// Deactivate pull-to-refresh when decelerating
if (!self.__refreshActive) {
self.__startDeceleration(timeStamp);
}
}
} else {
self.__scrollingComplete();
}
} else if ((timeStamp - self.__lastTouchMove) > 100) {
self.__scrollingComplete();
}
}
// If this was a slower move it is per default non decelerated, but this
// still means that we want snap back to the bounds which is done here.
// This is placed outside the condition above to improve edge case stability
// e.g. touchend fired without enabled dragging. This should normally do not
// have modified the scroll positions or even showed the scrollbars though.
if (!self.__isDecelerating) {
if (self.__refreshActive && self.__refreshStart) {
// Use publish instead of scrollTo to allow scrolling to out of boundary position
// We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled
self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true);
if (self.__refreshStart) {
self.__refreshStart();
}
} else {
if (self.__interruptedAnimation || self.__isDragging) {
self.__scrollingComplete();
}
self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel);
// Directly signalize deactivation (nothing todo on refresh?)
if (self.__refreshActive) {
self.__refreshActive = false;
if (self.__refreshDeactivate) {
self.__refreshDeactivate();
}
}
}
}
// Fully cleanup list
self.__positions.length = 0;
},
/*
---------------------------------------------------------------------------
PRIVATE API
---------------------------------------------------------------------------
*/
/**
* Applies the scroll position to the content element
*
* @param left {Number} Left scroll position
* @param top {Number} Top scroll position
* @param animate {Boolean?false} Whether animation should be used to move to the new coordinates
*/
__publish: function(left, top, zoom, animate) {
var self = this;
// Remember whether we had an animation, then we try to continue based on the current "drive" of the animation
var wasAnimating = self.__isAnimating;
if (wasAnimating) {
core.effect.Animate.stop(wasAnimating);
self.__isAnimating = false;
}
if (animate && self.options.animating) {
// Keep scheduled positions for scrollBy/zoomBy functionality
self.__scheduledLeft = left;
self.__scheduledTop = top;
self.__scheduledZoom = zoom;
var oldLeft = self.__scrollLeft;
var oldTop = self.__scrollTop;
var oldZoom = self.__zoomLevel;
var diffLeft = left - oldLeft;
var diffTop = top - oldTop;
var diffZoom = zoom - oldZoom;
var step = function(percent, now, render) {
if (render) {
self.__scrollLeft = oldLeft + (diffLeft * percent);
self.__scrollTop = oldTop + (diffTop * percent);
self.__zoomLevel = oldZoom + (diffZoom * percent);
// Push values out
if (self.__callback) {
self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel);
}
}
};
var verify = function(id) {
return self.__isAnimating === id;
};
var completed = function(renderedFramesPerSecond, animationId, wasFinished) {
if (animationId === self.__isAnimating) {
self.__isAnimating = false;
}
if (self.__didDecelerationComplete || wasFinished) {
self.__scrollingComplete();
}
if (self.options.zooming) {
self.__computeScrollMax();
}
};
// When continuing based on previous animation we choose an ease-out animation instead of ease-in-out
self.__isAnimating = core.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic);
} else {
self.__scheduledLeft = self.__scrollLeft = left;
self.__scheduledTop = self.__scrollTop = top;
self.__scheduledZoom = self.__zoomLevel = zoom;
// Push values out
if (self.__callback) {
self.__callback(left, top, zoom);
}
// Fix max scroll ranges
if (self.options.zooming) {
self.__computeScrollMax();
}
}
},
/**
* Recomputes scroll minimum values based on client dimensions and content dimensions.
*/
__computeScrollMax: function(zoomLevel) {
var self = this;
if (zoomLevel == null) {
zoomLevel = self.__zoomLevel;
}
self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0);
self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0);
if(!self.__didWaitForSize && self.__maxScrollLeft == 0 && self.__maxScrollTop == 0) {
self.__didWaitForSize = true;
self.__waitForSize();
}
},
/**
* If the scroll view isn't sized correctly on start, wait until we have at least some size
*/
__waitForSize: function() {
var self = this;
clearTimeout(self.__sizerTimeout);
var sizer = function() {
self.resize();
if((self.options.scrollingX && self.__maxScrollLeft == 0) || (self.options.scrollingY && self.__maxScrollTop == 0)) {
//self.__sizerTimeout = setTimeout(sizer, 1000);
}
};
sizer();
self.__sizerTimeout = setTimeout(sizer, 1000);
},
/*
---------------------------------------------------------------------------
ANIMATION (DECELERATION) SUPPORT
---------------------------------------------------------------------------
*/
/**
* Called when a touch sequence end and the speed of the finger was high enough
* to switch into deceleration mode.
*/
__startDeceleration: function(timeStamp) {
var self = this;
if (self.options.paging) {
var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0);
var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0);
var clientWidth = self.__clientWidth;
var clientHeight = self.__clientHeight;
// We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area.
// Each page should have exactly the size of the client area.
self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth;
self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight;
self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth;
self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight;
} else {
self.__minDecelerationScrollLeft = 0;
self.__minDecelerationScrollTop = 0;
self.__maxDecelerationScrollLeft = self.__maxScrollLeft;
self.__maxDecelerationScrollTop = self.__maxScrollTop;
}
// Wrap class method
var step = function(percent, now, render) {
self.__stepThroughDeceleration(render);
};
// How much velocity is required to keep the deceleration running
var minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1;
// Detect whether it's still worth to continue animating steps
// If we are already slow enough to not being user perceivable anymore, we stop the whole process here.
var verify = function() {
var shouldContinue = Math.abs(self.__decelerationVelocityX) >= minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= minVelocityToKeepDecelerating;
if (!shouldContinue) {
self.__didDecelerationComplete = true;
}
return shouldContinue;
};
var completed = function(renderedFramesPerSecond, animationId, wasFinished) {
self.__isDecelerating = false;
if (self.__didDecelerationComplete) {
self.__scrollingComplete();
}
// Animate to grid when snapping is active, otherwise just fix out-of-boundary positions
if(self.options.paging) {
self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping);
}
};
// Start animation and switch on flag
self.__isDecelerating = core.effect.Animate.start(step, verify, completed);
},
/**
* Called on every step of the animation
*
* @param inMemory {Boolean?false} Whether to not render the current step, but keep it in memory only. Used internally only!
*/
__stepThroughDeceleration: function(render) {
var self = this;
//
// COMPUTE NEXT SCROLL POSITION
//
// Add deceleration to scroll position
var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;
var scrollTop = self.__scrollTop + self.__decelerationVelocityY;
//
// HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE
//
if (!self.options.bouncing) {
var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft);
if (scrollLeftFixed !== scrollLeft) {
scrollLeft = scrollLeftFixed;
self.__decelerationVelocityX = 0;
}
var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop);
if (scrollTopFixed !== scrollTop) {
scrollTop = scrollTopFixed;
self.__decelerationVelocityY = 0;
}
}
//
// UPDATE SCROLL POSITION
//
if (render) {
self.__publish(scrollLeft, scrollTop, self.__zoomLevel);
} else {
self.__scrollLeft = scrollLeft;
self.__scrollTop = scrollTop;
}
//
// SLOW DOWN
//
// Slow down velocity on every iteration
if (!self.options.paging) {
// This is the factor applied to every iteration of the animation
// to slow down the process. This should emulate natural behavior where
// objects slow down when the initiator of the movement is removed
var frictionFactor = 0.95;
self.__decelerationVelocityX *= frictionFactor;
self.__decelerationVelocityY *= frictionFactor;
}
//
// BOUNCING SUPPORT
//
if (self.options.bouncing) {
var scrollOutsideX = 0;
var scrollOutsideY = 0;
// This configures the amount of change applied to deceleration/acceleration when reaching boundaries
var penetrationDeceleration = self.options.penetrationDeceleration;
var penetrationAcceleration = self.options.penetrationAcceleration;
// Check limits
if (scrollLeft < self.__minDecelerationScrollLeft) {
scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft;
} else if (scrollLeft > self.__maxDecelerationScrollLeft) {
scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft;
}
if (scrollTop < self.__minDecelerationScrollTop) {
scrollOutsideY = self.__minDecelerationScrollTop - scrollTop;
} else if (scrollTop > self.__maxDecelerationScrollTop) {
scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop;
}
// Slow down until slow enough, then flip back to snap position
if (scrollOutsideX !== 0) {
if (scrollOutsideX * self.__decelerationVelocityX <= 0) {
self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration;
} else {
self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration;
}
}
if (scrollOutsideY !== 0) {
if (scrollOutsideY * self.__decelerationVelocityY <= 0) {
self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration;
} else {
self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration;
}
}
}
}
});
})(ionic);
;
(function(ionic) {
'use strict';
/**
* An ActionSheet is the slide up menu popularized on iOS.
*
* You see it all over iOS apps, where it offers a set of options
* triggered after an action.
*/
ionic.views.ActionSheet = ionic.views.View.inherit({
initialize: function(opts) {
this.el = opts.el;
},
show: function() {
// Force a reflow so the animation will actually run
this.el.offsetWidth;
this.el.classList.add('active');
},
hide: function() {
// Force a reflow so the animation will actually run
this.el.offsetWidth;
this.el.classList.remove('active');
}
});
})(ionic);
;
(function(ionic) {
'use strict';
ionic.views.HeaderBar = ionic.views.View.inherit({
initialize: function(opts) {
this.el = opts.el;
ionic.extend(this, {
alignTitle: 'center'
}, opts);
this.align();
},
/**
* Align the title text given the buttons in the header
* so that the header text size is maximized and aligned
* correctly as long as possible.
*/
align: function() {
var _this = this;
window.rAF(ionic.proxy(function() {
var i, c, childSize;
var childNodes = this.el.childNodes;
// Find the title element
var title = this.el.querySelector('.title');
if(!title) {
return;
}
var leftWidth = 0;
var rightWidth = 0;
var titlePos = Array.prototype.indexOf.call(childNodes, title);
// Compute how wide the left children are
for(i = 0; i < titlePos; i++) {
childSize = null;
c = childNodes[i];
if(c.nodeType == 3) {
childSize = ionic.DomUtil.getTextBounds(c);
} else if(c.nodeType == 1) {
childSize = c.getBoundingClientRect();
}
if(childSize) {
leftWidth += childSize.width;
}
}
// Compute how wide the right children are
for(i = titlePos + 1; i < childNodes.length; i++) {
childSize = null;
c = childNodes[i];
if(c.nodeType == 3) {
childSize = ionic.DomUtil.getTextBounds(c);
} else if(c.nodeType == 1) {
childSize = c.getBoundingClientRect();
}
if(childSize) {
rightWidth += childSize.width;
}
}
var margin = Math.max(leftWidth, rightWidth) + 10;
// Size and align the header title based on the sizes of the left and
// right children, and the desired alignment mode
if(this.alignTitle == 'center') {
if(margin > 10) {
title.style.left = margin + 'px';
title.style.right = margin + 'px';
}
if(title.offsetWidth < title.scrollWidth) {
if(rightWidth > 0) {
title.style.right = (rightWidth + 5) + 'px';
}
}
} else if(this.alignTitle == 'left') {
title.classList.add('title-left');
if(leftWidth > 0) {
title.style.left = (leftWidth + 15) + 'px';
}
} else if(this.alignTitle == 'right') {
title.classList.add('title-right');
if(rightWidth > 0) {
title.style.right = (rightWidth + 15) + 'px';
}
}
}, this));
}
});
})(ionic);
;
(function(ionic) {
'use strict';
var ITEM_CLASS = 'item';
var ITEM_CONTENT_CLASS = 'item-content';
var ITEM_SLIDING_CLASS = 'item-sliding';
var ITEM_OPTIONS_CLASS = 'item-options';
var ITEM_PLACEHOLDER_CLASS = 'item-placeholder';
var ITEM_REORDERING_CLASS = 'item-reordering';
var ITEM_DRAG_CLASS = 'item-drag';
var DragOp = function() {};
DragOp.prototype = {
start: function(e) {
},
drag: function(e) {
},
end: function(e) {
}
};
var SlideDrag = function(opts) {
this.dragThresholdX = opts.dragThresholdX || 10;
this.el = opts.el;
};
SlideDrag.prototype = new DragOp();
SlideDrag.prototype.start = function(e) {
var content, buttons, offsetX, buttonsWidth;
if(e.target.classList.contains(ITEM_CONTENT_CLASS)) {
content = e.target;
} else if(e.target.classList.contains(ITEM_CLASS)) {
content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);
}
// If we don't have a content area as one of our children (or ourselves), skip
if(!content) {
return;
}
// Make sure we aren't animating as we slide
content.classList.remove(ITEM_SLIDING_CLASS);
// Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)
offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0;
// Grab the buttons
buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);
if(!buttons) {
return;
}
buttonsWidth = buttons.offsetWidth;
this._currentDrag = {
buttonsWidth: buttonsWidth,
content: content,
startOffsetX: offsetX
};
};
SlideDrag.prototype.drag = function(e) {
var _this = this, buttonsWidth;
window.rAF(function() {
// We really aren't dragging
if(!_this._currentDrag) {
return;
}
// Check if we should start dragging. Check if we've dragged past the threshold,
// or we are starting from the open state.
if(!_this._isDragging &&
((Math.abs(e.gesture.deltaX) > _this.dragThresholdX) ||
(Math.abs(_this._currentDrag.startOffsetX) > 0)))
{
_this._isDragging = true;
}
if(_this._isDragging) {
buttonsWidth = _this._currentDrag.buttonsWidth;
// Grab the new X point, capping it at zero
var newX = Math.min(0, _this._currentDrag.startOffsetX + e.gesture.deltaX);
// If the new X position is past the buttons, we need to slow down the drag (rubber band style)
if(newX < -buttonsWidth) {
// Calculate the new X position, capped at the top of the buttons
newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));
}
_this._currentDrag.content.style.webkitTransform = 'translate3d(' + newX + 'px, 0, 0)';
_this._currentDrag.content.style.webkitTransition = 'none';
}
});
};
SlideDrag.prototype.end = function(e, doneCallback) {
var _this = this;
// There is no drag, just end immediately
if(!this._currentDrag) {
doneCallback && doneCallback();
return;
}
// If we are currently dragging, we want to snap back into place
// The final resting point X will be the width of the exposed buttons
var restingPoint = -this._currentDrag.buttonsWidth;
// Check if the drag didn't clear the buttons mid-point
// and we aren't moving fast enough to swipe open
if(e.gesture.deltaX > -(this._currentDrag.buttonsWidth/2)) {
// If we are going left but too slow, or going right, go back to resting
if(e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) {
restingPoint = 0;
} else if(e.gesture.direction == "right") {
restingPoint = 0;
}
}
// var content = this._currentDrag.content;
// var onRestingAnimationEnd = function(e) {
// if(e.propertyName == '-webkit-transform') {
// if(content) content.classList.remove(ITEM_SLIDING_CLASS);
// }
// e.target.removeEventListener('webkitTransitionEnd', onRestingAnimationEnd);
// };
window.rAF(function() {
// var currentX = parseFloat(_this._currentDrag.content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0;
// if(currentX !== restingPoint) {
// _this._currentDrag.content.classList.add(ITEM_SLIDING_CLASS);
// _this._currentDrag.content.addEventListener('webkitTransitionEnd', onRestingAnimationEnd);
// }
if(restingPoint === 0) {
_this._currentDrag.content.style.webkitTransform = '';
} else {
_this._currentDrag.content.style.webkitTransform = 'translate3d(' + restingPoint + 'px, 0, 0)';
}
_this._currentDrag.content.style.webkitTransition = '';
// Kill the current drag
_this._currentDrag = null;
// We are done, notify caller
doneCallback && doneCallback();
});
};
var ReorderDrag = function(opts) {
this.dragThresholdY = opts.dragThresholdY || 0;
this.onReorder = opts.onReorder;
this.el = opts.el;
};
ReorderDrag.prototype = new DragOp();
ReorderDrag.prototype.start = function(e) {
var content;
// Grab the starting Y point for the item
var offsetY = this.el.offsetTop;//parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0;
var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase());
var placeholder = this.el.cloneNode(true);
placeholder.classList.add(ITEM_PLACEHOLDER_CLASS);
this.el.parentNode.insertBefore(placeholder, this.el);
this.el.classList.add(ITEM_REORDERING_CLASS);
this._currentDrag = {
startOffsetTop: offsetY,
startIndex: startIndex,
placeholder: placeholder
};
};
ReorderDrag.prototype.drag = function(e) {
var _this = this;
window.rAF(function() {
// We really aren't dragging
if(!_this._currentDrag) {
return;
}
// Check if we should start dragging. Check if we've dragged past the threshold,
// or we are starting from the open state.
if(!_this._isDragging && Math.abs(e.gesture.deltaY) > _this.dragThresholdY) {
_this._isDragging = true;
}
if(_this._isDragging) {
var newY = _this._currentDrag.startOffsetTop + e.gesture.deltaY;
_this.el.style.top = newY + 'px';
_this._currentDrag.currentY = newY;
_this._reorderItems();
}
});
};
// When an item is dragged, we need to reorder any items for sorting purposes
ReorderDrag.prototype._reorderItems = function() {
var placeholder = this._currentDrag.placeholder;
var siblings = Array.prototype.slice.call(this._currentDrag.placeholder.parentNode.children);
// Remove the floating element from the child search list
siblings.splice(siblings.indexOf(this.el), 1);
var index = siblings.indexOf(this._currentDrag.placeholder);
var topSibling = siblings[Math.max(0, index - 1)];
var bottomSibling = siblings[Math.min(siblings.length, index+1)];
var thisOffsetTop = this._currentDrag.currentY;// + this._currentDrag.startOffsetTop;
if(topSibling && (thisOffsetTop < topSibling.offsetTop + topSibling.offsetHeight/2)) {
ionic.DomUtil.swapNodes(this._currentDrag.placeholder, topSibling);
return index - 1;
} else if(bottomSibling && thisOffsetTop > (bottomSibling.offsetTop + bottomSibling.offsetHeight/2)) {
ionic.DomUtil.swapNodes(bottomSibling, this._currentDrag.placeholder);
return index + 1;
}
};
ReorderDrag.prototype.end = function(e, doneCallback) {
if(!this._currentDrag) {
doneCallback && doneCallback();
return;
}
var placeholder = this._currentDrag.placeholder;
// Reposition the element
this.el.classList.remove(ITEM_REORDERING_CLASS);
this.el.style.top = 0;
var finalPosition = ionic.DomUtil.getChildIndex(placeholder, placeholder.nodeName.toLowerCase());
placeholder.parentNode.insertBefore(this.el, placeholder);
placeholder.parentNode.removeChild(placeholder);
this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalPosition);
this._currentDrag = null;
doneCallback && doneCallback();
};
/**
* The ListView handles a list of items. It will process drag animations, edit mode,
* and other operations that are common on mobile lists or table views.
*/
ionic.views.ListView = ionic.views.View.inherit({
initialize: function(opts) {
var _this = this;
opts = ionic.extend({
onReorder: function(el, oldIndex, newIndex) {},
virtualRemoveThreshold: -200,
virtualAddThreshold: 200
}, opts);
ionic.extend(this, opts);
if(!this.itemHeight && this.listEl) {
this.itemHeight = this.listEl.children[0] && parseInt(this.listEl.children[0].style.height, 10);
}
//ionic.views.ListView.__super__.initialize.call(this, opts);
this.onRefresh = opts.onRefresh || function() {};
this.onRefreshOpening = opts.onRefreshOpening || function() {};
this.onRefreshHolding = opts.onRefreshHolding || function() {};
window.ionic.onGesture('touch', function(e) {
_this._handleTouch(e);
}, this.el);
window.ionic.onGesture('release', function(e) {
_this._handleEndDrag(e);
}, this.el);
window.ionic.onGesture('drag', function(e) {
_this._handleDrag(e);
}, this.el);
// Start the drag states
this._initDrag();
},
/**
* Called to tell the list to stop refreshing. This is useful
* if you are refreshing the list and are done with refreshing.
*/
stopRefreshing: function() {
var refresher = this.el.querySelector('.list-refresher');
refresher.style.height = '0px';
},
/**
* If we scrolled and have virtual mode enabled, compute the window
* of active elements in order to figure out the viewport to render.
*/
didScroll: function(e) {
if(this.isVirtual) {
var itemHeight = this.itemHeight;
// TODO: This would be inaccurate if we are windowed
var totalItems = this.listEl.children.length;
// Grab the total height of the list
var scrollHeight = e.target.scrollHeight;
// Get the viewport height
var viewportHeight = this.el.parentNode.offsetHeight;
// scrollTop is the current scroll position
var scrollTop = e.scrollTop;
// High water is the pixel position of the first element to include (everything before
// that will be removed)
var highWater = Math.max(0, e.scrollTop + this.virtualRemoveThreshold);
// Low water is the pixel position of the last element to include (everything after
// that will be removed)
var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + this.virtualAddThreshold);
// Compute how many items per viewport size can show
var itemsPerViewport = Math.floor((lowWater - highWater) / itemHeight);
// Get the first and last elements in the list based on how many can fit
// between the pixel range of lowWater and highWater
var first = parseInt(Math.abs(highWater / itemHeight), 10);
var last = parseInt(Math.abs(lowWater / itemHeight), 10);
// Get the items we need to remove
this._virtualItemsToRemove = Array.prototype.slice.call(this.listEl.children, 0, first);
// Grab the nodes we will be showing
var nodes = Array.prototype.slice.call(this.listEl.children, first, first + itemsPerViewport);
this.renderViewport && this.renderViewport(highWater, lowWater, first, last);
}
},
didStopScrolling: function(e) {
if(this.isVirtual) {
for(var i = 0; i < this._virtualItemsToRemove.length; i++) {
var el = this._virtualItemsToRemove[i];
//el.parentNode.removeChild(el);
this.didHideItem && this.didHideItem(i);
}
// Once scrolling stops, check if we need to remove old items
}
},
_initDrag: function() {
//ionic.views.ListView.__super__._initDrag.call(this);
//this._isDragging = false;
this._dragOp = null;
},
// Return the list item from the given target
_getItem: function(target) {
while(target) {
if(target.classList.contains(ITEM_CLASS)) {
return target;
}
target = target.parentNode;
}
return null;
},
_startDrag: function(e) {
var _this = this;
this._isDragging = false;
// Check if this is a reorder drag
if(ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_DRAG_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
var item = this._getItem(e.target);
if(item) {
this._dragOp = new ReorderDrag({
el: item,
onReorder: function(el, start, end) {
_this.onReorder && _this.onReorder(el, start, end);
}
});
this._dragOp.start(e);
e.preventDefault();
return;
}
}
// Or check if this is a swipe to the side drag
else if((e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) {
this._dragOp = new SlideDrag({ el: this.el });
this._dragOp.start(e);
e.preventDefault();
return;
}
// We aren't handling it, so pass it up the chain
//ionic.views.ListView.__super__._startDrag.call(this, e);
},
_handleEndDrag: function(e) {
var _this = this;
if(!this._dragOp) {
//ionic.views.ListView.__super__._handleEndDrag.call(this, e);
return;
}
// Cancel touch timeout
clearTimeout(this._touchTimeout);
var items = _this.el.querySelectorAll('.item');
for(var i = 0, l = items.length; i < l; i++) {
items[i].classList.remove('active');
}
this._dragOp.end(e, function() {
_this._initDrag();
});
},
/**
* Process the drag event to move the item to the left or right.
*/
_handleDrag: function(e) {
var _this = this, content, buttons;
// If the user has a touch timeout to highlight an element, clear it if we
// get sufficient draggage
if(Math.abs(e.gesture.deltaX) > 10 || Math.abs(e.gesture.deltaY) > 10) {
clearTimeout(this._touchTimeout);
}
clearTimeout(this._touchTimeout);
// If we get a drag event, make sure we aren't in another drag, then check if we should
// start one
if(!this.isDragging && !this._dragOp) {
this._startDrag(e);
}
// No drag still, pass it up
if(!this._dragOp) {
//ionic.views.ListView.__super__._handleDrag.call(this, e);
return;
}
e.gesture.srcEvent.preventDefault();
this._dragOp.drag(e);
},
/**
* Handle the touch event to show the active state on an item if necessary.
*/
_handleTouch: function(e) {
var _this = this;
var item = ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_CLASS);
if(!item) { return; }
this._touchTimeout = setTimeout(function() {
var items = _this.el.querySelectorAll('.item');
for(var i = 0, l = items.length; i < l; i++) {
items[i].classList.remove('active');
}
item.classList.add('active');
}, 250);
},
});
})(ionic);
;
(function(ionic) {
'use strict';
/**
* An ActionSheet is the slide up menu popularized on iOS.
*
* You see it all over iOS apps, where it offers a set of options
* triggered after an action.
*/
ionic.views.Loading = ionic.views.View.inherit({
initialize: function(opts) {
var _this = this;
this.el = opts.el;
this.maxWidth = opts.maxWidth || 200;
this._loadingBox = this.el.querySelector('.loading');
},
show: function() {
var _this = this;
if(this._loadingBox) {
var lb = _this._loadingBox;
var width = Math.min(_this.maxWidth, Math.max(window.outerWidth - 40, lb.offsetWidth));
lb.style.width = width;
lb.style.marginLeft = (-lb.offsetWidth) / 2 + 'px';
lb.style.marginTop = (-lb.offsetHeight) / 2 + 'px';
_this.el.classList.add('active');
}
},
hide: function() {
// Force a reflow so the animation will actually run
this.el.offsetWidth;
this.el.classList.remove('active');
}
});
})(ionic);
;
(function(ionic) {
'use strict';
ionic.views.Modal = ionic.views.View.inherit({
initialize: function(opts) {
opts = ionic.extend({
focusFirstInput: false,
unfocusOnHide: true
}, opts);
ionic.extend(this, opts);
this.el = opts.el;
},
show: function() {
this.el.classList.add('active');
if(this.focusFirstInput) {
var input = this.el.querySelector('input, textarea');
input && input.focus && input.focus();
}
},
hide: function() {
this.el.classList.remove('active');
// Unfocus all elements
if(this.unfocusOnHide) {
var inputs = this.el.querySelectorAll('input, textarea');
for(var i = 0; i < inputs.length; i++) {
inputs[i].blur && inputs[i].blur();
}
}
}
});
})(ionic);
;
(function(ionic) {
'use strict';
ionic.views.NavBar = ionic.views.View.inherit({
initialize: function(opts) {
this.el = opts.el;
this._titleEl = this.el.querySelector('.title');
if(opts.hidden) {
this.hide();
}
},
hide: function() {
this.el.classList.add('hidden');
},
show: function() {
this.el.classList.remove('hidden');
},
shouldGoBack: function() {},
setTitle: function(title) {
if(!this._titleEl) {
return;
}
this._titleEl.innerHTML = title;
},
showBackButton: function(shouldShow) {
var _this = this;
if(!this._currentBackButton) {
var back = document.createElement('a');
back.className = 'button back';
back.innerHTML = 'Back';
this._currentBackButton = back;
this._currentBackButton.onclick = function(event) {
_this.shouldGoBack && _this.shouldGoBack();
};
}
if(shouldShow && !this._currentBackButton.parentNode) {
// Prepend the back button
this.el.insertBefore(this._currentBackButton, this.el.firstChild);
} else if(!shouldShow && this._currentBackButton.parentNode) {
// Remove the back button if it's there
this._currentBackButton.parentNode.removeChild(this._currentBackButton);
}
}
});
})(ionic);
;
(function(ionic) {
'use strict';
/**
* An ActionSheet is the slide up menu popularized on iOS.
*
* You see it all over iOS apps, where it offers a set of options
* triggered after an action.
*/
ionic.views.Popup = ionic.views.View.inherit({
initialize: function(opts) {
var _this = this;
this.el = opts.el;
},
setTitle: function(title) {
var titleEl = el.querySelector('.popup-title');
if(titleEl) {
titleEl.innerHTML = title;
}
},
alert: function(message) {
var _this = this;
window.rAF(function() {
_this.setTitle(message);
_this.el.classList.add('active');
});
},
hide: function() {
// Force a reflow so the animation will actually run
this.el.offsetWidth;
this.el.classList.remove('active');
}
});
})(ionic);
;
(function(ionic) {
'use strict';
/**
* The side menu view handles one of the side menu's in a Side Menu Controller
* configuration.
* It takes a DOM reference to that side menu element.
*/
ionic.views.SideMenu = ionic.views.View.inherit({
initialize: function(opts) {
this.el = opts.el;
this.width = opts.width;
this.isEnabled = opts.isEnabled || true;
},
getFullWidth: function() {
return this.width;
},
setIsEnabled: function(isEnabled) {
this.isEnabled = isEnabled;
},
bringUp: function() {
this.el.style.zIndex = 0;
},
pushDown: function() {
this.el.style.zIndex = -1;
}
});
ionic.views.SideMenuContent = ionic.views.View.inherit({
initialize: function(opts) {
var _this = this;
ionic.extend(this, {
animationClass: 'menu-animated',
onDrag: function(e) {},
onEndDrag: function(e) {},
}, opts);
ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el);
ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el);
},
_onDrag: function(e) {
this.onDrag && this.onDrag(e);
},
_onEndDrag: function(e) {
this.onEndDrag && this.onEndDrag(e);
},
disableAnimation: function() {
this.el.classList.remove(this.animationClass);
},
enableAnimation: function() {
this.el.classList.add(this.animationClass);
},
getTranslateX: function() {
return parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[0]);
},
setTranslateX: function(x) {
this.el.style.webkitTransform = 'translate3d(' + x + 'px, 0, 0)';
}
});
})(ionic);
;
/*
* Adapted from Swipe.js 2.0
*
* Brad Birdsall
* Copyright 2013, MIT License
*
*/
(function(ionic) {
'use strict';
ionic.views.Slider = ionic.views.View.inherit({
initialize: function (options) {
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
var container = options.el;
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = container.getBoundingClientRect().width || container.offsetWidth;
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index-1), -width, 0);
move(circle(index+1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
options.slidesChanged && options.slidesChanged();
}
function prev() {
if (options.continuous) slide(index-1);
else if (index) slide(index-1);
}
function next() {
if (options.continuous) slide(index+1);
else if (index < slides.length - 1) slide(index+1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) to = -direction * slides.length + to;
}
var diff = Math.abs(index-to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
if(event.type == 'mousedown' || event.type == 'mouseup' || event.type == 'mousemove') {
event.touches = [{
pageX: event.pageX,
pageY: event.pageY
}];
}
switch (event.type) {
case 'mousedown': this.start(event); break;
case 'touchstart': this.start(event); break;
case 'touchmove': this.move(event); break;
case 'mousemove': this.move(event); break;
case 'touchend': offloadFn(this.end(event)); break;
case 'mouseup': offloadFn(this.end(event)); break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend': offloadFn(this.transitionEnd(event)); break;
case 'resize': offloadFn(setup); break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
if(browser.touch) {
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
} else {
element.addEventListener('mousemove', this, false);
element.addEventListener('mouseup', this, false);
}
},
move: function(event) {
// ensure swiping with one touch and not pinching
if ( event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if ( typeof isScrolling == 'undefined') {
isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0);
} else {
delta.x =
delta.x /
( (!index && delta.x > 0 // if first slide and sliding left
|| index == slides.length - 1 // or if last slide and sliding right
&& delta.x < 0 // and if sliding at all
) ?
( Math.abs(delta.x) / width + 1 ) // determine resistance level
: 1 ); // no resistance if false
// translate 1:1
translate(index-1, delta.x + slidePos[index-1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index+1, delta.x + slidePos[index+1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&& Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
|| Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds =
!index && delta.x > 0 // if first slide and slide amt is greater than 0
|| index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index-1), -width, 0);
move(circle(index+2), width, 0);
} else {
move(index-1, -width, 0);
}
move(index, slidePos[index]-width, speed);
move(circle(index+1), slidePos[circle(index+1)]-width, speed);
index = circle(index+1);
} else {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index+1), width, 0);
move(circle(index-2), -width, 0);
} else {
move(index+1, width, 0);
}
move(index, slidePos[index]+width, speed);
move(circle(index-1), slidePos[circle(index-1)]+width, speed);
index = circle(index-1);
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index-1), -width, speed);
move(index, 0, speed);
move(circle(index+1), width, speed);
} else {
move(index-1, -width, speed);
move(index, 0, speed);
move(index+1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
if(browser.touch) {
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
} else {
element.removeEventListener('mousemove', events, false)
element.removeEventListener('mouseup', events, false)
}
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// Public API
this.setup = function() {
setup();
};
this.slide = function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
};
this.prev = function() {
// cancel slideshow
stop();
prev();
};
this.next = function() {
// cancel slideshow
stop();
next();
};
this.stop = function() {
// cancel slideshow
stop();
};
this.getPos = function() {
// return current index position
return index;
};
this.getNumSlides = function() {
// return total number of slides
return length;
};
this.kill = function() {
// cancel slideshow
stop();
// reset element
element.style.width = '';
element.style.left = '';
// reset slides
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = '';
slide.style.left = '';
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
}
else {
window.onresize = null;
}
};
this.load = function() {
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) {
element.addEventListener('touchstart', events, false);
} else {
element.addEventListener('mousedown', events, false);
}
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function () { setup() }; // to play nice with old IE
}
}
}
});
})(ionic);
;
(function(ionic) {
'use strict';
ionic.views.TabBarItem = ionic.views.View.inherit({
initialize: function(el) {
this.el = el;
this._buildItem();
},
// Factory for creating an item from a given javascript object
create: function(itemData) {
var item = document.createElement('a');
item.className = 'tab-item';
// If there is an icon, add the icon element
if(itemData.icon) {
var icon = document.createElement('i');
icon.className = itemData.icon;
item.appendChild(icon);
}
item.appendChild(document.createTextNode(itemData.title));
return new ionic.views.TabBarItem(item);
},
_buildItem: function() {
var _this = this, child, children = Array.prototype.slice.call(this.el.children);
for(var i = 0, j = children.length; i < j; i++) {
child = children[i];
// Test if this is a "i" tag with icon in the class name
// TODO: This heuristic might not be sufficient
if(child.tagName.toLowerCase() == 'i' && /icon/.test(child.className)) {
this.icon = child.className;
break;
}
}
// Set the title to the text content of the tab.
this.title = this.el.textContent.trim();
this._tapHandler = function(e) {
_this.onTap && _this.onTap(e);
};
ionic.on('tap', this._tapHandler, this.el);
},
onTap: function(e) {
},
// Remove the event listeners from this object
destroy: function() {
ionic.off('tap', this._tapHandler, this.el);
},
getIcon: function() {
return this.icon;
},
getTitle: function() {
return this.title;
},
setSelected: function(isSelected) {
this.isSelected = isSelected;
if(isSelected) {
this.el.classList.add('active');
} else {
this.el.classList.remove('active');
}
}
});
ionic.views.TabBar = ionic.views.View.inherit({
initialize: function(opts) {
this.el = opts.el;
this.items = [];
this._buildItems();
},
// get all the items for the TabBar
getItems: function() {
return this.items;
},
// Add an item to the tab bar
addItem: function(item) {
// Create a new TabItem
var tabItem = ionic.views.TabBarItem.prototype.create(item);
this.appendItemElement(tabItem);
this.items.push(tabItem);
this._bindEventsOnItem(tabItem);
},
appendItemElement: function(item) {
if(!this.el) {
return;
}
this.el.appendChild(item.el);
},
// Remove an item from the tab bar
removeItem: function(index) {
var item = this.items[index];
if(!item) {
return;
}
item.onTap = undefined;
item.destroy();
},
_bindEventsOnItem: function(item) {
var _this = this;
if(!this._itemTapHandler) {
this._itemTapHandler = function(e) {
//_this.selectItem(this);
_this.trySelectItem(this);
};
}
item.onTap = this._itemTapHandler;
},
// Get the currently selected item
getSelectedItem: function() {
return this.selectedItem;
},
// Set the currently selected item by index
setSelectedItem: function(index) {
this.selectedItem = this.items[index];
// Deselect all
for(var i = 0, j = this.items.length; i < j; i += 1) {
this.items[i].setSelected(false);
}
// Select the new item
if(this.selectedItem) {
this.selectedItem.setSelected(true);
//this.onTabSelected && this.onTabSelected(this.selectedItem, index);
}
},
// Select the given item assuming we can find it in our
// item list.
selectItem: function(item) {
for(var i = 0, j = this.items.length; i < j; i += 1) {
if(this.items[i] == item) {
this.setSelectedItem(i);
return;
}
}
},
// Try to select a given item. This triggers an event such
// that the view controller managing this tab bar can decide
// whether to select the item or cancel it.
trySelectItem: function(item) {
for(var i = 0, j = this.items.length; i < j; i += 1) {
if(this.items[i] == item) {
this.tryTabSelect && this.tryTabSelect(i);
return;
}
}
},
// Build the initial items list from the given DOM node.
_buildItems: function() {
var item, items = Array.prototype.slice.call(this.el.children);
for(var i = 0, j = items.length; i < j; i += 1) {
item = new ionic.views.TabBarItem(items[i]);
this.items[i] = item;
this._bindEventsOnItem(item);
}
if(this.items.length > 0) {
this.selectedItem = this.items[0];
}
},
// Destroy this tab bar
destroy: function() {
for(var i = 0, j = this.items.length; i < j; i += 1) {
this.items[i].destroy();
}
this.items.length = 0;
}
});
})(window.ionic);
;
(function(ionic) {
'use strict';
ionic.views.Toggle = ionic.views.View.inherit({
initialize: function(opts) {
this.el = opts.el;
this.checkbox = opts.checkbox;
this.handle = opts.handle;
this.openPercent = -1;
},
tap: function(e) {
this.val( !this.checkbox.checked );
},
drag: function(e) {
var slidePageLeft = this.checkbox.offsetLeft + (this.handle.offsetWidth / 2);
var slidePageRight = this.checkbox.offsetLeft + this.checkbox.offsetWidth - (this.handle.offsetWidth / 2);
if(e.pageX >= slidePageRight - 4) {
this.val(true);
} else if(e.pageX <= slidePageLeft) {
this.val(false);
} else {
this.setOpenPercent( Math.round( (1 - ((slidePageRight - e.pageX) / (slidePageRight - slidePageLeft) )) * 100) );
}
},
setOpenPercent: function(openPercent) {
// only make a change if the new open percent has changed
if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) {
this.openPercent = openPercent;
if(openPercent === 0) {
this.val(false);
} else if(openPercent === 100) {
this.val(true);
} else {
var openPixel = Math.round( (openPercent / 100) * this.checkbox.offsetWidth - (this.handle.offsetWidth) );
openPixel = (openPixel < 1 ? 0 : openPixel);
this.handle.style.webkitTransform = 'translate3d(' + openPixel + 'px,0,0)';
}
}
},
release: function(e) {
this.val( this.openPercent >= 50 );
},
val: function(value) {
if(value === true || value === false) {
if(this.handle.style.webkitTransform !== "") {
this.handle.style.webkitTransform = "";
}
this.checkbox.checked = value;
this.openPercent = (value ? 100 : 0);
}
return this.checkbox.checked;
}
});
})(ionic);
;
(function(ionic) {
'use strict';
ionic.controllers.ViewController = function(options) {
this.initialize.apply(this, arguments);
};
ionic.controllers.ViewController.inherit = ionic.inherit;
ionic.extend(ionic.controllers.ViewController.prototype, {
initialize: function() {},
// Destroy this view controller, including all child views
destroy: function() {
}
});
})(window.ionic);
;
(function(ionic) {
'use strict';
/**
* The NavController makes it easy to have a stack
* of views or screens that can be pushed and popped
* for a dynamic navigation flow. This API is modelled
* off of the UINavigationController in iOS.
*
* The NavController can drive a nav bar to show a back button
* if the stack can be poppped to go back to the last view, and
* it will handle updating the title of the nav bar and processing animations.
*/
ionic.controllers.NavController = ionic.controllers.ViewController.inherit({
initialize: function(opts) {
var _this = this;
this.navBar = opts.navBar;
this.content = opts.content;
this.controllers = opts.controllers || [];
this._updateNavBar();
// TODO: Is this the best way?
this.navBar.shouldGoBack = function() {
_this.pop();
};
},
/**
* @return {array} the array of controllers on the stack.
*/
getControllers: function() {
return this.controllers;
},
/**
* @return {object} the controller at the top of the stack.
*/
getTopController: function() {
return this.controllers[this.controllers.length-1];
},
/**
* Push a new controller onto the navigation stack. The new controller
* will automatically become the new visible view.
*
* @param {object} controller the controller to push on the stack.
*/
push: function(controller) {
var last = this.controllers[this.controllers.length - 1];
this.controllers.push(controller);
// Indicate we are switching controllers
var shouldSwitch = this.switchingController && this.switchingController(controller) || true;
// Return if navigation cancelled
if(shouldSwitch === false)
return;
// Actually switch the active controllers
if(last) {
last.isVisible = false;
last.visibilityChanged && last.visibilityChanged('push');
}
// Grab the top controller on the stack
var next = this.controllers[this.controllers.length - 1];
next.isVisible = true;
// Trigger visibility change, but send 'first' if this is the first page
next.visibilityChanged && next.visibilityChanged(last ? 'push' : 'first');
this._updateNavBar();
return controller;
},
/**
* Pop the top controller off the stack, and show the last one. This is the
* "back" operation.
*
* @return {object} the last popped controller
*/
pop: function() {
var next, last;
// Make sure we keep one on the stack at all times
if(this.controllers.length < 2) {
return;
}
// Grab the controller behind the top one on the stack
last = this.controllers.pop();
if(last) {
last.isVisible = false;
last.visibilityChanged && last.visibilityChanged('pop');
}
// Remove the old one
//last && last.detach();
next = this.controllers[this.controllers.length - 1];
// TODO: No DOM stuff here
//this.content.el.appendChild(next.el);
next.isVisible = true;
next.visibilityChanged && next.visibilityChanged('pop');
// Switch to it (TODO: Animate or such things here)
this._updateNavBar();
return last;
},
/**
* Show the NavBar (if any)
*/
showNavBar: function() {
if(this.navBar) {
this.navBar.show();
}
},
/**
* Hide the NavBar (if any)
*/
hideNavBar: function() {
if(this.navBar) {
this.navBar.hide();
}
},
// Update the nav bar after a push or pop
_updateNavBar: function() {
if(!this.getTopController() || !this.navBar) {
return;
}
this.navBar.setTitle(this.getTopController().title);
if(this.controllers.length > 1) {
this.navBar.showBackButton(true);
} else {
this.navBar.showBackButton(false);
}
}
});
})(window.ionic);
;
(function(ionic) {
'use strict';
/**
* The SideMenuController is a controller with a left and/or right menu that
* can be slid out and toggled. Seen on many an app.
*
* The right or left menu can be disabled or not used at all, if desired.
*/
ionic.controllers.SideMenuController = ionic.controllers.ViewController.inherit({
initialize: function(options) {
var self = this;
this.left = options.left;
this.right = options.right;
this.content = options.content;
this.dragThresholdX = options.dragThresholdX || 10;
this._rightShowing = false;
this._leftShowing = false;
this._isDragging = false;
if(this.content) {
this.content.onDrag = function(e) {
self._handleDrag(e);
};
this.content.onEndDrag =function(e) {
self._endDrag(e);
};
}
},
/**
* Set the content view controller if not passed in the constructor options.
*
* @param {object} content
*/
setContent: function(content) {
var self = this;
this.content = content;
this.content.onDrag = function(e) {
self._handleDrag(e);
};
this.content.endDrag = function(e) {
self._endDrag(e);
};
},
/**
* Toggle the left menu to open 100%
*/
toggleLeft: function() {
this.content.enableAnimation();
var openAmount = this.getOpenAmount();
if(openAmount > 0) {
this.openPercentage(0);
} else {
this.openPercentage(100);
}
},
/**
* Toggle the right menu to open 100%
*/
toggleRight: function() {
this.content.enableAnimation();
var openAmount = this.getOpenAmount();
if(openAmount < 0) {
this.openPercentage(0);
} else {
this.openPercentage(-100);
}
},
/**
* Close all menus.
*/
close: function() {
this.openPercentage(0);
},
/**
* @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative)
*/
getOpenAmount: function() {
return this.content.getTranslateX() || 0;
},
/**
* @return {float} The ratio of open amount over menu width. For example, a
* menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative
* for right menu.
*/
getOpenRatio: function() {
var amount = this.getOpenAmount();
if(amount >= 0) {
return amount / this.left.width;
}
return amount / this.right.width;
},
isOpen: function() {
return this.getOpenRatio() == 1;
},
/**
* @return {float} The percentage of open amount over menu width. For example, a
* menu of width 100 open 50 pixels would be open 50%. Value is negative
* for right menu.
*/
getOpenPercentage: function() {
return this.getOpenRatio() * 100;
},
/**
* Open the menu with a given percentage amount.
* @param {float} percentage The percentage (positive or negative for left/right) to open the menu.
*/
openPercentage: function(percentage) {
var p = percentage / 100;
if(this.left && percentage >= 0) {
this.openAmount(this.left.width * p);
} else if(this.right && percentage < 0) {
var maxRight = this.right.width;
this.openAmount(this.right.width * p);
}
},
/**
* Open the menu the given pixel amount.
* @param {float} amount the pixel amount to open the menu. Positive value for left menu,
* negative value for right menu (only one menu will be visible at a time).
*/
openAmount: function(amount) {
var maxLeft = this.left && this.left.width || 0;
var maxRight = this.right && this.right.width || 0;
// Check if we can move to that side, depending if the left/right panel is enabled
if((!(this.left && this.left.isEnabled) && amount > 0) || (!(this.right && this.right.isEnabled) && amount < 0)) {
return;
}
if((this._leftShowing && amount > maxLeft) || (this._rightShowing && amount < -maxRight)) {
return;
}
this.content.setTranslateX(amount);
if(amount >= 0) {
this._leftShowing = true;
this._rightShowing = false;
// Push the z-index of the right menu down
this.right && this.right.pushDown && this.right.pushDown();
// Bring the z-index of the left menu up
this.left && this.left.bringUp && this.left.bringUp();
} else {
this._rightShowing = true;
this._leftShowing = false;
// Bring the z-index of the right menu up
this.right && this.right.bringUp && this.right.bringUp();
// Push the z-index of the left menu down
this.left && this.left.pushDown && this.left.pushDown();
}
},
/**
* Given an event object, find the final resting position of this side
* menu. For example, if the user "throws" the content to the right and
* releases the touch, the left menu should snap open (animated, of course).
*
* @param {Event} e the gesture event to use for snapping
*/
snapToRest: function(e) {
// We want to animate at the end of this
this.content.enableAnimation();
this._isDragging = false;
// Check how much the panel is open after the drag, and
// what the drag velocity is
var ratio = this.getOpenRatio();
if(ratio === 0)
return;
var velocityThreshold = 0.3;
var velocityX = e.gesture.velocityX;
var direction = e.gesture.direction;
// Less than half, going left
//if(ratio > 0 && ratio < 0.5 && direction == 'left' && velocityX < velocityThreshold) {
//this.openPercentage(0);
//}
// Going right, less than half, too slow (snap back)
if(ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
this.openPercentage(0);
}
// Going left, more than half, too slow (snap back)
else if(ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) {
this.openPercentage(100);
}
// Going left, less than half, too slow (snap back)
else if(ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) {
this.openPercentage(0);
}
// Going right, more than half, too slow (snap back)
else if(ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
this.openPercentage(-100);
}
// Going right, more than half, or quickly (snap open)
else if(direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) {
this.openPercentage(100);
}
// Going left, more than half, or quickly (span open)
else if(direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) {
this.openPercentage(-100);
}
// Snap back for safety
else {
this.openPercentage(0);
}
},
// End a drag with the given event
_endDrag: function(e) {
if(this._isDragging) {
this.snapToRest(e);
}
this._startX = null;
this._lastX = null;
this._offsetX = null;
},
// Handle a drag event
_handleDrag: function(e) {
// If we don't have start coords, grab and store them
if(!this._startX) {
this._startX = e.gesture.touches[0].pageX;
this._lastX = this._startX;
} else {
// Grab the current tap coords
this._lastX = e.gesture.touches[0].pageX;
}
// Calculate difference from the tap points
if(!this._isDragging && Math.abs(this._lastX - this._startX) > this.dragThresholdX) {
// if the difference is greater than threshold, start dragging using the current
// point as the starting point
this._startX = this._lastX;
this._isDragging = true;
// Initialize dragging
this.content.disableAnimation();
this._offsetX = this.getOpenAmount();
}
if(this._isDragging) {
this.openAmount(this._offsetX + (this._lastX - this._startX));
}
}
});
})(ionic);
;
(function(ionic) {
'use strict';
/**
* The TabBarController handles a set of view controllers powered by a tab strip
* at the bottom (or possibly top) of a screen.
*
* The API here is somewhat modelled off of UITabController in the sense that the
* controllers actually define what the tab will look like (title, icon, etc.).
*
* Tabs shouldn't be interacted with through your own code. Instead, use the controller
* methods which will power the tab bar.
*/
ionic.controllers.TabBarController = ionic.controllers.ViewController.inherit({
initialize: function(options) {
this.tabBar = options.tabBar;
this._bindEvents();
this.controllers = [];
var controllers = options.controllers || [];
for(var i = 0; i < controllers.length; i++) {
this.addController(controllers[i]);
}
// Bind or set our tabWillChange callback
this.controllerWillChange = options.controllerWillChange || function(controller) {};
this.controllerChanged = options.controllerChanged || function(controller) {};
// Try to select the first controller if we have one
this.setSelectedController(0);
},
// Start listening for events on our tab bar
_bindEvents: function() {
var _this = this;
this.tabBar.tryTabSelect = function(index) {
_this.setSelectedController(index);
};
},
selectController: function(index) {
var shouldChange = true;
// Check if we should switch to this tab. This lets the app
// cancel tab switches if the context isn't right, for example.
if(this.controllerWillChange) {
if(this.controllerWillChange(this.controllers[index], index) === false) {
shouldChange = false;
}
}
if(shouldChange) {
this.setSelectedController(index);
}
},
// Force the selection of a controller at the given index
setSelectedController: function(index) {
if(index >= this.controllers.length) {
return;
}
var lastController = this.selectedController;
var lastIndex = this.selectedIndex;
this.selectedController = this.controllers[index];
this.selectedIndex = index;
this._showController(index);
this.tabBar.setSelectedItem(index);
this.controllerChanged && this.controllerChanged(lastController, lastIndex, this.selectedController, this.selectedIndex);
},
_showController: function(index) {
var c;
for(var i = 0, j = this.controllers.length; i < j; i ++) {
c = this.controllers[i];
//c.detach && c.detach();
c.isVisible = false;
c.visibilityChanged && c.visibilityChanged();
}
c = this.controllers[index];
//c.attach && c.attach();
c.isVisible = true;
c.visibilityChanged && c.visibilityChanged();
},
_clearSelected: function() {
this.selectedController = null;
this.selectedIndex = -1;
},
// Return the tab at the given index
getController: function(index) {
return this.controllers[index];
},
// Return the current tab list
getControllers: function() {
return this.controllers;
},
// Get the currently selected controller
getSelectedController: function() {
return this.selectedController;
},
// Get the index of the currently selected controller
getSelectedControllerIndex: function() {
return this.selectedIndex;
},
// Add a tab
addController: function(controller) {
this.controllers.push(controller);
this.tabBar.addItem({
title: controller.title,
icon: controller.icon
});
// If we don't have a selected controller yet, select the first one.
if(!this.selectedController) {
this.setSelectedController(0);
}
},
// Set the tabs and select the first
setControllers: function(controllers) {
this.controllers = controllers;
this._clearSelected();
this.selectController(0);
},
});
})(window.ionic);
|
ajax/libs/riot/2.3.17/riot+compiler.js | dlueth/cdnjs | /* Riot v2.3.17, @license MIT */
;(function(window, undefined) {
'use strict';
var riot = { version: 'v2.3.17', settings: {} },
// be aware, internal usage
// ATTENTION: prefix the global dynamic variables with `__`
// counter to give a unique id to all the Tag instances
__uid = 0,
// tags instances cache
__virtualDom = [],
// tags implementation cache
__tagImpl = {},
/**
* Const
*/
GLOBAL_MIXIN = '__global_mixin',
// riot specific prefixes
RIOT_PREFIX = 'riot-',
RIOT_TAG = RIOT_PREFIX + 'tag',
RIOT_TAG_IS = 'data-is',
// for typeof == '' comparisons
T_STRING = 'string',
T_OBJECT = 'object',
T_UNDEF = 'undefined',
T_BOOL = 'boolean',
T_FUNCTION = 'function',
// special native tags that cannot be treated like the others
SPECIAL_TAGS_REGEX = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?|opt(?:ion|group))$/,
RESERVED_WORDS_BLACKLIST = ['_item', '_id', '_parent', 'update', 'root', 'mount', 'unmount', 'mixin', 'isMounted', 'isLoop', 'tags', 'parent', 'opts', 'trigger', 'on', 'off', 'one'],
// version# for IE 8-11, 0 for others
IE_VERSION = (window && window.document || {}).documentMode | 0
/* istanbul ignore next */
riot.observable = function(el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {}
/**
* Private variables and methods
*/
var callbacks = {},
slice = Array.prototype.slice,
onEachEvent = function(e, fn) { e.replace(/\S+/g, fn) }
// extend the object adding the observable methods
Object.defineProperties(el, {
/**
* Listen to the given space separated list of `events` and execute the `callback` each time an event is triggered.
* @param { String } events - events ids
* @param { Function } fn - callback function
* @returns { Object } el
*/
on: {
value: function(events, fn) {
if (typeof fn != 'function') return el
onEachEvent(events, function(name, pos) {
(callbacks[name] = callbacks[name] || []).push(fn)
fn.typed = pos > 0
})
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Removes the given space separated list of `events` listeners
* @param { String } events - events ids
* @param { Function } fn - callback function
* @returns { Object } el
*/
off: {
value: function(events, fn) {
if (events == '*' && !fn) callbacks = {}
else {
onEachEvent(events, function(name) {
if (fn) {
var arr = callbacks[name]
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) arr.splice(i--, 1)
}
} else delete callbacks[name]
})
}
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Listen to the given space separated list of `events` and execute the `callback` at most once
* @param { String } events - events ids
* @param { Function } fn - callback function
* @returns { Object } el
*/
one: {
value: function(events, fn) {
function on() {
el.off(events, on)
fn.apply(el, arguments)
}
return el.on(events, on)
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Execute all callback functions that listen to the given space separated list of `events`
* @param { String } events - events ids
* @returns { Object } el
*/
trigger: {
value: function(events) {
// getting the arguments
var arglen = arguments.length - 1,
args = new Array(arglen),
fns
for (var i = 0; i < arglen; i++) {
args[i] = arguments[i + 1] // skip first argument
}
onEachEvent(events, function(name) {
fns = slice.call(callbacks[name] || [], 0)
for (var i = 0, fn; fn = fns[i]; ++i) {
if (fn.busy) return
fn.busy = 1
fn.apply(el, fn.typed ? [name].concat(args) : args)
if (fns[i] !== fn) { i-- }
fn.busy = 0
}
if (callbacks['*'] && name != '*')
el.trigger.apply(el, ['*', name].concat(args))
})
return el
},
enumerable: false,
writable: false,
configurable: false
}
})
return el
}
/* istanbul ignore next */
;(function(riot) {
/**
* Simple client-side router
* @module riot-route
*/
var RE_ORIGIN = /^.+?\/+[^\/]+/,
EVENT_LISTENER = 'EventListener',
REMOVE_EVENT_LISTENER = 'remove' + EVENT_LISTENER,
ADD_EVENT_LISTENER = 'add' + EVENT_LISTENER,
HAS_ATTRIBUTE = 'hasAttribute',
REPLACE = 'replace',
POPSTATE = 'popstate',
HASHCHANGE = 'hashchange',
TRIGGER = 'trigger',
MAX_EMIT_STACK_LEVEL = 3,
win = typeof window != 'undefined' && window,
doc = typeof document != 'undefined' && document,
hist = win && history,
loc = win && (hist.location || win.location), // see html5-history-api
prot = Router.prototype, // to minify more
clickEvent = doc && doc.ontouchstart ? 'touchstart' : 'click',
started = false,
central = riot.observable(),
routeFound = false,
debouncedEmit,
base, current, parser, secondParser, emitStack = [], emitStackLevel = 0
/**
* Default parser. You can replace it via router.parser method.
* @param {string} path - current path (normalized)
* @returns {array} array
*/
function DEFAULT_PARSER(path) {
return path.split(/[/?#]/)
}
/**
* Default parser (second). You can replace it via router.parser method.
* @param {string} path - current path (normalized)
* @param {string} filter - filter string (normalized)
* @returns {array} array
*/
function DEFAULT_SECOND_PARSER(path, filter) {
var re = new RegExp('^' + filter[REPLACE](/\*/g, '([^/?#]+?)')[REPLACE](/\.\./, '.*') + '$'),
args = path.match(re)
if (args) return args.slice(1)
}
/**
* Simple/cheap debounce implementation
* @param {function} fn - callback
* @param {number} delay - delay in seconds
* @returns {function} debounced function
*/
function debounce(fn, delay) {
var t
return function () {
clearTimeout(t)
t = setTimeout(fn, delay)
}
}
/**
* Set the window listeners to trigger the routes
* @param {boolean} autoExec - see route.start
*/
function start(autoExec) {
debouncedEmit = debounce(emit, 1)
win[ADD_EVENT_LISTENER](POPSTATE, debouncedEmit)
win[ADD_EVENT_LISTENER](HASHCHANGE, debouncedEmit)
doc[ADD_EVENT_LISTENER](clickEvent, click)
if (autoExec) emit(true)
}
/**
* Router class
*/
function Router() {
this.$ = []
riot.observable(this) // make it observable
central.on('stop', this.s.bind(this))
central.on('emit', this.e.bind(this))
}
function normalize(path) {
return path[REPLACE](/^\/|\/$/, '')
}
function isString(str) {
return typeof str == 'string'
}
/**
* Get the part after domain name
* @param {string} href - fullpath
* @returns {string} path from root
*/
function getPathFromRoot(href) {
return (href || loc.href || '')[REPLACE](RE_ORIGIN, '')
}
/**
* Get the part after base
* @param {string} href - fullpath
* @returns {string} path from base
*/
function getPathFromBase(href) {
return base[0] == '#'
? (href || loc.href || '').split(base)[1] || ''
: getPathFromRoot(href)[REPLACE](base, '')
}
function emit(force) {
// the stack is needed for redirections
var isRoot = emitStackLevel == 0
if (MAX_EMIT_STACK_LEVEL <= emitStackLevel) return
emitStackLevel++
emitStack.push(function() {
var path = getPathFromBase()
if (force || path != current) {
central[TRIGGER]('emit', path)
current = path
}
})
if (isRoot) {
while (emitStack.length) {
emitStack[0]()
emitStack.shift()
}
emitStackLevel = 0
}
}
function click(e) {
if (
e.which != 1 // not left click
|| e.metaKey || e.ctrlKey || e.shiftKey // or meta keys
|| e.defaultPrevented // or default prevented
) return
var el = e.target
while (el && el.nodeName != 'A') el = el.parentNode
if (
!el || el.nodeName != 'A' // not A tag
|| el[HAS_ATTRIBUTE]('download') // has download attr
|| !el[HAS_ATTRIBUTE]('href') // has no href attr
|| el.target && el.target != '_self' // another window or frame
|| el.href.indexOf(loc.href.match(RE_ORIGIN)[0]) == -1 // cross origin
) return
if (el.href != loc.href) {
if (
el.href.split('#')[0] == loc.href.split('#')[0] // internal jump
|| base != '#' && getPathFromRoot(el.href).indexOf(base) !== 0 // outside of base
|| !go(getPathFromBase(el.href), el.title || doc.title) // route not found
) return
}
e.preventDefault()
}
/**
* Go to the path
* @param {string} path - destination path
* @param {string} title - page title
* @param {boolean} shouldReplace - use replaceState or pushState
* @returns {boolean} - route not found flag
*/
function go(path, title, shouldReplace) {
if (hist) { // if a browser
path = base + normalize(path)
title = title || doc.title
// browsers ignores the second parameter `title`
shouldReplace
? hist.replaceState(null, title, path)
: hist.pushState(null, title, path)
// so we need to set it manually
doc.title = title
routeFound = false
emit()
return routeFound
}
// Server-side usage: directly execute handlers for the path
return central[TRIGGER]('emit', getPathFromBase(path))
}
/**
* Go to path or set action
* a single string: go there
* two strings: go there with setting a title
* two strings and boolean: replace history with setting a title
* a single function: set an action on the default route
* a string/RegExp and a function: set an action on the route
* @param {(string|function)} first - path / action / filter
* @param {(string|RegExp|function)} second - title / action
* @param {boolean} third - replace flag
*/
prot.m = function(first, second, third) {
if (isString(first) && (!second || isString(second))) go(first, second, third || false)
else if (second) this.r(first, second)
else this.r('@', first)
}
/**
* Stop routing
*/
prot.s = function() {
this.off('*')
this.$ = []
}
/**
* Emit
* @param {string} path - path
*/
prot.e = function(path) {
this.$.concat('@').some(function(filter) {
var args = (filter == '@' ? parser : secondParser)(normalize(path), normalize(filter))
if (typeof args != 'undefined') {
this[TRIGGER].apply(null, [filter].concat(args))
return routeFound = true // exit from loop
}
}, this)
}
/**
* Register route
* @param {string} filter - filter for matching to url
* @param {function} action - action to register
*/
prot.r = function(filter, action) {
if (filter != '@') {
filter = '/' + normalize(filter)
this.$.push(filter)
}
this.on(filter, action)
}
var mainRouter = new Router()
var route = mainRouter.m.bind(mainRouter)
/**
* Create a sub router
* @returns {function} the method of a new Router object
*/
route.create = function() {
var newSubRouter = new Router()
// stop only this sub-router
newSubRouter.m.stop = newSubRouter.s.bind(newSubRouter)
// return sub-router's main method
return newSubRouter.m.bind(newSubRouter)
}
/**
* Set the base of url
* @param {(str|RegExp)} arg - a new base or '#' or '#!'
*/
route.base = function(arg) {
base = arg || '#'
current = getPathFromBase() // recalculate current path
}
/** Exec routing right now **/
route.exec = function() {
emit(true)
}
/**
* Replace the default router to yours
* @param {function} fn - your parser function
* @param {function} fn2 - your secondParser function
*/
route.parser = function(fn, fn2) {
if (!fn && !fn2) {
// reset parser for testing...
parser = DEFAULT_PARSER
secondParser = DEFAULT_SECOND_PARSER
}
if (fn) parser = fn
if (fn2) secondParser = fn2
}
/**
* Helper function to get url query as an object
* @returns {object} parsed query
*/
route.query = function() {
var q = {}
var href = loc.href || current
href[REPLACE](/[?&](.+?)=([^&]*)/g, function(_, k, v) { q[k] = v })
return q
}
/** Stop routing **/
route.stop = function () {
if (started) {
if (win) {
win[REMOVE_EVENT_LISTENER](POPSTATE, debouncedEmit)
win[REMOVE_EVENT_LISTENER](HASHCHANGE, debouncedEmit)
doc[REMOVE_EVENT_LISTENER](clickEvent, click)
}
central[TRIGGER]('stop')
started = false
}
}
/**
* Start routing
* @param {boolean} autoExec - automatically exec after starting if true
*/
route.start = function (autoExec) {
if (!started) {
if (win) {
if (document.readyState == 'complete') start(autoExec)
// the timeout is needed to solve
// a weird safari bug https://github.com/riot/route/issues/33
else win[ADD_EVENT_LISTENER]('load', function() {
setTimeout(function() { start(autoExec) }, 1)
})
}
started = true
}
}
/** Prepare the router **/
route.base()
route.parser()
riot.route = route
})(riot)
/* istanbul ignore next */
/**
* The riot template engine
* @version v2.3.21
*/
/**
* riot.util.brackets
*
* - `brackets ` - Returns a string or regex based on its parameter
* - `brackets.set` - Change the current riot brackets
*
* @module
*/
var brackets = (function (UNDEF) {
var
REGLOB = 'g',
R_MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g,
R_STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'/g,
S_QBLOCKS = R_STRINGS.source + '|' +
/(?:\breturn\s+|(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/]))/.source + '|' +
/\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source,
FINDBRACES = {
'(': RegExp('([()])|' + S_QBLOCKS, REGLOB),
'[': RegExp('([[\\]])|' + S_QBLOCKS, REGLOB),
'{': RegExp('([{}])|' + S_QBLOCKS, REGLOB)
},
DEFAULT = '{ }'
var _pairs = [
'{', '}',
'{', '}',
/{[^}]*}/,
/\\([{}])/g,
/\\({)|{/g,
RegExp('\\\\(})|([[({])|(})|' + S_QBLOCKS, REGLOB),
DEFAULT,
/^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S.*)\s*}/,
/(^|[^\\]){=[\S\s]*?}/
]
var
cachedBrackets = UNDEF,
_regex,
_cache = [],
_settings
function _loopback (re) { return re }
function _rewrite (re, bp) {
if (!bp) bp = _cache
return new RegExp(
re.source.replace(/{/g, bp[2]).replace(/}/g, bp[3]), re.global ? REGLOB : ''
)
}
function _create (pair) {
if (pair === DEFAULT) return _pairs
var arr = pair.split(' ')
if (arr.length !== 2 || /[\x00-\x1F<>a-zA-Z0-9'",;\\]/.test(pair)) {
throw new Error('Unsupported brackets "' + pair + '"')
}
arr = arr.concat(pair.replace(/(?=[[\]()*+?.^$|])/g, '\\').split(' '))
arr[4] = _rewrite(arr[1].length > 1 ? /{[\S\s]*?}/ : _pairs[4], arr)
arr[5] = _rewrite(pair.length > 3 ? /\\({|})/g : _pairs[5], arr)
arr[6] = _rewrite(_pairs[6], arr)
arr[7] = RegExp('\\\\(' + arr[3] + ')|([[({])|(' + arr[3] + ')|' + S_QBLOCKS, REGLOB)
arr[8] = pair
return arr
}
function _brackets (reOrIdx) {
return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx]
}
_brackets.split = function split (str, tmpl, _bp) {
// istanbul ignore next: _bp is for the compiler
if (!_bp) _bp = _cache
var
parts = [],
match,
isexpr,
start,
pos,
re = _bp[6]
isexpr = start = re.lastIndex = 0
while (match = re.exec(str)) {
pos = match.index
if (isexpr) {
if (match[2]) {
re.lastIndex = skipBraces(str, match[2], re.lastIndex)
continue
}
if (!match[3])
continue
}
if (!match[1]) {
unescapeStr(str.slice(start, pos))
start = re.lastIndex
re = _bp[6 + (isexpr ^= 1)]
re.lastIndex = start
}
}
if (str && start < str.length) {
unescapeStr(str.slice(start))
}
return parts
function unescapeStr (s) {
if (tmpl || isexpr)
parts.push(s && s.replace(_bp[5], '$1'))
else
parts.push(s)
}
function skipBraces (s, ch, ix) {
var
match,
recch = FINDBRACES[ch]
recch.lastIndex = ix
ix = 1
while (match = recch.exec(s)) {
if (match[1] &&
!(match[1] === ch ? ++ix : --ix)) break
}
return ix ? s.length : recch.lastIndex
}
}
_brackets.hasExpr = function hasExpr (str) {
return _cache[4].test(str)
}
_brackets.loopKeys = function loopKeys (expr) {
var m = expr.match(_cache[9])
return m
? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] }
: { val: expr.trim() }
}
_brackets.hasRaw = function (src) {
return _cache[10].test(src)
}
_brackets.array = function array (pair) {
return pair ? _create(pair) : _cache
}
function _reset (pair) {
if ((pair || (pair = DEFAULT)) !== _cache[8]) {
_cache = _create(pair)
_regex = pair === DEFAULT ? _loopback : _rewrite
_cache[9] = _regex(_pairs[9])
_cache[10] = _regex(_pairs[10])
}
cachedBrackets = pair
}
function _setSettings (o) {
var b
o = o || {}
b = o.brackets
Object.defineProperty(o, 'brackets', {
set: _reset,
get: function () { return cachedBrackets },
enumerable: true
})
_settings = o
_reset(b)
}
Object.defineProperty(_brackets, 'settings', {
set: _setSettings,
get: function () { return _settings }
})
/* istanbul ignore next: in the browser riot is always in the scope */
_brackets.settings = typeof riot !== 'undefined' && riot.settings || {}
_brackets.set = _reset
_brackets.R_STRINGS = R_STRINGS
_brackets.R_MLCOMMS = R_MLCOMMS
_brackets.S_QBLOCKS = S_QBLOCKS
return _brackets
})()
/**
* @module tmpl
*
* tmpl - Root function, returns the template value, render with data
* tmpl.hasExpr - Test the existence of a expression inside a string
* tmpl.loopKeys - Get the keys for an 'each' loop (used by `_each`)
*/
var tmpl = (function () {
var _cache = {}
function _tmpl (str, data) {
if (!str) return str
return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr)
}
_tmpl.haveRaw = brackets.hasRaw
_tmpl.hasExpr = brackets.hasExpr
_tmpl.loopKeys = brackets.loopKeys
_tmpl.errorHandler = null
function _logErr (err, ctx) {
if (_tmpl.errorHandler) {
err.riotData = {
tagName: ctx && ctx.root && ctx.root.tagName,
_riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase
}
_tmpl.errorHandler(err)
}
}
function _create (str) {
var expr = _getTmpl(str)
if (expr.slice(0, 11) !== 'try{return ') expr = 'return ' + expr
return new Function('E', expr + ';')
}
var
RE_QBLOCK = RegExp(brackets.S_QBLOCKS, 'g'),
RE_QBMARK = /\x01(\d+)~/g
function _getTmpl (str) {
var
qstr = [],
expr,
parts = brackets.split(str.replace(/\u2057/g, '"'), 1)
if (parts.length > 2 || parts[0]) {
var i, j, list = []
for (i = j = 0; i < parts.length; ++i) {
expr = parts[i]
if (expr && (expr = i & 1 ?
_parseExpr(expr, 1, qstr) :
'"' + expr
.replace(/\\/g, '\\\\')
.replace(/\r\n?|\n/g, '\\n')
.replace(/"/g, '\\"') +
'"'
)) list[j++] = expr
}
expr = j < 2 ? list[0] :
'[' + list.join(',') + '].join("")'
} else {
expr = _parseExpr(parts[1], 0, qstr)
}
if (qstr[0])
expr = expr.replace(RE_QBMARK, function (_, pos) {
return qstr[pos]
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
})
return expr
}
var
RE_BREND = {
'(': /[()]/g,
'[': /[[\]]/g,
'{': /[{}]/g
},
CS_IDENT = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\x01(\d+)~):/
function _parseExpr (expr, asText, qstr) {
if (expr[0] === '=') expr = expr.slice(1)
expr = expr
.replace(RE_QBLOCK, function (s, div) {
return s.length > 2 && !div ? '\x01' + (qstr.push(s) - 1) + '~' : s
})
.replace(/\s+/g, ' ').trim()
.replace(/\ ?([[\({},?\.:])\ ?/g, '$1')
if (expr) {
var
list = [],
cnt = 0,
match
while (expr &&
(match = expr.match(CS_IDENT)) &&
!match.index
) {
var
key,
jsb,
re = /,|([[{(])|$/g
expr = RegExp.rightContext
key = match[2] ? qstr[match[2]].slice(1, -1).trim().replace(/\s+/g, ' ') : match[1]
while (jsb = (match = re.exec(expr))[1]) skipBraces(jsb, re)
jsb = expr.slice(0, match.index)
expr = RegExp.rightContext
list[cnt++] = _wrapExpr(jsb, 1, key)
}
expr = !cnt ? _wrapExpr(expr, asText) :
cnt > 1 ? '[' + list.join(',') + '].join(" ").trim()' : list[0]
}
return expr
function skipBraces (ch, re) {
var
mm,
lv = 1,
ir = RE_BREND[ch]
ir.lastIndex = re.lastIndex
while (mm = ir.exec(expr)) {
if (mm[0] === ch) ++lv
else if (!--lv) break
}
re.lastIndex = lv ? expr.length : ir.lastIndex
}
}
// istanbul ignore next: not both
var
JS_CONTEXT = '"in this?this:' + (typeof window !== 'object' ? 'global' : 'window') + ').',
JS_VARNAME = /[,{][$\w]+:|(^ *|[^$\w\.])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g,
JS_NOPROPS = /^(?=(\.[$\w]+))\1(?:[^.[(]|$)/
function _wrapExpr (expr, asText, key) {
var tb
expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) {
if (mvar) {
pos = tb ? 0 : pos + match.length
if (mvar !== 'this' && mvar !== 'global' && mvar !== 'window') {
match = p + '("' + mvar + JS_CONTEXT + mvar
if (pos) tb = (s = s[pos]) === '.' || s === '(' || s === '['
} else if (pos) {
tb = !JS_NOPROPS.test(s.slice(pos))
}
}
return match
})
if (tb) {
expr = 'try{return ' + expr + '}catch(e){E(e,this)}'
}
if (key) {
expr = (tb ?
'function(){' + expr + '}.call(this)' : '(' + expr + ')'
) + '?"' + key + '":""'
} else if (asText) {
expr = 'function(v){' + (tb ?
expr.replace('return ', 'v=') : 'v=(' + expr + ')'
) + ';return v||v===0?v:""}.call(this)'
}
return expr
}
// istanbul ignore next: compatibility fix for beta versions
_tmpl.parse = function (s) { return s }
_tmpl.version = brackets.version = 'v2.3.21'
return _tmpl
})()
/*
lib/browser/tag/mkdom.js
Includes hacks needed for the Internet Explorer version 9 and below
See: http://kangax.github.io/compat-table/es5/#ie8
http://codeplanet.io/dropping-ie8/
*/
var mkdom = (function _mkdom() {
var
reHasYield = /<yield\b/i,
reYieldAll = /<yield\s*(?:\/>|>([\S\s]*?)<\/yield\s*>)/ig,
reYieldSrc = /<yield\s+to=['"]([^'">]*)['"]\s*>([\S\s]*?)<\/yield\s*>/ig,
reYieldDest = /<yield\s+from=['"]?([-\w]+)['"]?\s*(?:\/>|>([\S\s]*?)<\/yield\s*>)/ig
var
rootEls = { tr: 'tbody', th: 'tr', td: 'tr', col: 'colgroup' },
tblTags = IE_VERSION && IE_VERSION < 10
? SPECIAL_TAGS_REGEX : /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?)$/
/**
* Creates a DOM element to wrap the given content. Normally an `DIV`, but can be
* also a `TABLE`, `SELECT`, `TBODY`, `TR`, or `COLGROUP` element.
*
* @param {string} templ - The template coming from the custom tag definition
* @param {string} [html] - HTML content that comes from the DOM element where you
* will mount the tag, mostly the original tag in the page
* @returns {HTMLElement} DOM element with _templ_ merged through `YIELD` with the _html_.
*/
function _mkdom(templ, html) {
var
match = templ && templ.match(/^\s*<([-\w]+)/),
tagName = match && match[1].toLowerCase(),
el = mkEl('div')
// replace all the yield tags with the tag inner html
templ = replaceYield(templ, html)
/* istanbul ignore next */
if (tblTags.test(tagName))
el = specialTags(el, templ, tagName)
else
el.innerHTML = templ
el.stub = true
return el
}
/*
Creates the root element for table or select child elements:
tr/th/td/thead/tfoot/tbody/caption/col/colgroup/option/optgroup
*/
function specialTags(el, templ, tagName) {
var
select = tagName[0] === 'o',
parent = select ? 'select>' : 'table>'
// trim() is important here, this ensures we don't have artifacts,
// so we can check if we have only one element inside the parent
el.innerHTML = '<' + parent + templ.trim() + '</' + parent
parent = el.firstChild
// returns the immediate parent if tr/th/td/col is the only element, if not
// returns the whole tree, as this can include additional elements
if (select) {
parent.selectedIndex = -1 // for IE9, compatible w/current riot behavior
} else {
// avoids insertion of cointainer inside container (ex: tbody inside tbody)
var tname = rootEls[tagName]
if (tname && parent.childElementCount === 1) parent = $(tname, parent)
}
return parent
}
/*
Replace the yield tag from any tag template with the innerHTML of the
original tag in the page
*/
function replaceYield(templ, html) {
// do nothing if no yield
if (!reHasYield.test(templ)) return templ
// be careful with #1343 - string on the source having `$1`
var src = {}
html = html && html.replace(reYieldSrc, function (_, ref, text) {
src[ref] = src[ref] || text // preserve first definition
return ''
}).trim()
return templ
.replace(reYieldDest, function (_, ref, def) { // yield with from - to attrs
return src[ref] || def || ''
})
.replace(reYieldAll, function (_, def) { // yield without any "from"
return html || def || ''
})
}
return _mkdom
})()
/**
* Convert the item looped into an object used to extend the child tag properties
* @param { Object } expr - object containing the keys used to extend the children tags
* @param { * } key - value to assign to the new object returned
* @param { * } val - value containing the position of the item in the array
* @returns { Object } - new object containing the values of the original item
*
* The variables 'key' and 'val' are arbitrary.
* They depend on the collection type looped (Array, Object)
* and on the expression used on the each tag
*
*/
function mkitem(expr, key, val) {
var item = {}
item[expr.key] = key
if (expr.pos) item[expr.pos] = val
return item
}
/**
* Unmount the redundant tags
* @param { Array } items - array containing the current items to loop
* @param { Array } tags - array containing all the children tags
*/
function unmountRedundant(items, tags) {
var i = tags.length,
j = items.length,
t
while (i > j) {
t = tags[--i]
tags.splice(i, 1)
t.unmount()
}
}
/**
* Move the nested custom tags in non custom loop tags
* @param { Object } child - non custom loop tag
* @param { Number } i - current position of the loop tag
*/
function moveNestedTags(child, i) {
Object.keys(child.tags).forEach(function(tagName) {
var tag = child.tags[tagName]
if (isArray(tag))
each(tag, function (t) {
moveChildTag(t, tagName, i)
})
else
moveChildTag(tag, tagName, i)
})
}
/**
* Adds the elements for a virtual tag
* @param { Tag } tag - the tag whose root's children will be inserted or appended
* @param { Node } src - the node that will do the inserting or appending
* @param { Tag } target - only if inserting, insert before this tag's first child
*/
function addVirtual(tag, src, target) {
var el = tag._root, sib
tag._virts = []
while (el) {
sib = el.nextSibling
if (target)
src.insertBefore(el, target._root)
else
src.appendChild(el)
tag._virts.push(el) // hold for unmounting
el = sib
}
}
/**
* Move virtual tag and all child nodes
* @param { Tag } tag - first child reference used to start move
* @param { Node } src - the node that will do the inserting
* @param { Tag } target - insert before this tag's first child
* @param { Number } len - how many child nodes to move
*/
function moveVirtual(tag, src, target, len) {
var el = tag._root, sib, i = 0
for (; i < len; i++) {
sib = el.nextSibling
src.insertBefore(el, target._root)
el = sib
}
}
/**
* Manage tags having the 'each'
* @param { Object } dom - DOM node we need to loop
* @param { Tag } parent - parent tag instance where the dom node is contained
* @param { String } expr - string contained in the 'each' attribute
*/
function _each(dom, parent, expr) {
// remove the each property from the original tag
remAttr(dom, 'each')
var mustReorder = typeof getAttr(dom, 'no-reorder') !== T_STRING || remAttr(dom, 'no-reorder'),
tagName = getTagName(dom),
impl = __tagImpl[tagName] || { tmpl: dom.outerHTML },
useRoot = SPECIAL_TAGS_REGEX.test(tagName),
root = dom.parentNode,
ref = document.createTextNode(''),
child = getTag(dom),
isOption = tagName.toLowerCase() === 'option', // the option tags must be treated differently
tags = [],
oldItems = [],
hasKeys,
isVirtual = dom.tagName == 'VIRTUAL'
// parse the each expression
expr = tmpl.loopKeys(expr)
// insert a marked where the loop tags will be injected
root.insertBefore(ref, dom)
// clean template code
parent.one('before-mount', function () {
// remove the original DOM node
dom.parentNode.removeChild(dom)
if (root.stub) root = parent.root
}).on('update', function () {
// get the new items collection
var items = tmpl(expr.val, parent),
// create a fragment to hold the new DOM nodes to inject in the parent tag
frag = document.createDocumentFragment()
// object loop. any changes cause full redraw
if (!isArray(items)) {
hasKeys = items || false
items = hasKeys ?
Object.keys(items).map(function (key) {
return mkitem(expr, key, items[key])
}) : []
}
// loop all the new items
var i = 0,
itemsLength = items.length
for (; i < itemsLength; i++) {
// reorder only if the items are objects
var
item = items[i],
_mustReorder = mustReorder && item instanceof Object && !hasKeys,
oldPos = oldItems.indexOf(item),
pos = ~oldPos && _mustReorder ? oldPos : i,
// does a tag exist in this position?
tag = tags[pos]
item = !hasKeys && expr.key ? mkitem(expr, item, i) : item
// new tag
if (
!_mustReorder && !tag // with no-reorder we just update the old tags
||
_mustReorder && !~oldPos || !tag // by default we always try to reorder the DOM elements
) {
tag = new Tag(impl, {
parent: parent,
isLoop: true,
hasImpl: !!__tagImpl[tagName],
root: useRoot ? root : dom.cloneNode(),
item: item
}, dom.innerHTML)
tag.mount()
if (isVirtual) tag._root = tag.root.firstChild // save reference for further moves or inserts
// this tag must be appended
if (i == tags.length || !tags[i]) { // fix 1581
if (isVirtual)
addVirtual(tag, frag)
else frag.appendChild(tag.root)
}
// this tag must be insert
else {
if (isVirtual)
addVirtual(tag, root, tags[i])
else root.insertBefore(tag.root, tags[i].root) // #1374 some browsers reset selected here
oldItems.splice(i, 0, item)
}
tags.splice(i, 0, tag)
pos = i // handled here so no move
} else tag.update(item, true)
// reorder the tag if it's not located in its previous position
if (
pos !== i && _mustReorder &&
tags[i] // fix 1581 unable to reproduce it in a test!
) {
// update the DOM
if (isVirtual)
moveVirtual(tag, root, tags[i], dom.childNodes.length)
else root.insertBefore(tag.root, tags[i].root)
// update the position attribute if it exists
if (expr.pos)
tag[expr.pos] = i
// move the old tag instance
tags.splice(i, 0, tags.splice(pos, 1)[0])
// move the old item
oldItems.splice(i, 0, oldItems.splice(pos, 1)[0])
// if the loop tags are not custom
// we need to move all their custom tags into the right position
if (!child && tag.tags) moveNestedTags(tag, i)
}
// cache the original item to use it in the events bound to this node
// and its children
tag._item = item
// cache the real parent tag internally
defineProperty(tag, '_parent', parent)
}
// remove the redundant tags
unmountRedundant(items, tags)
// insert the new nodes
if (isOption) {
root.appendChild(frag)
// #1374 <select> <option selected={true}> </select>
if (root.length) {
var si, op = root.options
root.selectedIndex = si = -1
for (i = 0; i < op.length; i++) {
if (op[i].selected = op[i].__selected) {
if (si < 0) root.selectedIndex = si = i
}
}
}
}
else root.insertBefore(frag, ref)
// set the 'tags' property of the parent tag
// if child is 'undefined' it means that we don't need to set this property
// for example:
// we don't need store the `myTag.tags['div']` property if we are looping a div tag
// but we need to track the `myTag.tags['child']` property looping a custom child node named `child`
if (child) parent.tags[tagName] = tags
// clone the items array
oldItems = items.slice()
})
}
/**
* Object that will be used to inject and manage the css of every tag instance
*/
var styleManager = (function(_riot) {
if (!window) return { // skip injection on the server
add: function () {},
inject: function () {}
}
var styleNode = (function () {
// create a new style element with the correct type
var newNode = mkEl('style')
setAttr(newNode, 'type', 'text/css')
// replace any user node or insert the new one into the head
var userNode = $('style[type=riot]')
if (userNode) {
if (userNode.id) newNode.id = userNode.id
userNode.parentNode.replaceChild(newNode, userNode)
}
else document.getElementsByTagName('head')[0].appendChild(newNode)
return newNode
})()
// Create cache and shortcut to the correct property
var cssTextProp = styleNode.styleSheet,
stylesToInject = ''
// Expose the style node in a non-modificable property
Object.defineProperty(_riot, 'styleNode', {
value: styleNode,
writable: true
})
/**
* Public api
*/
return {
/**
* Save a tag style to be later injected into DOM
* @param { String } css [description]
*/
add: function(css) {
stylesToInject += css
},
/**
* Inject all previously saved tag styles into DOM
* innerHTML seems slow: http://jsperf.com/riot-insert-style
*/
inject: function() {
if (stylesToInject) {
if (cssTextProp) cssTextProp.cssText += stylesToInject
else styleNode.innerHTML += stylesToInject
stylesToInject = ''
}
}
}
})(riot)
function parseNamedElements(root, tag, childTags, forceParsingNamed) {
walk(root, function(dom) {
if (dom.nodeType == 1) {
dom.isLoop = dom.isLoop ||
(dom.parentNode && dom.parentNode.isLoop || getAttr(dom, 'each'))
? 1 : 0
// custom child tag
if (childTags) {
var child = getTag(dom)
if (child && !dom.isLoop)
childTags.push(initChildTag(child, {root: dom, parent: tag}, dom.innerHTML, tag))
}
if (!dom.isLoop || forceParsingNamed)
setNamed(dom, tag, [])
}
})
}
function parseExpressions(root, tag, expressions) {
function addExpr(dom, val, extra) {
if (tmpl.hasExpr(val)) {
expressions.push(extend({ dom: dom, expr: val }, extra))
}
}
walk(root, function(dom) {
var type = dom.nodeType,
attr
// text node
if (type == 3 && dom.parentNode.tagName != 'STYLE') addExpr(dom, dom.nodeValue)
if (type != 1) return
/* element */
// loop
attr = getAttr(dom, 'each')
if (attr) { _each(dom, tag, attr); return false }
// attribute expressions
each(dom.attributes, function(attr) {
var name = attr.name,
bool = name.split('__')[1]
addExpr(dom, attr.value, { attr: bool || name, bool: bool })
if (bool) { remAttr(dom, name); return false }
})
// skip custom tags
if (getTag(dom)) return false
})
}
function Tag(impl, conf, innerHTML) {
var self = riot.observable(this),
opts = inherit(conf.opts) || {},
parent = conf.parent,
isLoop = conf.isLoop,
hasImpl = conf.hasImpl,
item = cleanUpData(conf.item),
expressions = [],
childTags = [],
root = conf.root,
tagName = root.tagName.toLowerCase(),
attr = {},
implAttr = {},
propsInSyncWithParent = [],
dom
// only call unmount if we have a valid __tagImpl (has name property)
if (impl.name && root._tag) root._tag.unmount(true)
// not yet mounted
this.isMounted = false
root.isLoop = isLoop
// keep a reference to the tag just created
// so we will be able to mount this tag multiple times
root._tag = this
// create a unique id to this tag
// it could be handy to use it also to improve the virtual dom rendering speed
defineProperty(this, '_riot_id', ++__uid) // base 1 allows test !t._riot_id
extend(this, { parent: parent, root: root, opts: opts, tags: {} }, item)
// grab attributes
each(root.attributes, function(el) {
var val = el.value
// remember attributes with expressions only
if (tmpl.hasExpr(val)) attr[el.name] = val
})
dom = mkdom(impl.tmpl, innerHTML)
// options
function updateOpts() {
var ctx = hasImpl && isLoop ? self : parent || self
// update opts from current DOM attributes
each(root.attributes, function(el) {
var val = el.value
opts[toCamel(el.name)] = tmpl.hasExpr(val) ? tmpl(val, ctx) : val
})
// recover those with expressions
each(Object.keys(attr), function(name) {
opts[toCamel(name)] = tmpl(attr[name], ctx)
})
}
function normalizeData(data) {
for (var key in item) {
if (typeof self[key] !== T_UNDEF && isWritable(self, key))
self[key] = data[key]
}
}
function inheritFromParent () {
if (!self.parent || !isLoop) return
each(Object.keys(self.parent), function(k) {
// some properties must be always in sync with the parent tag
var mustSync = !contains(RESERVED_WORDS_BLACKLIST, k) && contains(propsInSyncWithParent, k)
if (typeof self[k] === T_UNDEF || mustSync) {
// track the property to keep in sync
// so we can keep it updated
if (!mustSync) propsInSyncWithParent.push(k)
self[k] = self.parent[k]
}
})
}
/**
* Update the tag expressions and options
* @param { * } data - data we want to use to extend the tag properties
* @param { Boolean } isInherited - is this update coming from a parent tag?
* @returns { self }
*/
defineProperty(this, 'update', function(data, isInherited) {
// make sure the data passed will not override
// the component core methods
data = cleanUpData(data)
// inherit properties from the parent
inheritFromParent()
// normalize the tag properties in case an item object was initially passed
if (data && isObject(item)) {
normalizeData(data)
item = data
}
extend(self, data)
updateOpts()
self.trigger('update', data)
update(expressions, self)
// the updated event will be triggered
// once the DOM will be ready and all the re-flows are completed
// this is useful if you want to get the "real" root properties
// 4 ex: root.offsetWidth ...
if (isInherited && self.parent)
// closes #1599
self.parent.one('updated', function() { self.trigger('updated') })
else rAF(function() { self.trigger('updated') })
return this
})
defineProperty(this, 'mixin', function() {
each(arguments, function(mix) {
var instance
mix = typeof mix === T_STRING ? riot.mixin(mix) : mix
// check if the mixin is a function
if (isFunction(mix)) {
// create the new mixin instance
instance = new mix()
// save the prototype to loop it afterwards
mix = mix.prototype
} else instance = mix
// loop the keys in the function prototype or the all object keys
each(Object.getOwnPropertyNames(mix), function(key) {
// bind methods to self
if (key != 'init')
self[key] = isFunction(instance[key]) ?
instance[key].bind(self) :
instance[key]
})
// init method will be called automatically
if (instance.init) instance.init.bind(self)()
})
return this
})
defineProperty(this, 'mount', function() {
updateOpts()
// add global mixin
var globalMixin = riot.mixin(GLOBAL_MIXIN)
if (globalMixin) self.mixin(globalMixin)
// initialiation
if (impl.fn) impl.fn.call(self, opts)
// parse layout after init. fn may calculate args for nested custom tags
parseExpressions(dom, self, expressions)
// mount the child tags
toggle(true)
// update the root adding custom attributes coming from the compiler
// it fixes also #1087
if (impl.attrs)
walkAttributes(impl.attrs, function (k, v) { setAttr(root, k, v) })
if (impl.attrs || hasImpl)
parseExpressions(self.root, self, expressions)
if (!self.parent || isLoop) self.update(item)
// internal use only, fixes #403
self.trigger('before-mount')
if (isLoop && !hasImpl) {
// update the root attribute for the looped elements
root = dom.firstChild
} else {
while (dom.firstChild) root.appendChild(dom.firstChild)
if (root.stub) root = parent.root
}
defineProperty(self, 'root', root)
// parse the named dom nodes in the looped child
// adding them to the parent as well
if (isLoop)
parseNamedElements(self.root, self.parent, null, true)
// if it's not a child tag we can trigger its mount event
if (!self.parent || self.parent.isMounted) {
self.isMounted = true
self.trigger('mount')
}
// otherwise we need to wait that the parent event gets triggered
else self.parent.one('mount', function() {
// avoid to trigger the `mount` event for the tags
// not visible included in an if statement
if (!isInStub(self.root)) {
self.parent.isMounted = self.isMounted = true
self.trigger('mount')
}
})
})
defineProperty(this, 'unmount', function(keepRootTag) {
var el = root,
p = el.parentNode,
ptag,
tagIndex = __virtualDom.indexOf(self)
self.trigger('before-unmount')
// remove this tag instance from the global virtualDom variable
if (~tagIndex)
__virtualDom.splice(tagIndex, 1)
if (this._virts) {
each(this._virts, function(v) {
if (v.parentNode) v.parentNode.removeChild(v)
})
}
if (p) {
if (parent) {
ptag = getImmediateCustomParentTag(parent)
// remove this tag from the parent tags object
// if there are multiple nested tags with same name..
// remove this element form the array
if (isArray(ptag.tags[tagName]))
each(ptag.tags[tagName], function(tag, i) {
if (tag._riot_id == self._riot_id)
ptag.tags[tagName].splice(i, 1)
})
else
// otherwise just delete the tag instance
ptag.tags[tagName] = undefined
}
else
while (el.firstChild) el.removeChild(el.firstChild)
if (!keepRootTag)
p.removeChild(el)
else
// the riot-tag attribute isn't needed anymore, remove it
remAttr(p, 'riot-tag')
}
self.trigger('unmount')
toggle()
self.off('*')
self.isMounted = false
delete root._tag
})
// proxy function to bind updates
// dispatched from a parent tag
function onChildUpdate(data) { self.update(data, true) }
function toggle(isMount) {
// mount/unmount children
each(childTags, function(child) { child[isMount ? 'mount' : 'unmount']() })
// listen/unlisten parent (events flow one way from parent to children)
if (!parent) return
var evt = isMount ? 'on' : 'off'
// the loop tags will be always in sync with the parent automatically
if (isLoop)
parent[evt]('unmount', self.unmount)
else {
parent[evt]('update', onChildUpdate)[evt]('unmount', self.unmount)
}
}
// named elements available for fn
parseNamedElements(dom, this, childTags)
}
/**
* Attach an event to a DOM node
* @param { String } name - event name
* @param { Function } handler - event callback
* @param { Object } dom - dom node
* @param { Tag } tag - tag instance
*/
function setEventHandler(name, handler, dom, tag) {
dom[name] = function(e) {
var ptag = tag._parent,
item = tag._item,
el
if (!item)
while (ptag && !item) {
item = ptag._item
ptag = ptag._parent
}
// cross browser event fix
e = e || window.event
// override the event properties
if (isWritable(e, 'currentTarget')) e.currentTarget = dom
if (isWritable(e, 'target')) e.target = e.srcElement
if (isWritable(e, 'which')) e.which = e.charCode || e.keyCode
e.item = item
// prevent default behaviour (by default)
if (handler.call(tag, e) !== true && !/radio|check/.test(dom.type)) {
if (e.preventDefault) e.preventDefault()
e.returnValue = false
}
if (!e.preventUpdate) {
el = item ? getImmediateCustomParentTag(ptag) : tag
el.update()
}
}
}
/**
* Insert a DOM node replacing another one (used by if- attribute)
* @param { Object } root - parent node
* @param { Object } node - node replaced
* @param { Object } before - node added
*/
function insertTo(root, node, before) {
if (!root) return
root.insertBefore(before, node)
root.removeChild(node)
}
/**
* Update the expressions in a Tag instance
* @param { Array } expressions - expression that must be re evaluated
* @param { Tag } tag - tag instance
*/
function update(expressions, tag) {
each(expressions, function(expr, i) {
var dom = expr.dom,
attrName = expr.attr,
value = tmpl(expr.expr, tag),
parent = expr.dom.parentNode
if (expr.bool) {
value = !!value
if (attrName === 'selected') dom.__selected = value // #1374
}
else if (value == null)
value = ''
// #1638: regression of #1612, update the dom only if the value of the
// expression was changed
if (expr.value === value) {
return
}
expr.value = value
// textarea and text nodes has no attribute name
if (!attrName) {
// about #815 w/o replace: the browser converts the value to a string,
// the comparison by "==" does too, but not in the server
value += ''
// test for parent avoids error with invalid assignment to nodeValue
if (parent) {
if (parent.tagName === 'TEXTAREA') {
parent.value = value // #1113
if (!IE_VERSION) dom.nodeValue = value // #1625 IE throws here, nodeValue
} // will be available on 'updated'
else dom.nodeValue = value
}
return
}
// ~~#1612: look for changes in dom.value when updating the value~~
if (attrName === 'value') {
dom.value = value
return
}
// remove original attribute
remAttr(dom, attrName)
// event handler
if (isFunction(value)) {
setEventHandler(attrName, value, dom, tag)
// if- conditional
} else if (attrName == 'if') {
var stub = expr.stub,
add = function() { insertTo(stub.parentNode, stub, dom) },
remove = function() { insertTo(dom.parentNode, dom, stub) }
// add to DOM
if (value) {
if (stub) {
add()
dom.inStub = false
// avoid to trigger the mount event if the tags is not visible yet
// maybe we can optimize this avoiding to mount the tag at all
if (!isInStub(dom)) {
walk(dom, function(el) {
if (el._tag && !el._tag.isMounted)
el._tag.isMounted = !!el._tag.trigger('mount')
})
}
}
// remove from DOM
} else {
stub = expr.stub = stub || document.createTextNode('')
// if the parentNode is defined we can easily replace the tag
if (dom.parentNode)
remove()
// otherwise we need to wait the updated event
else (tag.parent || tag).one('updated', remove)
dom.inStub = true
}
// show / hide
} else if (attrName === 'show') {
dom.style.display = value ? '' : 'none'
} else if (attrName === 'hide') {
dom.style.display = value ? 'none' : ''
} else if (expr.bool) {
dom[attrName] = value
if (value) setAttr(dom, attrName, attrName)
} else if (value === 0 || value && typeof value !== T_OBJECT) {
// <img src="{ expr }">
if (startsWith(attrName, RIOT_PREFIX) && attrName != RIOT_TAG) {
attrName = attrName.slice(RIOT_PREFIX.length)
}
setAttr(dom, attrName, value)
}
})
}
/**
* Specialized function for looping an array-like collection with `each={}`
* @param { Array } els - collection of items
* @param {Function} fn - callback function
* @returns { Array } the array looped
*/
function each(els, fn) {
var len = els ? els.length : 0
for (var i = 0, el; i < len; i++) {
el = els[i]
// return false -> current item was removed by fn during the loop
if (el != null && fn(el, i) === false) i--
}
return els
}
/**
* Detect if the argument passed is a function
* @param { * } v - whatever you want to pass to this function
* @returns { Boolean } -
*/
function isFunction(v) {
return typeof v === T_FUNCTION || false // avoid IE problems
}
/**
* Detect if the argument passed is an object, exclude null.
* NOTE: Use isObject(x) && !isArray(x) to excludes arrays.
* @param { * } v - whatever you want to pass to this function
* @returns { Boolean } -
*/
function isObject(v) {
return v && typeof v === T_OBJECT // typeof null is 'object'
}
/**
* Remove any DOM attribute from a node
* @param { Object } dom - DOM node we want to update
* @param { String } name - name of the property we want to remove
*/
function remAttr(dom, name) {
dom.removeAttribute(name)
}
/**
* Convert a string containing dashes to camel case
* @param { String } string - input string
* @returns { String } my-string -> myString
*/
function toCamel(string) {
return string.replace(/-(\w)/g, function(_, c) {
return c.toUpperCase()
})
}
/**
* Get the value of any DOM attribute on a node
* @param { Object } dom - DOM node we want to parse
* @param { String } name - name of the attribute we want to get
* @returns { String | undefined } name of the node attribute whether it exists
*/
function getAttr(dom, name) {
return dom.getAttribute(name)
}
/**
* Set any DOM attribute
* @param { Object } dom - DOM node we want to update
* @param { String } name - name of the property we want to set
* @param { String } val - value of the property we want to set
*/
function setAttr(dom, name, val) {
dom.setAttribute(name, val)
}
/**
* Detect the tag implementation by a DOM node
* @param { Object } dom - DOM node we need to parse to get its tag implementation
* @returns { Object } it returns an object containing the implementation of a custom tag (template and boot function)
*/
function getTag(dom) {
return dom.tagName && __tagImpl[getAttr(dom, RIOT_TAG_IS) ||
getAttr(dom, RIOT_TAG) || dom.tagName.toLowerCase()]
}
/**
* Add a child tag to its parent into the `tags` object
* @param { Object } tag - child tag instance
* @param { String } tagName - key where the new tag will be stored
* @param { Object } parent - tag instance where the new child tag will be included
*/
function addChildTag(tag, tagName, parent) {
var cachedTag = parent.tags[tagName]
// if there are multiple children tags having the same name
if (cachedTag) {
// if the parent tags property is not yet an array
// create it adding the first cached tag
if (!isArray(cachedTag))
// don't add the same tag twice
if (cachedTag !== tag)
parent.tags[tagName] = [cachedTag]
// add the new nested tag to the array
if (!contains(parent.tags[tagName], tag))
parent.tags[tagName].push(tag)
} else {
parent.tags[tagName] = tag
}
}
/**
* Move the position of a custom tag in its parent tag
* @param { Object } tag - child tag instance
* @param { String } tagName - key where the tag was stored
* @param { Number } newPos - index where the new tag will be stored
*/
function moveChildTag(tag, tagName, newPos) {
var parent = tag.parent,
tags
// no parent no move
if (!parent) return
tags = parent.tags[tagName]
if (isArray(tags))
tags.splice(newPos, 0, tags.splice(tags.indexOf(tag), 1)[0])
else addChildTag(tag, tagName, parent)
}
/**
* Create a new child tag including it correctly into its parent
* @param { Object } child - child tag implementation
* @param { Object } opts - tag options containing the DOM node where the tag will be mounted
* @param { String } innerHTML - inner html of the child node
* @param { Object } parent - instance of the parent tag including the child custom tag
* @returns { Object } instance of the new child tag just created
*/
function initChildTag(child, opts, innerHTML, parent) {
var tag = new Tag(child, opts, innerHTML),
tagName = getTagName(opts.root),
ptag = getImmediateCustomParentTag(parent)
// fix for the parent attribute in the looped elements
tag.parent = ptag
// store the real parent tag
// in some cases this could be different from the custom parent tag
// for example in nested loops
tag._parent = parent
// add this tag to the custom parent tag
addChildTag(tag, tagName, ptag)
// and also to the real parent tag
if (ptag !== parent)
addChildTag(tag, tagName, parent)
// empty the child node once we got its template
// to avoid that its children get compiled multiple times
opts.root.innerHTML = ''
return tag
}
/**
* Loop backward all the parents tree to detect the first custom parent tag
* @param { Object } tag - a Tag instance
* @returns { Object } the instance of the first custom parent tag found
*/
function getImmediateCustomParentTag(tag) {
var ptag = tag
while (!getTag(ptag.root)) {
if (!ptag.parent) break
ptag = ptag.parent
}
return ptag
}
/**
* Helper function to set an immutable property
* @param { Object } el - object where the new property will be set
* @param { String } key - object key where the new property will be stored
* @param { * } value - value of the new property
* @param { Object } options - set the propery overriding the default options
* @returns { Object } - the initial object
*/
function defineProperty(el, key, value, options) {
Object.defineProperty(el, key, extend({
value: value,
enumerable: false,
writable: false,
configurable: false
}, options))
return el
}
/**
* Get the tag name of any DOM node
* @param { Object } dom - DOM node we want to parse
* @returns { String } name to identify this dom node in riot
*/
function getTagName(dom) {
var child = getTag(dom),
namedTag = getAttr(dom, 'name'),
tagName = namedTag && !tmpl.hasExpr(namedTag) ?
namedTag :
child ? child.name : dom.tagName.toLowerCase()
return tagName
}
/**
* Extend any object with other properties
* @param { Object } src - source object
* @returns { Object } the resulting extended object
*
* var obj = { foo: 'baz' }
* extend(obj, {bar: 'bar', foo: 'bar'})
* console.log(obj) => {bar: 'bar', foo: 'bar'}
*
*/
function extend(src) {
var obj, args = arguments
for (var i = 1; i < args.length; ++i) {
if (obj = args[i]) {
for (var key in obj) {
// check if this property of the source object could be overridden
if (isWritable(src, key))
src[key] = obj[key]
}
}
}
return src
}
/**
* Check whether an array contains an item
* @param { Array } arr - target array
* @param { * } item - item to test
* @returns { Boolean } Does 'arr' contain 'item'?
*/
function contains(arr, item) {
return ~arr.indexOf(item)
}
/**
* Check whether an object is a kind of array
* @param { * } a - anything
* @returns {Boolean} is 'a' an array?
*/
function isArray(a) { return Array.isArray(a) || a instanceof Array }
/**
* Detect whether a property of an object could be overridden
* @param { Object } obj - source object
* @param { String } key - object property
* @returns { Boolean } is this property writable?
*/
function isWritable(obj, key) {
var props = Object.getOwnPropertyDescriptor(obj, key)
return typeof obj[key] === T_UNDEF || props && props.writable
}
/**
* With this function we avoid that the internal Tag methods get overridden
* @param { Object } data - options we want to use to extend the tag instance
* @returns { Object } clean object without containing the riot internal reserved words
*/
function cleanUpData(data) {
if (!(data instanceof Tag) && !(data && typeof data.trigger == T_FUNCTION))
return data
var o = {}
for (var key in data) {
if (!contains(RESERVED_WORDS_BLACKLIST, key))
o[key] = data[key]
}
return o
}
/**
* Walk down recursively all the children tags starting dom node
* @param { Object } dom - starting node where we will start the recursion
* @param { Function } fn - callback to transform the child node just found
*/
function walk(dom, fn) {
if (dom) {
// stop the recursion
if (fn(dom) === false) return
else {
dom = dom.firstChild
while (dom) {
walk(dom, fn)
dom = dom.nextSibling
}
}
}
}
/**
* Minimize risk: only zero or one _space_ between attr & value
* @param { String } html - html string we want to parse
* @param { Function } fn - callback function to apply on any attribute found
*/
function walkAttributes(html, fn) {
var m,
re = /([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g
while (m = re.exec(html)) {
fn(m[1].toLowerCase(), m[2] || m[3] || m[4])
}
}
/**
* Check whether a DOM node is in stub mode, useful for the riot 'if' directive
* @param { Object } dom - DOM node we want to parse
* @returns { Boolean } -
*/
function isInStub(dom) {
while (dom) {
if (dom.inStub) return true
dom = dom.parentNode
}
return false
}
/**
* Create a generic DOM node
* @param { String } name - name of the DOM node we want to create
* @returns { Object } DOM node just created
*/
function mkEl(name) {
return document.createElement(name)
}
/**
* Shorter and fast way to select multiple nodes in the DOM
* @param { String } selector - DOM selector
* @param { Object } ctx - DOM node where the targets of our search will is located
* @returns { Object } dom nodes found
*/
function $$(selector, ctx) {
return (ctx || document).querySelectorAll(selector)
}
/**
* Shorter and fast way to select a single node in the DOM
* @param { String } selector - unique dom selector
* @param { Object } ctx - DOM node where the target of our search will is located
* @returns { Object } dom node found
*/
function $(selector, ctx) {
return (ctx || document).querySelector(selector)
}
/**
* Simple object prototypal inheritance
* @param { Object } parent - parent object
* @returns { Object } child instance
*/
function inherit(parent) {
function Child() {}
Child.prototype = parent
return new Child()
}
/**
* Get the name property needed to identify a DOM node in riot
* @param { Object } dom - DOM node we need to parse
* @returns { String | undefined } give us back a string to identify this dom node
*/
function getNamedKey(dom) {
return getAttr(dom, 'id') || getAttr(dom, 'name')
}
/**
* Set the named properties of a tag element
* @param { Object } dom - DOM node we need to parse
* @param { Object } parent - tag instance where the named dom element will be eventually added
* @param { Array } keys - list of all the tag instance properties
*/
function setNamed(dom, parent, keys) {
// get the key value we want to add to the tag instance
var key = getNamedKey(dom),
isArr,
// add the node detected to a tag instance using the named property
add = function(value) {
// avoid to override the tag properties already set
if (contains(keys, key)) return
// check whether this value is an array
isArr = isArray(value)
// if the key was never set
if (!value)
// set it once on the tag instance
parent[key] = dom
// if it was an array and not yet set
else if (!isArr || isArr && !contains(value, dom)) {
// add the dom node into the array
if (isArr)
value.push(dom)
else
parent[key] = [value, dom]
}
}
// skip the elements with no named properties
if (!key) return
// check whether this key has been already evaluated
if (tmpl.hasExpr(key))
// wait the first updated event only once
parent.one('mount', function() {
key = getNamedKey(dom)
add(parent[key])
})
else
add(parent[key])
}
/**
* Faster String startsWith alternative
* @param { String } src - source string
* @param { String } str - test string
* @returns { Boolean } -
*/
function startsWith(src, str) {
return src.slice(0, str.length) === str
}
/**
* requestAnimationFrame function
* Adapted from https://gist.github.com/paulirish/1579671, license MIT
*/
var rAF = (function (w) {
var raf = w.requestAnimationFrame ||
w.mozRequestAnimationFrame || w.webkitRequestAnimationFrame
if (!raf || /iP(ad|hone|od).*OS 6/.test(w.navigator.userAgent)) { // buggy iOS6
var lastTime = 0
raf = function (cb) {
var nowtime = Date.now(), timeout = Math.max(16 - (nowtime - lastTime), 0)
setTimeout(function () { cb(lastTime = nowtime + timeout) }, timeout)
}
}
return raf
})(window || {})
/**
* Mount a tag creating new Tag instance
* @param { Object } root - dom node where the tag will be mounted
* @param { String } tagName - name of the riot tag we want to mount
* @param { Object } opts - options to pass to the Tag instance
* @returns { Tag } a new Tag instance
*/
function mountTo(root, tagName, opts) {
var tag = __tagImpl[tagName],
// cache the inner HTML to fix #855
innerHTML = root._innerHTML = root._innerHTML || root.innerHTML
// clear the inner html
root.innerHTML = ''
if (tag && root) tag = new Tag(tag, { root: root, opts: opts }, innerHTML)
if (tag && tag.mount) {
tag.mount()
// add this tag to the virtualDom variable
if (!contains(__virtualDom, tag)) __virtualDom.push(tag)
}
return tag
}
/**
* Riot public api
*/
// share methods for other riot parts, e.g. compiler
riot.util = { brackets: brackets, tmpl: tmpl }
/**
* Create a mixin that could be globally shared across all the tags
*/
riot.mixin = (function() {
var mixins = {}
/**
* Create/Return a mixin by its name
* @param { String } name - mixin name (global mixin if missing)
* @param { Object } mixin - mixin logic
* @returns { Object } the mixin logic
*/
return function(name, mixin) {
if (isObject(name)) {
mixin = name
mixins[GLOBAL_MIXIN] = extend(mixins[GLOBAL_MIXIN] || {}, mixin)
return
}
if (!mixin) return mixins[name]
mixins[name] = mixin
}
})()
/**
* Create a new riot tag implementation
* @param { String } name - name/id of the new riot tag
* @param { String } html - tag template
* @param { String } css - custom tag css
* @param { String } attrs - root tag attributes
* @param { Function } fn - user function
* @returns { String } name/id of the tag just created
*/
riot.tag = function(name, html, css, attrs, fn) {
if (isFunction(attrs)) {
fn = attrs
if (/^[\w\-]+\s?=/.test(css)) {
attrs = css
css = ''
} else attrs = ''
}
if (css) {
if (isFunction(css)) fn = css
else styleManager.add(css)
}
name = name.toLowerCase()
__tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn }
return name
}
/**
* Create a new riot tag implementation (for use by the compiler)
* @param { String } name - name/id of the new riot tag
* @param { String } html - tag template
* @param { String } css - custom tag css
* @param { String } attrs - root tag attributes
* @param { Function } fn - user function
* @returns { String } name/id of the tag just created
*/
riot.tag2 = function(name, html, css, attrs, fn) {
if (css) styleManager.add(css)
//if (bpair) riot.settings.brackets = bpair
__tagImpl[name] = { name: name, tmpl: html, attrs: attrs, fn: fn }
return name
}
/**
* Mount a tag using a specific tag implementation
* @param { String } selector - tag DOM selector
* @param { String } tagName - tag implementation name
* @param { Object } opts - tag logic
* @returns { Array } new tags instances
*/
riot.mount = function(selector, tagName, opts) {
var els,
allTags,
tags = []
// helper functions
function addRiotTags(arr) {
var list = ''
each(arr, function (e) {
if (!/[^-\w]/.test(e)) {
e = e.trim().toLowerCase()
list += ',[' + RIOT_TAG_IS + '="' + e + '"],[' + RIOT_TAG + '="' + e + '"]'
}
})
return list
}
function selectAllTags() {
var keys = Object.keys(__tagImpl)
return keys + addRiotTags(keys)
}
function pushTags(root) {
if (root.tagName) {
var riotTag = getAttr(root, RIOT_TAG_IS) || getAttr(root, RIOT_TAG)
// have tagName? force riot-tag to be the same
if (tagName && riotTag !== tagName) {
riotTag = tagName
setAttr(root, RIOT_TAG_IS, tagName)
}
var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts)
if (tag) tags.push(tag)
} else if (root.length) {
each(root, pushTags) // assume nodeList
}
}
// ----- mount code -----
// inject styles into DOM
styleManager.inject()
if (isObject(tagName)) {
opts = tagName
tagName = 0
}
// crawl the DOM to find the tag
if (typeof selector === T_STRING) {
if (selector === '*')
// select all the tags registered
// and also the tags found with the riot-tag attribute set
selector = allTags = selectAllTags()
else
// or just the ones named like the selector
selector += addRiotTags(selector.split(/, */))
// make sure to pass always a selector
// to the querySelectorAll function
els = selector ? $$(selector) : []
}
else
// probably you have passed already a tag or a NodeList
els = selector
// select all the registered and mount them inside their root elements
if (tagName === '*') {
// get all custom tags
tagName = allTags || selectAllTags()
// if the root els it's just a single tag
if (els.tagName)
els = $$(tagName, els)
else {
// select all the children for all the different root elements
var nodeList = []
each(els, function (_el) {
nodeList.push($$(tagName, _el))
})
els = nodeList
}
// get rid of the tagName
tagName = 0
}
pushTags(els)
return tags
}
/**
* Update all the tags instances created
* @returns { Array } all the tags instances
*/
riot.update = function() {
return each(__virtualDom, function(tag) {
tag.update()
})
}
/**
* Export the Tag constructor
*/
riot.Tag = Tag
/* istanbul ignore next */
/**
* @module parsers
*/
var parsers = (function () {
function _req (name) {
var parser = window[name]
if (parser) return parser
throw new Error(name + ' parser not found.')
}
function extend (obj, props) {
if (props) {
for (var prop in props) {
/* istanbul ignore next */
if (props.hasOwnProperty(prop)) {
obj[prop] = props[prop]
}
}
}
return obj
}
var _p = {
html: {
jade: function (html, opts, url) {
opts = extend({
pretty: true,
filename: url,
doctype: 'html'
}, opts)
return _req('jade').render(html, opts)
}
},
css: {
less: function (tag, css, opts, url) {
var ret
opts = extend({
sync: true,
syncImport: true,
filename: url
}, opts)
_req('less').render(css, opts, function (err, result) {
// istanbul ignore next
if (err) throw err
ret = result.css
})
return ret
}
},
js: {
es6: function (js, opts) {
opts = extend({
blacklist: ['useStrict', 'strict', 'react'],
sourceMaps: false,
comments: false
}, opts)
return _req('babel').transform(js, opts).code
},
babel: function (js, opts, url) {
return _req('babel').transform(js, extend({ filename: url }, opts)).code
},
coffee: function (js, opts) {
return _req('CoffeeScript').compile(js, extend({ bare: true }, opts))
},
livescript: function (js, opts) {
return _req('livescript').compile(js, extend({ bare: true, header: false }, opts))
},
typescript: function (js, opts) {
return _req('typescript')(js, opts)
},
none: function (js) {
return js
}
}
}
_p.js.javascript = _p.js.none
_p.js.coffeescript = _p.js.coffee
return _p
})()
riot.parsers = parsers
/**
* Compiler for riot custom tags
* @version v2.3.22
*/
var compile = (function () {
var S_LINESTR = /"[^"\n\\]*(?:\\[\S\s][^"\n\\]*)*"|'[^'\n\\]*(?:\\[\S\s][^'\n\\]*)*'/.source
var S_STRINGS = brackets.R_STRINGS.source
var HTML_ATTRS = / *([-\w:\xA0-\xFF]+) ?(?:= ?('[^']*'|"[^"]*"|\S+))?/g
var HTML_COMMS = RegExp(/<!--(?!>)[\S\s]*?-->/.source + '|' + S_LINESTR, 'g')
var HTML_TAGS = /<([-\w]+)(?:\s+([^"'\/>]*(?:(?:"[^"]*"|'[^']*'|\/[^>])[^'"\/>]*)*)|\s*)(\/?)>/g
var BOOL_ATTRS = RegExp(
'^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|' +
'compact|controls|default|formnovalidate|hidden|ismap|itemscope|loop|' +
'multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|' +
'selected|sortable|truespeed|typemustmatch)$')
var RIOT_ATTRS = ['style', 'src', 'd']
var VOID_TAGS = /^(?:input|img|br|wbr|hr|area|base|col|embed|keygen|link|meta|param|source|track)$/
var PRE_TAGS = /<pre(?:\s+(?:[^">]*|"[^"]*")*)?>([\S\s]+?)<\/pre\s*>/gi
var SPEC_TYPES = /^"(?:number|date(?:time)?|time|month|email|color)\b/i
var TRIM_TRAIL = /[ \t]+$/gm
var
DQ = '"',
SQ = "'"
function cleanSource (src) {
var
mm,
re = HTML_COMMS
if (~src.indexOf('\r')) {
src = src.replace(/\r\n?/g, '\n')
}
re.lastIndex = 0
while (mm = re.exec(src)) {
if (mm[0][0] === '<') {
src = RegExp.leftContext + RegExp.rightContext
re.lastIndex = mm[3] + 1
}
}
return src
}
function parseAttribs (str, pcex) {
var
list = [],
match,
type, vexp
HTML_ATTRS.lastIndex = 0
str = str.replace(/\s+/g, ' ')
while (match = HTML_ATTRS.exec(str)) {
var
k = match[1].toLowerCase(),
v = match[2]
if (!v) {
list.push(k)
} else {
if (v[0] !== DQ) {
v = DQ + (v[0] === SQ ? v.slice(1, -1) : v) + DQ
}
if (k === 'type' && SPEC_TYPES.test(v)) {
type = v
} else {
if (/\u0001\d/.test(v)) {
if (k === 'value') vexp = 1
else if (BOOL_ATTRS.test(k)) k = '__' + k
else if (~RIOT_ATTRS.indexOf(k)) k = 'riot-' + k
}
list.push(k + '=' + v)
}
}
}
if (type) {
if (vexp) type = DQ + pcex._bp[0] + SQ + type.slice(1, -1) + SQ + pcex._bp[1] + DQ
list.push('type=' + type)
}
return list.join(' ')
}
function splitHtml (html, opts, pcex) {
var _bp = pcex._bp
if (html && _bp[4].test(html)) {
var
jsfn = opts.expr && (opts.parser || opts.type) ? _compileJS : 0,
list = brackets.split(html, 0, _bp),
expr, israw
for (var i = 1; i < list.length; i += 2) {
expr = list[i]
if (expr[0] === '^') {
expr = expr.slice(1)
} else if (jsfn) {
israw = expr[0] === '='
expr = jsfn(israw ? expr.slice(1) : expr, opts).trim()
if (expr.slice(-1) === ';') expr = expr.slice(0, -1)
if (israw) expr = '=' + expr
}
list[i] = '\u0001' + (pcex.push(expr) - 1) + _bp[1]
}
html = list.join('')
}
return html
}
function restoreExpr (html, pcex) {
if (pcex.length) {
html = html
.replace(/\u0001(\d+)/g, function (_, d) {
var expr = pcex[d]
if (expr[0] === '=') {
expr = expr.replace(brackets.R_STRINGS, function (qs) {
return qs
.replace(/</g, '<')
.replace(/>/g, '>')
})
}
return pcex._bp[0] + expr.trim().replace(/[\r\n]+/g, ' ').replace(/"/g, '\u2057')
})
}
return html
}
function _compileHTML (html, opts, pcex) {
html = splitHtml(html, opts, pcex)
.replace(HTML_TAGS, function (_, name, attr, ends) {
name = name.toLowerCase()
ends = ends && !VOID_TAGS.test(name) ? '></' + name : ''
if (attr) name += ' ' + parseAttribs(attr, pcex)
return '<' + name + ends + '>'
})
if (!opts.whitespace) {
var p = []
if (/<pre[\s>]/.test(html)) {
html = html.replace(PRE_TAGS, function (q) {
p.push(q)
return '\u0002'
})
}
html = html.trim().replace(/\s+/g, ' ')
if (p.length) html = html.replace(/\u0002/g, function () { return p.shift() })
}
if (opts.compact) html = html.replace(/>[ \t]+<([-\w\/])/g, '><$1')
return restoreExpr(html, pcex).replace(TRIM_TRAIL, '')
}
function compileHTML (html, opts, pcex) {
if (Array.isArray(opts)) {
pcex = opts
opts = {}
} else {
if (!pcex) pcex = []
if (!opts) opts = {}
}
pcex._bp = brackets.array(opts.brackets)
return _compileHTML(cleanSource(html), opts, pcex)
}
var JS_ES6SIGN = /^[ \t]*([$_A-Za-z][$\w]*)\s*\([^()]*\)\s*{/m
var JS_ES6END = RegExp('[{}]|' + brackets.S_QBLOCKS, 'g')
var JS_COMMS = RegExp(brackets.R_MLCOMMS.source + '|//[^\r\n]*|' + brackets.S_QBLOCKS, 'g')
function riotjs (js) {
var
parts = [],
match,
toes5,
pos,
name,
RE = RegExp
if (~js.indexOf('/')) js = rmComms(js, JS_COMMS)
while (match = js.match(JS_ES6SIGN)) {
parts.push(RE.leftContext)
js = RE.rightContext
pos = skipBody(js, JS_ES6END)
name = match[1]
toes5 = !/^(?:if|while|for|switch|catch|function)$/.test(name)
name = toes5 ? match[0].replace(name, 'this.' + name + ' = function') : match[0]
parts.push(name, js.slice(0, pos))
js = js.slice(pos)
if (toes5 && !/^\s*.\s*bind\b/.test(js)) parts.push('.bind(this)')
}
return parts.length ? parts.join('') + js : js
function rmComms (s, r, m) {
r.lastIndex = 0
while (m = r.exec(s)) {
if (m[0][0] === '/' && !m[1] && !m[2]) {
s = RE.leftContext + ' ' + RE.rightContext
r.lastIndex = m[3] + 1
}
}
return s
}
function skipBody (s, r) {
var m, i = 1
r.lastIndex = 0
while (i && (m = r.exec(s))) {
if (m[0] === '{') ++i
else if (m[0] === '}') --i
}
return i ? s.length : r.lastIndex
}
}
function _compileJS (js, opts, type, parserOpts, url) {
if (!/\S/.test(js)) return ''
if (!type) type = opts.type
var parser = opts.parser || (type ? parsers.js[type] : riotjs)
if (!parser) {
throw new Error('JS parser not found: "' + type + '"')
}
return parser(js, parserOpts, url).replace(/\r\n?/g, '\n').replace(TRIM_TRAIL, '')
}
function compileJS (js, opts, type, userOpts) {
if (typeof opts === 'string') {
userOpts = type
type = opts
opts = {}
}
if (type && typeof type === 'object') {
userOpts = type
type = ''
}
if (!userOpts) userOpts = {}
return _compileJS(js, opts || {}, type, userOpts.parserOptions, userOpts.url)
}
var CSS_SELECTOR = RegExp('([{}]|^)[ ;]*([^@ ;{}][^{}]*)(?={)|' + S_LINESTR, 'g')
function scopedCSS (tag, css) {
var scope = ':scope'
return css.replace(CSS_SELECTOR, function (m, p1, p2) {
if (!p2) return m
p2 = p2.replace(/[^,]+/g, function (sel) {
var s = sel.trim()
if (!s || s === 'from' || s === 'to' || s.slice(-1) === '%') {
return sel
}
if (s.indexOf(scope) < 0) {
s = tag + ' ' + s + ',[riot-tag="' + tag + '"] ' + s
} else {
s = s.replace(scope, tag) + ',' +
s.replace(scope, '[riot-tag="' + tag + '"]')
}
return sel.slice(-1) === ' ' ? s + ' ' : s
})
return p1 ? p1 + ' ' + p2 : p2
})
}
function _compileCSS (css, tag, type, opts) {
var scoped = (opts || (opts = {})).scoped
if (type) {
if (type === 'scoped-css') {
scoped = true
} else if (parsers.css[type]) {
css = parsers.css[type](tag, css, opts.parserOpts || {}, opts.url)
} else if (type !== 'css') {
throw new Error('CSS parser not found: "' + type + '"')
}
}
css = css.replace(brackets.R_MLCOMMS, '').replace(/\s+/g, ' ').trim()
if (scoped) {
if (!tag) {
throw new Error('Can not parse scoped CSS without a tagName')
}
css = scopedCSS(tag, css)
}
return css
}
function compileCSS (css, type, opts) {
if (type && typeof type === 'object') {
opts = type
type = ''
} else if (!opts) opts = {}
return _compileCSS(css, opts.tagName, type, opts)
}
var TYPE_ATTR = /\stype\s*=\s*(?:(['"])(.+?)\1|(\S+))/i
var MISC_ATTR = '\\s*=\\s*(' + S_STRINGS + '|{[^}]+}|\\S+)'
var END_TAGS = /\/>\n|^<(?:\/?[-\w]+\s*|[-\w]+\s+[-\w:\xA0-\xFF][\S\s]*?)>\n/
function _q (s, r) {
if (!s) return "''"
s = SQ + s.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + SQ
return r && ~s.indexOf('\n') ? s.replace(/\n/g, '\\n') : s
}
function mktag (name, html, css, attribs, js, pcex) {
var
c = ', ',
s = '}' + (pcex.length ? ', ' + _q(pcex._bp[8]) : '') + ');'
if (js && js.slice(-1) !== '\n') s = '\n' + s
return 'riot.tag2(\'' + name + SQ +
c + _q(html, 1) +
c + _q(css) +
c + _q(attribs) + ', function(opts) {\n' + js + s
}
function splitBlocks (str) {
if (/<[-\w]/.test(str)) {
var
m,
k = str.lastIndexOf('<'),
n = str.length
while (~k) {
m = str.slice(k, n).match(END_TAGS)
if (m) {
k += m.index + m[0].length
return [str.slice(0, k), str.slice(k)]
}
n = k
k = str.lastIndexOf('<', k - 1)
}
}
return ['', str]
}
function getType (attribs) {
if (attribs) {
var match = attribs.match(TYPE_ATTR)
match = match && (match[2] || match[3])
if (match) {
return match.replace('text/', '')
}
}
return ''
}
function getAttrib (attribs, name) {
if (attribs) {
var match = attribs.match(RegExp('\\s' + name + MISC_ATTR, 'i'))
match = match && match[1]
if (match) {
return (/^['"]/).test(match) ? match.slice(1, -1) : match
}
}
return ''
}
function getParserOptions (attribs) {
var opts = getAttrib(attribs, 'options')
return opts ? JSON.parse(opts) : null
}
function getCode (code, opts, attribs, base) {
var type = getType(attribs)
return _compileJS(code, opts, type, getParserOptions(attribs), base)
}
function cssCode (code, opts, attribs, url, tag) {
var extraOpts = {
parserOpts: getParserOptions(attribs),
scoped: attribs && /\sscoped(\s|=|$)/i.test(attribs),
url: url
}
return _compileCSS(code, tag, getType(attribs) || opts.style, extraOpts)
}
function compileTemplate (html, url, lang, opts) {
var parser = parsers.html[lang]
if (!parser) {
throw new Error('Template parser not found: "' + lang + '"')
}
return parser(html, opts, url)
}
var
CUST_TAG = RegExp(/^([ \t]*)<([-\w]+)(?:\s+([^'"\/>]+(?:(?:@|\/[^>])[^'"\/>]*)*)|\s*)?(?:\/>|>[ \t]*\n?([\S\s]*)^\1<\/\2\s*>|>(.*)<\/\2\s*>)/
.source.replace('@', S_STRINGS), 'gim'),
SCRIPTS = /<script(\s+[^>]*)?>\n?([\S\s]*?)<\/script\s*>/gi,
STYLES = /<style(\s+[^>]*)?>\n?([\S\s]*?)<\/style\s*>/gi
function compile (src, opts, url) {
var
parts = [],
included
if (!opts) opts = {}
included = opts.exclude
? function (s) { return opts.exclude.indexOf(s) < 0 } : function () { return 1 }
if (!url) url = ''
var _bp = brackets.array(opts.brackets)
if (opts.template) {
src = compileTemplate(src, url, opts.template, opts.templateOptions)
}
src = cleanSource(src)
.replace(CUST_TAG, function (_, indent, tagName, attribs, body, body2) {
var
jscode = '',
styles = '',
html = '',
pcex = []
pcex._bp = _bp
tagName = tagName.toLowerCase()
attribs = attribs && included('attribs')
? restoreExpr(
parseAttribs(
splitHtml(attribs, opts, pcex),
pcex),
pcex) : ''
if ((body || (body = body2)) && /\S/.test(body)) {
if (body2) {
if (included('html')) html = _compileHTML(body2, opts, pcex)
} else {
body = body.replace(RegExp('^' + indent, 'gm'), '')
body = body.replace(STYLES, function (_m, _attrs, _style) {
if (included('css')) {
styles += (styles ? ' ' : '') + cssCode(_style, opts, _attrs, url, tagName)
}
return ''
})
body = body.replace(SCRIPTS, function (_m, _attrs, _script) {
if (included('js')) {
var code = getCode(_script, opts, _attrs, url)
if (code) jscode += (jscode ? '\n' : '') + code
}
return ''
})
var blocks = splitBlocks(body.replace(TRIM_TRAIL, ''))
if (included('html')) {
html = _compileHTML(blocks[0], opts, pcex)
}
if (included('js')) {
body = _compileJS(blocks[1], opts, null, null, url)
if (body) jscode += (jscode ? '\n' : '') + body
}
}
}
jscode = /\S/.test(jscode) ? jscode.replace(/\n{3,}/g, '\n\n') : ''
if (opts.entities) {
parts.push({
tagName: tagName,
html: html,
css: styles,
attribs: attribs,
js: jscode
})
return ''
}
return mktag(tagName, html, styles, attribs, jscode, pcex)
})
if (opts.entities) return parts
return src
}
riot.util.compiler = {
compile: compile,
html: compileHTML,
css: compileCSS,
js: compileJS,
version: 'v2.3.22'
}
return compile
})()
/*
Compilation for the browser
*/
riot.compile = (function () {
var
promise, // emits the 'ready' event and runs the first callback
ready // all the scripts were compiled?
// gets the source of an external tag with an async call
function GET (url, fn, opts) {
var req = new XMLHttpRequest()
req.onreadystatechange = function () {
if (req.readyState === 4 &&
(req.status === 200 || !req.status && req.responseText.length)) {
fn(req.responseText, opts, url)
}
}
req.open('GET', url, true)
req.send('')
}
// evaluates a compiled tag within the global context
function globalEval (js, url) {
if (typeof js === T_STRING) {
var
node = mkEl('script'),
root = document.documentElement
// make the source available in the "(no domain)" tab
// of Chrome DevTools, with a .js extension
if (url) js += '\n//# sourceURL=' + url + '.js'
node.text = js
root.appendChild(node)
root.removeChild(node)
}
}
// compiles all the internal and external tags on the page
function compileScripts (fn, xopt) {
var
scripts = $$('script[type="riot/tag"]'),
scriptsAmount = scripts.length
function done() {
promise.trigger('ready')
ready = true
if (fn) fn()
}
function compileTag (src, opts, url) {
var code = compile(src, opts, url)
globalEval(code, url)
if (!--scriptsAmount) done()
}
if (!scriptsAmount) done()
else {
for (var i = 0; i < scripts.length; ++i) {
var
script = scripts[i],
opts = extend({template: getAttr(script, 'template')}, xopt),
url = getAttr(script, 'src')
url ? GET(url, compileTag, opts) : compileTag(script.innerHTML, opts)
}
}
}
//// Entry point -----
return function (arg, fn, opts) {
if (typeof arg === T_STRING) {
// 2nd parameter is optional, but can be null
if (isObject(fn)) {
opts = fn
fn = false
}
// `riot.compile(tag [, callback | true][, options])`
if (/^\s*</m.test(arg)) {
var js = compile(arg, opts)
if (fn !== true) globalEval(js)
if (isFunction(fn)) fn(js, arg, opts)
return js
}
// `riot.compile(url [, callback][, options])`
GET(arg, function (str, opts, url) {
var js = compile(str, opts, url)
globalEval(js, url)
if (fn) fn(js, str, opts)
})
}
else {
// `riot.compile([callback][, options])`
if (isFunction(arg)) {
opts = fn
fn = arg
} else {
opts = arg
fn = undefined
}
if (ready) {
return fn && fn()
}
if (promise) {
if (fn) promise.on('ready', fn)
} else {
promise = riot.observable()
compileScripts(fn, opts)
}
}
}
})()
// reassign mount methods -----
var mount = riot.mount
riot.mount = function (a, b, c) {
var ret
riot.compile(function () { ret = mount(a, b, c) })
return ret
}
// support CommonJS, AMD & browser
/* istanbul ignore next */
if (typeof exports === T_OBJECT)
module.exports = riot
else if (typeof define === T_FUNCTION && typeof define.amd !== T_UNDEF)
define(function() { return riot })
else
window.riot = riot
})(typeof window != 'undefined' ? window : void 0);
|
src/components/Twitter.js | KingCosmic/tinyQuotes | import React from 'react';
const Twitter = (props) => {
const { author, meta } = props.quote;
const { encoded, twitter } = meta;
return (
<li>
{(twitter) ?
<a href={`https://twitter.com/intent/tweet?text=${encoded}%20-${author}`} className=''
target="_blank" id="twitter" title={`Share me :) | ${encoded.length}`}>Twitter</a>
:
<a href='' className='disabled'
target="_blank" id="twitter" title={`Too long to share ;( | ${encoded.length}`}>Twitter</a>}
</li>
)
}
export default Twitter; |
client/router/routes.js | jasonf7/memories-of-harambe | import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import App from '#app/components/app';
import Homepage from '#app/components/homepage';
import Main from '#app/components/main';
import Preview from '#app/components/preview';
import NotFound from '#app/components/not-found';
/**
* Returns configured routes for different
* environments. `w` - wrapper that helps skip
* data fetching with onEnter hook at first time.
* @param {Object} - any data for static loaders and first-time-loading marker
* @returns {Object} - configured routes
*/
export default ({store, first}) => {
// Make a closure to skip first request
function w(loader) {
return (nextState, replaceState, callback) => {
if (first.time) {
first.time = false;
return callback();
}
return loader ? loader({store, nextState, replaceState, callback}) : callback();
};
}
return <Route path="/" component={App}>
<IndexRoute component={Homepage} onEnter={w(Homepage.onEnter)}/>
<Route path="main" component={Main} onEnter={w(Main.onEnter)}/>
<Route path="preview" component={Preview} onEnter={w(Preview.onEnter)}/>
<Route path="*" component={NotFound} onEnter={w(NotFound.onEnter)}/>
</Route>;
};
|
src/templates/indexes/tag-index.js | bretafinley/site |
import React from 'react';
import IndexDefault from './index-default';
export default function Template(props) {
const data = props.data;
const tag = props.pathContext.tag;
return (
<div>
<h2 className="card page-title">Tag: {tag}</h2>
<IndexDefault data={data} />
</div>
);
}
export const postQuery = graphql`
query TagIndex($tag: String!) {
allMarkdownRemark(
sort: { fields: [frontmatter___post_date], order: DESC },
filter: { frontmatter: { tags: { eq: $tag } }
}){
edges {
node {
id
excerpt(pruneLength: 250)
frontmatter {
title
subtitle
path
post_type
post_date
published
subject_url
category
folder
tags
}
}
}
}
}`
|
src/common/components/Heading.js | TheoMer/este | // @flow
import type { TextProps } from './Text';
import type { Theme } from '../themes/types';
import Text from './Text';
import React from 'react';
type HeadingContext = {
theme: Theme,
};
const Heading = (props: TextProps, { theme }: HeadingContext) => {
const {
bold = true,
fontFamily = theme.heading.fontFamily,
marginBottom = theme.heading.marginBottom,
...restProps
} = props;
return (
<Text
bold={bold}
fontFamily={fontFamily}
marginBottom={marginBottom}
{...restProps}
/>
);
};
Heading.contextTypes = {
theme: React.PropTypes.object,
};
export default Heading;
|
src/index.js | SabyasachiDhar/react101 | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import {Router, Route, browserHistory} from 'react-router';
import reducers from './reducers';
import routes from './routes';
import promise from 'redux-promise';
const createStoreWithMiddleware = applyMiddleware(
promise
)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('.container'));
|
src/containers/Root.prod.js | fireyy/react-antd-admin | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import route from '../route';
import { HashRouter as Router } from 'react-router-dom';
export default class Root extends Component {
render() {
const { store } = this.props;
if (!this.route) this.route = route;
return (
<Provider store={store}>
<Router children={this.route}/>
</Provider>
);
}
}
|
packages/material-ui-icons/src/SettingsEthernetSharp.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7.77 6.76L6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52l-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z" />
, 'SettingsEthernetSharp');
|
examples/async-data/app.js | jhta/react-router | var React = require('react');
var Router = require('react-router');
var EventEmitter = require('events').EventEmitter;
var { Route, DefaultRoute, RouteHandler, Link } = Router;
var API = 'http://addressbook-api.herokuapp.com';
var loadingEvents = new EventEmitter();
function getJSON(url) {
if (getJSON._cache[url])
return Promise.resolve(getJSON._cache[url]);
return new Promise((resolve, reject) => {
var req = new XMLHttpRequest();
req.onload = function () {
if (req.status === 404) {
reject(new Error('not found'));
} else {
// fake a slow response every now and then
setTimeout(function () {
var data = JSON.parse(req.response);
resolve(data);
getJSON._cache[url] = data;
}, Math.random() > 0.5 ? 0 : 1000);
}
};
req.open('GET', url);
req.send();
});
}
getJSON._cache = {};
var App = React.createClass({
statics: {
fetchData (params) {
return getJSON(`${API}/contacts`).then((res) => res.contacts);
}
},
getInitialState () {
return { loading: false };
},
componentDidMount () {
var timer;
loadingEvents.on('loadStart', () => {
clearTimeout(timer);
// for slow responses, indicate the app is thinking
// otherwise its fast enough to just wait for the
// data to load
timer = setTimeout(() => {
this.setState({ loading: true });
}, 300);
});
loadingEvents.on('loadEnd', () => {
clearTimeout(timer);
this.setState({ loading: false });
});
},
renderContacts () {
return this.props.data.contacts.map((contact, i) => {
return (
<li key={i}>
<Link to="contact" params={contact}>{contact.first} {contact.last}</Link>
</li>
);
});
},
render () {
return (
<div className={this.state.loading ? 'loading' : ''}>
<ul>
{this.renderContacts()}
</ul>
<RouteHandler {...this.props}/>
</div>
);
}
});
var Contact = React.createClass({
statics: {
fetchData (params) {
return getJSON(`${API}/contacts/${params.id}`).then((res) => res.contact);
}
},
render () {
var { contact } = this.props.data;
return (
<div>
<p><Link to="contacts">Back</Link></p>
<h1>{contact.first} {contact.last}</h1>
<img key={contact.avatar} src={contact.avatar}/>
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<h1>Welcome!</h1>
</div>
);
}
});
var routes = (
<Route name="contacts" path="/" handler={App}>
<DefaultRoute name="index" handler={Index}/>
<Route name="contact" path="contact/:id" handler={Contact}/>
</Route>
);
function fetchData(routes, params) {
var data = {};
return Promise.all(routes
.filter(route => route.handler.fetchData)
.map(route => {
return route.handler.fetchData(params).then(d => {data[route.name] = d;});
})
).then(() => data);
}
Router.run(routes, function (Handler, state) {
loadingEvents.emit('loadStart');
fetchData(state.routes, state.params).then((data) => {
loadingEvents.emit('loadEnd');
React.render(<Handler data={data}/>, document.getElementById('example'));
});
});
|
src/admin/src/components/controls/renderers/render_number.js | jgretz/zen-express | import React from 'react';
export const renderNumber = (data) =>
(
<span>{data ? data.toLocaleString() : ''}</span>
);
|
js/components/section.js | peterjacobson/Enspiral-Orientation-App-Redux | import React from 'react';
import Challenge from './challenge';
import mui from 'material-ui'
let Paper = mui.Paper
const divStyle = {
position: 'absolute',
width: '100%',
}
const paperStyle = {
padding: 20,
marginBottom: 40,
maxWidth: 600,
}
module.exports = React.createClass({
render: function () {
const {section, gameState} = this.props;
return (
<Paper className='paper' style={paperStyle}>
<div>
<h4>{section.title}</h4>
<p>{section.header}</p>
{section.challenges.map(function(challenge) {
return (
<Challenge
challenge={challenge}
gameState={gameState} />
)
})}
<p>{section.footer}</p>
</div>
</Paper>
)
}
}) |
examples/angular2/node_modules/bower-traceur-runtime/traceur-runtime.js | watonyweng/todomvc | (function(global) {
'use strict';
if (global.$traceurRuntime) {
return ;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
var $apply = Function.prototype.call.bind(Function.prototype.apply);
function $bind(operand, thisArg, args) {
var argArray = [thisArg];
for (var i = 0; i < args.length; i++) {
argArray[i + 1] = args[i];
}
var func = $apply(Function.prototype.bind, operand, argArray);
return func;
}
function $construct(func, argArray) {
var object = new ($bind(func, null, argArray));
return object;
}
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var privateNames = $create(null);
function isPrivateName(s) {
return privateNames[s];
}
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
var CONTINUATION_TYPE = Object.create(null);
function createContinuation(operand, thisArg, argsArray) {
return [CONTINUATION_TYPE, operand, thisArg, argsArray];
}
function isContinuation(object) {
return object && object[0] === CONTINUATION_TYPE;
}
var isTailRecursiveName = null;
function setupProperTailCalls() {
isTailRecursiveName = createPrivateName();
Function.prototype.call = initTailRecursiveFunction(function call(thisArg) {
var result = tailCall(function(thisArg) {
var argArray = [];
for (var i = 1; i < arguments.length; ++i) {
argArray[i - 1] = arguments[i];
}
var continuation = createContinuation(this, thisArg, argArray);
return continuation;
}, this, arguments);
return result;
});
Function.prototype.apply = initTailRecursiveFunction(function apply(thisArg, argArray) {
var result = tailCall(function(thisArg, argArray) {
var continuation = createContinuation(this, thisArg, argArray);
return continuation;
}, this, arguments);
return result;
});
}
function initTailRecursiveFunction(func) {
if (isTailRecursiveName === null) {
setupProperTailCalls();
}
func[isTailRecursiveName] = true;
return func;
}
function isTailRecursive(func) {
return !!func[isTailRecursiveName];
}
function tailCall(func, thisArg, argArray) {
var continuation = argArray[0];
if (isContinuation(continuation)) {
continuation = $apply(func, thisArg, continuation[3]);
return continuation;
}
continuation = createContinuation(func, thisArg, argArray);
while (true) {
if (isTailRecursive(func)) {
continuation = $apply(func, continuation[2], [continuation]);
} else {
continuation = $apply(func, continuation[2], continuation[3]);
}
if (!isContinuation(continuation)) {
return continuation;
}
func = continuation[1];
}
}
function construct() {
var object;
if (isTailRecursive(this)) {
object = $construct(this, [createContinuation(null, null, arguments)]);
} else {
object = $construct(this, arguments);
}
return object;
}
var $traceurRuntime = {
initTailRecursiveFunction: initTailRecursiveFunction,
call: tailCall,
continuation: createContinuation,
construct: construct
};
(function() {
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var method = nonEnum;
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
function isShimSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isShimSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
return symbolValue[symbolInternalProperty];
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
freeze(SymbolValue.prototype);
function isSymbolString(s) {
return symbolValues[s] || privateNames[s];
}
function toProperty(name) {
if (isShimSymbol(name))
return name[symbolInternalProperty];
return name;
}
function removeSymbolKeys(array) {
var rv = [];
for (var i = 0; i < array.length; i++) {
if (!isSymbolString(array[i])) {
rv.push(array[i]);
}
}
return rv;
}
function getOwnPropertyNames(object) {
return removeSymbolKeys($getOwnPropertyNames(object));
}
function keys(object) {
return removeSymbolKeys($keys(object));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol) {
rv.push(symbol);
}
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.$traceurRuntime.options[name];
}
function defineProperty(object, name, descriptor) {
if (isShimSymbol(name)) {
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
$defineProperty(Object, 'keys', {value: keys});
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (isSymbolString(name))
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function checkObjectCoercible(argument) {
if (argument == null) {
throw new TypeError('Value cannot be converted to an Object');
}
return argument;
}
function polyfillSymbol(global, Symbol) {
if (!global.Symbol) {
global.Symbol = Symbol;
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
if (!global.Symbol.iterator) {
global.Symbol.iterator = Symbol('Symbol.iterator');
}
if (!global.Symbol.observer) {
global.Symbol.observer = Symbol('Symbol.observer');
}
}
function setupGlobals(global) {
polyfillSymbol(global, Symbol);
global.Reflect = global.Reflect || {};
global.Reflect.global = global.Reflect.global || global;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
call: tailCall,
checkObjectCoercible: checkObjectCoercible,
construct: construct,
continuation: createContinuation,
createPrivateName: createPrivateName,
defineProperties: $defineProperties,
defineProperty: $defineProperty,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
initTailRecursiveFunction: initTailRecursiveFunction,
isObject: isObject,
isPrivateName: isPrivateName,
isSymbolString: isSymbolString,
keys: $keys,
options: {},
setupGlobals: setupGlobals,
toObject: toObject,
toProperty: toProperty,
typeof: typeOf
};
})();
})(typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this);
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__1 = $traceurRuntime,
canonicalizeUrl = $__1.canonicalizeUrl,
resolveUrl = $__1.resolveUrl,
isAbsolute = $__1.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
}
function ModuleEvaluationError(erroneousModuleName, cause) {
this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName;
if (!(cause instanceof ModuleEvaluationError) && cause.stack)
this.stack = this.stripStack(cause.stack);
else
this.stack = '';
}
ModuleEvaluationError.prototype = Object.create(Error.prototype);
ModuleEvaluationError.prototype.constructor = ModuleEvaluationError;
ModuleEvaluationError.prototype.stripError = function(message) {
return message.replace(/.*Error:/, this.constructor.name + ':');
};
ModuleEvaluationError.prototype.stripCause = function(cause) {
if (!cause)
return '';
if (!cause.message)
return cause + '';
return this.stripError(cause.message);
};
ModuleEvaluationError.prototype.loadedBy = function(moduleName) {
this.stack += '\n loaded by ' + moduleName;
};
ModuleEvaluationError.prototype.stripStack = function(causeStack) {
var stack = [];
causeStack.split('\n').some((function(frame) {
if (/UncoatedModuleInstantiator/.test(frame))
return true;
stack.push(frame);
}));
stack[0] = this.stripError(stack[0]);
return stack.join('\n');
};
function beforeLines(lines, number) {
var result = [];
var first = number - 3;
if (first < 0)
first = 0;
for (var i = first; i < number; i++) {
result.push(lines[i]);
}
return result;
}
function afterLines(lines, number) {
var last = number + 1;
if (last > lines.length - 1)
last = lines.length - 1;
var result = [];
for (var i = number; i <= last; i++) {
result.push(lines[i]);
}
return result;
}
function columnSpacing(columns) {
var result = '';
for (var i = 0; i < columns - 1; i++) {
result += '-';
}
return result;
}
function UncoatedModuleInstantiator(url, func) {
UncoatedModuleEntry.call(this, url, null);
this.func = func;
}
UncoatedModuleInstantiator.prototype = Object.create(UncoatedModuleEntry.prototype);
UncoatedModuleInstantiator.prototype.getUncoatedModule = function() {
if (this.value_)
return this.value_;
try {
var relativeRequire;
if (typeof $traceurRuntime !== undefined && $traceurRuntime.require) {
relativeRequire = $traceurRuntime.require.bind(null, this.url);
}
return this.value_ = this.func.call(global, relativeRequire);
} catch (ex) {
if (ex instanceof ModuleEvaluationError) {
ex.loadedBy(this.url);
throw ex;
}
if (ex.stack) {
var lines = this.func.toString().split('\n');
var evaled = [];
ex.stack.split('\n').some(function(frame) {
if (frame.indexOf('UncoatedModuleInstantiator.getUncoatedModule') > 0)
return true;
var m = /(at\s[^\s]*\s).*>:(\d*):(\d*)\)/.exec(frame);
if (m) {
var line = parseInt(m[2], 10);
evaled = evaled.concat(beforeLines(lines, line));
evaled.push(columnSpacing(m[3]) + '^');
evaled = evaled.concat(afterLines(lines, line));
evaled.push('= = = = = = = = =');
} else {
evaled.push(frame);
}
});
ex.stack = evaled.join('\n');
}
throw new ModuleEvaluationError(this.url, ex);
}
};
function getUncoatedModuleInstantiator(name) {
if (!name)
return ;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== 'string')
throw new TypeError('module name must be a string, not ' + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, deps, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, deps, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
var moduleStoreModule = new Module({ModuleStore: ModuleStore});
ModuleStore.set('@traceur/src/runtime/ModuleStore', moduleStoreModule);
ModuleStore.set('@traceur/src/runtime/ModuleStore.js', moduleStoreModule);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
registerModule: ModuleStore.registerModule.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this);
System.registerModule("[email protected]/src/runtime/async.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/async.js";
if (typeof $traceurRuntime !== 'object') {
throw new Error('traceur runtime not found.');
}
var $createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperty = $traceurRuntime.defineProperty;
var $defineProperties = $traceurRuntime.defineProperties;
var $create = Object.create;
var thisName = $createPrivateName();
var argsName = $createPrivateName();
var observeName = $createPrivateName();
function AsyncGeneratorFunction() {}
function AsyncGeneratorFunctionPrototype() {}
AsyncGeneratorFunction.prototype = AsyncGeneratorFunctionPrototype;
AsyncGeneratorFunctionPrototype.constructor = AsyncGeneratorFunction;
$defineProperty(AsyncGeneratorFunctionPrototype, 'constructor', {enumerable: false});
var AsyncGeneratorContext = function AsyncGeneratorContext(observer) {
var $__0 = this;
this.decoratedObserver = $traceurRuntime.createDecoratedGenerator(observer, (function() {
$__0.done = true;
}));
this.done = false;
this.inReturn = false;
};
($traceurRuntime.createClass)(AsyncGeneratorContext, {
throw: function(error) {
if (!this.inReturn) {
throw error;
}
},
yield: function(value) {
if (this.done) {
this.inReturn = true;
throw undefined;
}
var result;
try {
result = this.decoratedObserver.next(value);
} catch (e) {
this.done = true;
throw e;
}
if (result === undefined) {
return ;
}
if (result.done) {
this.done = true;
this.inReturn = true;
throw undefined;
}
return result.value;
},
yieldFor: function(observable) {
var ctx = this;
return $traceurRuntime.observeForEach(observable[$traceurRuntime.toProperty(Symbol.observer)].bind(observable), function(value) {
if (ctx.done) {
this.return();
return ;
}
var result;
try {
result = ctx.decoratedObserver.next(value);
} catch (e) {
ctx.done = true;
throw e;
}
if (result === undefined) {
return ;
}
if (result.done) {
ctx.done = true;
}
return result;
});
}
}, {});
AsyncGeneratorFunctionPrototype.prototype[Symbol.observer] = function(observer) {
var observe = this[observeName];
var ctx = new AsyncGeneratorContext(observer);
$traceurRuntime.schedule((function() {
return observe(ctx);
})).then((function(value) {
if (!ctx.done) {
ctx.decoratedObserver.return(value);
}
})).catch((function(error) {
if (!ctx.done) {
ctx.decoratedObserver.throw(error);
}
}));
return ctx.decoratedObserver;
};
$defineProperty(AsyncGeneratorFunctionPrototype.prototype, Symbol.observer, {enumerable: false});
function initAsyncGeneratorFunction(functionObject) {
functionObject.prototype = $create(AsyncGeneratorFunctionPrototype.prototype);
functionObject.__proto__ = AsyncGeneratorFunctionPrototype;
return functionObject;
}
function createAsyncGeneratorInstance(observe, functionObject) {
for (var args = [],
$__2 = 2; $__2 < arguments.length; $__2++)
args[$__2 - 2] = arguments[$__2];
var object = $create(functionObject.prototype);
object[thisName] = this;
object[argsName] = args;
object[observeName] = observe;
return object;
}
function observeForEach(observe, next) {
return new Promise((function(resolve, reject) {
var generator = observe({
next: function(value) {
return next.call(generator, value);
},
throw: function(error) {
reject(error);
},
return: function(value) {
resolve(value);
}
});
}));
}
function schedule(asyncF) {
return Promise.resolve().then(asyncF);
}
var generator = Symbol();
var onDone = Symbol();
var DecoratedGenerator = function DecoratedGenerator(_generator, _onDone) {
this[generator] = _generator;
this[onDone] = _onDone;
};
($traceurRuntime.createClass)(DecoratedGenerator, {
next: function(value) {
var result = this[generator].next(value);
if (result !== undefined && result.done) {
this[onDone].call(this);
}
return result;
},
throw: function(error) {
this[onDone].call(this);
return this[generator].throw(error);
},
return: function(value) {
this[onDone].call(this);
return this[generator].return(value);
}
}, {});
function createDecoratedGenerator(generator, onDone) {
return new DecoratedGenerator(generator, onDone);
}
$traceurRuntime.initAsyncGeneratorFunction = initAsyncGeneratorFunction;
$traceurRuntime.createAsyncGeneratorInstance = createAsyncGeneratorInstance;
$traceurRuntime.observeForEach = observeForEach;
$traceurRuntime.schedule = schedule;
$traceurRuntime.createDecoratedGenerator = createDecoratedGenerator;
return {};
});
System.registerModule("[email protected]/src/runtime/classes.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/classes.js";
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
var $__0 = Object,
getOwnPropertyNames = $__0.getOwnPropertyNames,
getOwnPropertySymbols = $__0.getOwnPropertySymbols;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superConstructor(ctor) {
return ctor.__proto__;
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError(("super has no setter '" + name + "'."));
}
function getDescriptors(object) {
var descriptors = {};
var names = getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
var symbols = getOwnPropertySymbols(object);
for (var i = 0; i < symbols.length; i++) {
var symbol = symbols[i];
descriptors[$traceurRuntime.toProperty(symbol)] = $getOwnPropertyDescriptor(object, $traceurRuntime.toProperty(symbol));
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
throw new $TypeError('super prototype must be an Object or null');
}
if (superClass === null)
return null;
throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + "."));
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.superConstructor = superConstructor;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
return {};
});
System.registerModule("[email protected]/src/runtime/destructuring.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/destructuring.js";
function iteratorToArray(iter) {
var rv = [];
var i = 0;
var tmp;
while (!(tmp = iter.next()).done) {
rv[i++] = tmp.value;
}
return rv;
}
$traceurRuntime.iteratorToArray = iteratorToArray;
return {};
});
System.registerModule("[email protected]/src/runtime/generators.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/generators.js";
if (typeof $traceurRuntime !== 'object') {
throw new Error('traceur runtime not found.');
}
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
var RETURN_SENTINEL = {};
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.oldReturnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
maybeUncatchable: function() {
if (this.storedException === RETURN_SENTINEL) {
throw RETURN_SENTINEL;
}
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
},
wrapYieldStar: function(iterator) {
var ctx = this;
return {
next: function(v) {
return iterator.next(v);
},
throw: function(e) {
var result;
if (e === RETURN_SENTINEL) {
if (iterator.return) {
result = iterator.return(ctx.returnValue);
if (!result.done) {
ctx.returnValue = ctx.oldReturnValue;
return result;
}
ctx.returnValue = result.value;
}
throw e;
}
if (iterator.throw) {
return iterator.throw(e);
}
iterator.return && iterator.return();
throw $TypeError('Inner iterator does not have a throw method');
}
};
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
if (x === RETURN_SENTINEL) {
return {
value: ctx.returnValue,
done: true
};
}
throw x;
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
if (x === RETURN_SENTINEL) {
return {
value: ctx.returnValue,
done: true
};
}
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value;
try {
value = moveNext(ctx);
} catch (ex) {
if (ex === RETURN_SENTINEL) {
value = ctx;
} else {
throw ex;
}
}
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
},
return: function(v) {
this[ctxName].oldReturnValue = this[ctxName].returnValue;
this[ctxName].returnValue = v;
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', RETURN_SENTINEL);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false},
return: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return ;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
return {};
});
System.registerModule("[email protected]/src/runtime/relativeRequire.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/relativeRequire.js";
var path;
function relativeRequire(callerPath, requiredPath) {
path = path || typeof require !== 'undefined' && require('path');
function isDirectory(path) {
return path.slice(-1) === '/';
}
function isAbsolute(path) {
return path[0] === '/';
}
function isRelative(path) {
return path[0] === '.';
}
if (isDirectory(requiredPath) || isAbsolute(requiredPath))
return ;
return isRelative(requiredPath) ? require(path.resolve(path.dirname(callerPath), requiredPath)) : require(requiredPath);
}
$traceurRuntime.require = relativeRequire;
return {};
});
System.registerModule("[email protected]/src/runtime/spread.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/spread.js";
function spread() {
var rv = [],
j = 0,
iterResult;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]);
if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') {
throw new TypeError('Cannot spread non-iterable object.');
}
var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)]();
while (!(iterResult = iter.next()).done) {
rv[j++] = iterResult.value;
}
}
return rv;
}
$traceurRuntime.spread = spread;
return {};
});
System.registerModule("[email protected]/src/runtime/type-assertions.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/type-assertions.js";
var types = {
any: {name: 'any'},
boolean: {name: 'boolean'},
number: {name: 'number'},
string: {name: 'string'},
symbol: {name: 'symbol'},
void: {name: 'void'}
};
var GenericType = function GenericType(type, argumentTypes) {
this.type = type;
this.argumentTypes = argumentTypes;
};
($traceurRuntime.createClass)(GenericType, {}, {});
var typeRegister = Object.create(null);
function genericType(type) {
for (var argumentTypes = [],
$__1 = 1; $__1 < arguments.length; $__1++)
argumentTypes[$__1 - 1] = arguments[$__1];
var typeMap = typeRegister;
var key = $traceurRuntime.getOwnHashObject(type).hash;
if (!typeMap[key]) {
typeMap[key] = Object.create(null);
}
typeMap = typeMap[key];
for (var i = 0; i < argumentTypes.length - 1; i++) {
key = $traceurRuntime.getOwnHashObject(argumentTypes[i]).hash;
if (!typeMap[key]) {
typeMap[key] = Object.create(null);
}
typeMap = typeMap[key];
}
var tail = argumentTypes[argumentTypes.length - 1];
key = $traceurRuntime.getOwnHashObject(tail).hash;
if (!typeMap[key]) {
typeMap[key] = new GenericType(type, argumentTypes);
}
return typeMap[key];
}
$traceurRuntime.GenericType = GenericType;
$traceurRuntime.genericType = genericType;
$traceurRuntime.type = types;
return {};
});
System.registerModule("[email protected]/src/runtime/runtime-modules.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/runtime-modules.js";
System.get("[email protected]/src/runtime/relativeRequire.js");
System.get("[email protected]/src/runtime/spread.js");
System.get("[email protected]/src/runtime/destructuring.js");
System.get("[email protected]/src/runtime/classes.js");
System.get("[email protected]/src/runtime/async.js");
System.get("[email protected]/src/runtime/generators.js");
System.get("[email protected]/src/runtime/type-assertions.js");
return {};
});
System.get("[email protected]/src/runtime/runtime-modules.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/utils.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/utils.js";
var $ceil = Math.ceil;
var $floor = Math.floor;
var $isFinite = isFinite;
var $isNaN = isNaN;
var $pow = Math.pow;
var $min = Math.min;
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x >>> 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function isNumber(x) {
return typeof x === 'number';
}
function toInteger(x) {
x = +x;
if ($isNaN(x))
return 0;
if (x === 0 || !$isFinite(x))
return x;
return x > 0 ? $floor(x) : $ceil(x);
}
var MAX_SAFE_LENGTH = $pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH);
}
function checkIterable(x) {
return !isObject(x) ? undefined : x[Symbol.iterator];
}
function isConstructor(x) {
return isCallable(x);
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function maybeDefine(object, name, descr) {
if (!(name in object)) {
Object.defineProperty(object, name, descr);
}
}
function maybeDefineMethod(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
function maybeDefineConst(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: false,
enumerable: false,
writable: false
});
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function maybeAddConsts(object, consts) {
for (var i = 0; i < consts.length; i += 2) {
var name = consts[i];
var value = consts[i + 1];
maybeDefineConst(object, name, value);
}
}
function maybeAddIterator(object, func, Symbol) {
if (!Symbol || !Symbol.iterator || object[Symbol.iterator])
return ;
if (object['@@iterator'])
func = object['@@iterator'];
Object.defineProperty(object, Symbol.iterator, {
value: func,
configurable: true,
enumerable: false,
writable: true
});
}
var polyfills = [];
function registerPolyfill(func) {
polyfills.push(func);
}
function polyfillAll(global) {
polyfills.forEach((function(f) {
return f(global);
}));
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get isNumber() {
return isNumber;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
},
get checkIterable() {
return checkIterable;
},
get isConstructor() {
return isConstructor;
},
get createIteratorResultObject() {
return createIteratorResultObject;
},
get maybeDefine() {
return maybeDefine;
},
get maybeDefineMethod() {
return maybeDefineMethod;
},
get maybeDefineConst() {
return maybeDefineConst;
},
get maybeAddFunctions() {
return maybeAddFunctions;
},
get maybeAddConsts() {
return maybeAddConsts;
},
get maybeAddIterator() {
return maybeAddIterator;
},
get registerPolyfill() {
return registerPolyfill;
},
get polyfillAll() {
return polyfillAll;
}
};
});
System.registerModule("[email protected]/src/runtime/polyfills/Map.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Map.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
isObject = $__0.isObject,
maybeAddIterator = $__0.maybeAddIterator,
registerPolyfill = $__0.registerPolyfill;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var $__10,
$__11;
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Map called on incompatible type');
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError('Map can not be reentrantly initialised');
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
var $__5 = true;
var $__6 = false;
var $__7 = undefined;
try {
for (var $__3 = void 0,
$__2 = (iterable)[$traceurRuntime.toProperty(Symbol.iterator)](); !($__5 = ($__3 = $__2.next()).done); $__5 = true) {
var $__9 = $__3.value,
key = ($__10 = $__9[$traceurRuntime.toProperty(Symbol.iterator)](), ($__11 = $__10.next()).done ? void 0 : $__11.value),
value = ($__11 = $__10.next()).done ? void 0 : $__11.value;
{
this.set(key, value);
}
}
} catch ($__8) {
$__6 = true;
$__7 = $__8;
} finally {
try {
if (!$__5 && $__2.return != null) {
$__2.return();
}
} finally {
if ($__6) {
throw $__7;
}
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
return true;
}
return false;
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0; i < this.entries_.length; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
},
entries: $traceurRuntime.initGeneratorFunction(function $__12() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return [key, value];
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__12, this);
}),
keys: $traceurRuntime.initGeneratorFunction(function $__13() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return key;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__13, this);
}),
values: $traceurRuntime.initGeneratorFunction(function $__14() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return value;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__14, this);
})
}, {});
Object.defineProperty(Map.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Map.prototype.entries
});
function polyfillMap(global) {
var $__9 = global,
Object = $__9.Object,
Symbol = $__9.Symbol;
if (!global.Map)
global.Map = Map;
var mapPrototype = global.Map.prototype;
if (mapPrototype.entries === undefined)
global.Map = Map;
if (mapPrototype.entries) {
maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillMap);
return {
get Map() {
return Map;
},
get polyfillMap() {
return polyfillMap;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Map.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/Set.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Set.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
isObject = $__0.isObject,
maybeAddIterator = $__0.maybeAddIterator,
registerPolyfill = $__0.registerPolyfill;
var Map = System.get("[email protected]/src/runtime/polyfills/Map.js").Map;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
function initSet(set) {
set.map_ = new Map();
}
var Set = function Set() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Set called on incompatible type');
if ($hasOwnProperty.call(this, 'map_')) {
throw new TypeError('Set can not be reentrantly initialised');
}
initSet(this);
if (iterable !== null && iterable !== undefined) {
var $__7 = true;
var $__8 = false;
var $__9 = undefined;
try {
for (var $__5 = void 0,
$__4 = (iterable)[$traceurRuntime.toProperty(Symbol.iterator)](); !($__7 = ($__5 = $__4.next()).done); $__7 = true) {
var item = $__5.value;
{
this.add(item);
}
}
} catch ($__10) {
$__8 = true;
$__9 = $__10;
} finally {
try {
if (!$__7 && $__4.return != null) {
$__4.return();
}
} finally {
if ($__8) {
throw $__9;
}
}
}
}
};
($traceurRuntime.createClass)(Set, {
get size() {
return this.map_.size;
},
has: function(key) {
return this.map_.has(key);
},
add: function(key) {
this.map_.set(key, key);
return this;
},
delete: function(key) {
return this.map_.delete(key);
},
clear: function() {
return this.map_.clear();
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
var $__2 = this;
return this.map_.forEach((function(value, key) {
callbackFn.call(thisArg, key, key, $__2);
}));
},
values: $traceurRuntime.initGeneratorFunction(function $__12() {
var $__13,
$__14;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__13 = $ctx.wrapYieldStar(this.map_.keys()[Symbol.iterator]());
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__14 = $__13[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__14.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__14.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__14.value;
default:
return $ctx.end();
}
}, $__12, this);
}),
entries: $traceurRuntime.initGeneratorFunction(function $__15() {
var $__16,
$__17;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__16 = $ctx.wrapYieldStar(this.map_.entries()[Symbol.iterator]());
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__17 = $__16[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__17.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__17.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__17.value;
default:
return $ctx.end();
}
}, $__15, this);
})
}, {});
Object.defineProperty(Set.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Set.prototype.values
});
Object.defineProperty(Set.prototype, 'keys', {
configurable: true,
writable: true,
value: Set.prototype.values
});
function polyfillSet(global) {
var $__11 = global,
Object = $__11.Object,
Symbol = $__11.Symbol;
if (!global.Set)
global.Set = Set;
var setPrototype = global.Set.prototype;
if (setPrototype.values) {
maybeAddIterator(setPrototype, setPrototype.values, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillSet);
return {
get Set() {
return Set;
},
get polyfillSet() {
return polyfillSet;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Set.js" + '');
System.registerModule("[email protected]/node_modules/rsvp/lib/rsvp/asap.js", [], function() {
"use strict";
var __moduleName = "[email protected]/node_modules/rsvp/lib/rsvp/asap.js";
var len = 0;
function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
scheduleFlush();
}
}
var $__default = asap;
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {characterData: true});
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function() {
channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.registerModule("[email protected]/src/runtime/polyfills/Promise.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Promise.js";
var async = System.get("[email protected]/node_modules/rsvp/lib/rsvp/asap.js").default;
var registerPolyfill = System.get("[email protected]/src/runtime/polyfills/utils.js").registerPolyfill;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return ;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
if (isPromise(x)) {
return x;
}
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var makeCountdownFunction = function(i) {
return (function(x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
});
};
var count = 0;
var i = 0;
var $__6 = true;
var $__7 = false;
var $__8 = undefined;
try {
for (var $__4 = void 0,
$__3 = (values)[$traceurRuntime.toProperty(Symbol.iterator)](); !($__6 = ($__4 = $__3.next()).done); $__6 = true) {
var value = $__4.value;
{
var countdownFunction = makeCountdownFunction(i);
this.resolve(value).then(countdownFunction, (function(r) {
deferred.reject(r);
}));
++i;
++count;
}
}
} catch ($__9) {
$__7 = true;
$__8 = $__9;
} finally {
try {
if (!$__6 && $__3.return != null) {
$__3.return();
}
} finally {
if ($__7) {
throw $__8;
}
}
}
if (count === 0) {
deferred.resolve(resolutions);
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return ;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
registerPolyfill(polyfillPromise);
return {
get Promise() {
return Promise;
},
get polyfillPromise() {
return polyfillPromise;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Promise.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/StringIterator.js", [], function() {
"use strict";
var $__2;
var __moduleName = "[email protected]/src/runtime/polyfills/StringIterator.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
createIteratorResultObject = $__0.createIteratorResultObject,
isObject = $__0.isObject;
var toProperty = $traceurRuntime.toProperty;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var iteratedString = Symbol('iteratedString');
var stringIteratorNextIndex = Symbol('stringIteratorNextIndex');
var StringIterator = function StringIterator() {
;
};
($traceurRuntime.createClass)(StringIterator, ($__2 = {}, Object.defineProperty($__2, "next", {
value: function() {
var o = this;
if (!isObject(o) || !hasOwnProperty.call(o, iteratedString)) {
throw new TypeError('this must be a StringIterator object');
}
var s = o[toProperty(iteratedString)];
if (s === undefined) {
return createIteratorResultObject(undefined, true);
}
var position = o[toProperty(stringIteratorNextIndex)];
var len = s.length;
if (position >= len) {
o[toProperty(iteratedString)] = undefined;
return createIteratorResultObject(undefined, true);
}
var first = s.charCodeAt(position);
var resultString;
if (first < 0xD800 || first > 0xDBFF || position + 1 === len) {
resultString = String.fromCharCode(first);
} else {
var second = s.charCodeAt(position + 1);
if (second < 0xDC00 || second > 0xDFFF) {
resultString = String.fromCharCode(first);
} else {
resultString = String.fromCharCode(first) + String.fromCharCode(second);
}
}
o[toProperty(stringIteratorNextIndex)] = position + resultString.length;
return createIteratorResultObject(resultString, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__2, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__2), {});
function createStringIterator(string) {
var s = String(string);
var iterator = Object.create(StringIterator.prototype);
iterator[toProperty(iteratedString)] = s;
iterator[toProperty(stringIteratorNextIndex)] = 0;
return iterator;
}
return {get createStringIterator() {
return createStringIterator;
}};
});
System.registerModule("[email protected]/src/runtime/polyfills/String.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/String.js";
var createStringIterator = System.get("[email protected]/src/runtime/polyfills/StringIterator.js").createStringIterator;
var $__1 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
maybeAddFunctions = $__1.maybeAddFunctions,
maybeAddIterator = $__1.maybeAddIterator,
registerPolyfill = $__1.registerPolyfill;
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function includes(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
if (search && $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (pos != pos) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
if (searchLength + start > stringLength) {
return false;
}
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint(_) {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
function stringPrototypeIterator() {
var o = $traceurRuntime.checkObjectCoercible(this);
var s = String(o);
return createStringIterator(s);
}
function polyfillString(global) {
var String = global.String;
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'endsWith', endsWith, 'includes', includes, 'repeat', repeat, 'startsWith', startsWith]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol);
}
registerPolyfill(polyfillString);
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get includes() {
return includes;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
},
get stringPrototypeIterator() {
return stringPrototypeIterator;
},
get polyfillString() {
return polyfillString;
}
};
});
System.get("[email protected]/src/runtime/polyfills/String.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/ArrayIterator.js", [], function() {
"use strict";
var $__2;
var __moduleName = "[email protected]/src/runtime/polyfills/ArrayIterator.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
toObject = $__0.toObject,
toUint32 = $__0.toUint32,
createIteratorResultObject = $__0.createIteratorResultObject;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {
;
};
($traceurRuntime.createClass)(ArrayIterator, ($__2 = {}, Object.defineProperty($__2, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__2, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__2), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.registerModule("[email protected]/src/runtime/polyfills/Array.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Array.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/ArrayIterator.js"),
entries = $__0.entries,
keys = $__0.keys,
jsValues = $__0.values;
var $__1 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
checkIterable = $__1.checkIterable,
isCallable = $__1.isCallable,
isConstructor = $__1.isConstructor,
maybeAddFunctions = $__1.maybeAddFunctions,
maybeAddIterator = $__1.maybeAddIterator,
registerPolyfill = $__1.registerPolyfill,
toInteger = $__1.toInteger,
toLength = $__1.toLength,
toObject = $__1.toObject;
function from(arrLike) {
var mapFn = arguments[1];
var thisArg = arguments[2];
var C = this;
var items = toObject(arrLike);
var mapping = mapFn !== undefined;
var k = 0;
var arr,
len;
if (mapping && !isCallable(mapFn)) {
throw TypeError();
}
if (checkIterable(items)) {
arr = isConstructor(C) ? new C() : [];
var $__5 = true;
var $__6 = false;
var $__7 = undefined;
try {
for (var $__3 = void 0,
$__2 = (items)[$traceurRuntime.toProperty(Symbol.iterator)](); !($__5 = ($__3 = $__2.next()).done); $__5 = true) {
var item = $__3.value;
{
if (mapping) {
arr[k] = mapFn.call(thisArg, item, k);
} else {
arr[k] = item;
}
k++;
}
}
} catch ($__8) {
$__6 = true;
$__7 = $__8;
} finally {
try {
if (!$__5 && $__2.return != null) {
$__2.return();
}
} finally {
if ($__6) {
throw $__7;
}
}
}
arr.length = k;
return arr;
}
len = toLength(items.length);
arr = isConstructor(C) ? new C(len) : new Array(len);
for (; k < len; k++) {
if (mapping) {
arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k);
} else {
arr[k] = items[k];
}
}
arr.length = len;
return arr;
}
function of() {
for (var items = [],
$__9 = 0; $__9 < arguments.length; $__9++)
items[$__9] = arguments[$__9];
var C = this;
var len = items.length;
var arr = isConstructor(C) ? new C(len) : new Array(len);
for (var k = 0; k < len; k++) {
arr[k] = items[k];
}
arr.length = len;
return arr;
}
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
return returnIndex ? -1 : undefined;
}
function polyfillArray(global) {
var $__10 = global,
Array = $__10.Array,
Object = $__10.Object,
Symbol = $__10.Symbol;
var values = jsValues;
if (Symbol && Symbol.iterator && Array.prototype[Symbol.iterator]) {
values = Array.prototype[Symbol.iterator];
}
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
maybeAddFunctions(Array, ['from', from, 'of', of]);
maybeAddIterator(Array.prototype, values, Symbol);
maybeAddIterator(Object.getPrototypeOf([].values()), function() {
return this;
}, Symbol);
}
registerPolyfill(polyfillArray);
return {
get from() {
return from;
},
get of() {
return of;
},
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
},
get polyfillArray() {
return polyfillArray;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Array.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/Object.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Object.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
maybeAddFunctions = $__0.maybeAddFunctions,
registerPolyfill = $__0.registerPolyfill;
var $__1 = $traceurRuntime,
defineProperty = $__1.defineProperty,
getOwnPropertyDescriptor = $__1.getOwnPropertyDescriptor,
getOwnPropertyNames = $__1.getOwnPropertyNames,
isPrivateName = $__1.isPrivateName,
keys = $__1.keys;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = source == null ? [] : keys(source);
var p = void 0,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (isPrivateName(name))
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (isPrivateName(name))
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
function polyfillObject(global) {
var Object = global.Object;
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
registerPolyfill(polyfillObject);
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
},
get polyfillObject() {
return polyfillObject;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Object.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/Number.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Number.js";
var $__0 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
isNumber = $__0.isNumber,
maybeAddConsts = $__0.maybeAddConsts,
maybeAddFunctions = $__0.maybeAddFunctions,
registerPolyfill = $__0.registerPolyfill,
toInteger = $__0.toInteger;
var $abs = Math.abs;
var $isFinite = isFinite;
var $isNaN = isNaN;
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1;
var EPSILON = Math.pow(2, -52);
function NumberIsFinite(number) {
return isNumber(number) && $isFinite(number);
}
;
function isInteger(number) {
return NumberIsFinite(number) && toInteger(number) === number;
}
function NumberIsNaN(number) {
return isNumber(number) && $isNaN(number);
}
;
function isSafeInteger(number) {
if (NumberIsFinite(number)) {
var integral = toInteger(number);
if (integral === number)
return $abs(integral) <= MAX_SAFE_INTEGER;
}
return false;
}
function polyfillNumber(global) {
var Number = global.Number;
maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]);
maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]);
}
registerPolyfill(polyfillNumber);
return {
get MAX_SAFE_INTEGER() {
return MAX_SAFE_INTEGER;
},
get MIN_SAFE_INTEGER() {
return MIN_SAFE_INTEGER;
},
get EPSILON() {
return EPSILON;
},
get isFinite() {
return NumberIsFinite;
},
get isInteger() {
return isInteger;
},
get isNaN() {
return NumberIsNaN;
},
get isSafeInteger() {
return isSafeInteger;
},
get polyfillNumber() {
return polyfillNumber;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Number.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/fround.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/fround.js";
var $isFinite = isFinite;
var $isNaN = isNaN;
var $__0 = Math,
LN2 = $__0.LN2,
abs = $__0.abs,
floor = $__0.floor,
log = $__0.log,
min = $__0.min,
pow = $__0.pow;
function packIEEE754(v, ebits, fbits) {
var bias = (1 << (ebits - 1)) - 1,
s,
e,
f,
ln,
i,
bits,
str,
bytes;
function roundToEven(n) {
var w = floor(n),
f = n - w;
if (f < 0.5)
return w;
if (f > 0.5)
return w + 1;
return w % 2 ? w + 1 : w;
}
if (v !== v) {
e = (1 << ebits) - 1;
f = pow(2, fbits - 1);
s = 0;
} else if (v === Infinity || v === -Infinity) {
e = (1 << ebits) - 1;
f = 0;
s = (v < 0) ? 1 : 0;
} else if (v === 0) {
e = 0;
f = 0;
s = (1 / v === -Infinity) ? 1 : 0;
} else {
s = v < 0;
v = abs(v);
if (v >= pow(2, 1 - bias)) {
e = min(floor(log(v) / LN2), 1023);
f = roundToEven(v / pow(2, e) * pow(2, fbits));
if (f / pow(2, fbits) >= 2) {
e = e + 1;
f = 1;
}
if (e > bias) {
e = (1 << ebits) - 1;
f = 0;
} else {
e = e + bias;
f = f - pow(2, fbits);
}
} else {
e = 0;
f = roundToEven(v / pow(2, 1 - bias - fbits));
}
}
bits = [];
for (i = fbits; i; i -= 1) {
bits.push(f % 2 ? 1 : 0);
f = floor(f / 2);
}
for (i = ebits; i; i -= 1) {
bits.push(e % 2 ? 1 : 0);
e = floor(e / 2);
}
bits.push(s ? 1 : 0);
bits.reverse();
str = bits.join('');
bytes = [];
while (str.length) {
bytes.push(parseInt(str.substring(0, 8), 2));
str = str.substring(8);
}
return bytes;
}
function unpackIEEE754(bytes, ebits, fbits) {
var bits = [],
i,
j,
b,
str,
bias,
s,
e,
f;
for (i = bytes.length; i; i -= 1) {
b = bytes[i - 1];
for (j = 8; j; j -= 1) {
bits.push(b % 2 ? 1 : 0);
b = b >> 1;
}
}
bits.reverse();
str = bits.join('');
bias = (1 << (ebits - 1)) - 1;
s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
e = parseInt(str.substring(1, 1 + ebits), 2);
f = parseInt(str.substring(1 + ebits), 2);
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
} else if (e > 0) {
return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
} else if (f !== 0) {
return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
} else {
return s < 0 ? -0 : 0;
}
}
function unpackF32(b) {
return unpackIEEE754(b, 8, 23);
}
function packF32(v) {
return packIEEE754(v, 8, 23);
}
function fround(x) {
if (x === 0 || !$isFinite(x) || $isNaN(x)) {
return x;
}
return unpackF32(packF32(Number(x)));
}
return {get fround() {
return fround;
}};
});
System.registerModule("[email protected]/src/runtime/polyfills/Math.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Math.js";
var jsFround = System.get("[email protected]/src/runtime/polyfills/fround.js").fround;
var $__1 = System.get("[email protected]/src/runtime/polyfills/utils.js"),
maybeAddFunctions = $__1.maybeAddFunctions,
registerPolyfill = $__1.registerPolyfill,
toUint32 = $__1.toUint32;
var $isFinite = isFinite;
var $isNaN = isNaN;
var $__2 = Math,
abs = $__2.abs,
ceil = $__2.ceil,
exp = $__2.exp,
floor = $__2.floor,
log = $__2.log,
pow = $__2.pow,
sqrt = $__2.sqrt;
function clz32(x) {
x = toUint32(+x);
if (x == 0)
return 32;
var result = 0;
if ((x & 0xFFFF0000) === 0) {
x <<= 16;
result += 16;
}
;
if ((x & 0xFF000000) === 0) {
x <<= 8;
result += 8;
}
;
if ((x & 0xF0000000) === 0) {
x <<= 4;
result += 4;
}
;
if ((x & 0xC0000000) === 0) {
x <<= 2;
result += 2;
}
;
if ((x & 0x80000000) === 0) {
x <<= 1;
result += 1;
}
;
return result;
}
function imul(x, y) {
x = toUint32(+x);
y = toUint32(+y);
var xh = (x >>> 16) & 0xffff;
var xl = x & 0xffff;
var yh = (y >>> 16) & 0xffff;
var yl = y & 0xffff;
return xl * yl + (((xh * yl + xl * yh) << 16) >>> 0) | 0;
}
function sign(x) {
x = +x;
if (x > 0)
return 1;
if (x < 0)
return -1;
return x;
}
function log10(x) {
return log(x) * 0.434294481903251828;
}
function log2(x) {
return log(x) * 1.442695040888963407;
}
function log1p(x) {
x = +x;
if (x < -1 || $isNaN(x)) {
return NaN;
}
if (x === 0 || x === Infinity) {
return x;
}
if (x === -1) {
return -Infinity;
}
var result = 0;
var n = 50;
if (x < 0 || x > 1) {
return log(1 + x);
}
for (var i = 1; i < n; i++) {
if ((i % 2) === 0) {
result -= pow(x, i) / i;
} else {
result += pow(x, i) / i;
}
}
return result;
}
function expm1(x) {
x = +x;
if (x === -Infinity) {
return -1;
}
if (!$isFinite(x) || x === 0) {
return x;
}
return exp(x) - 1;
}
function cosh(x) {
x = +x;
if (x === 0) {
return 1;
}
if ($isNaN(x)) {
return NaN;
}
if (!$isFinite(x)) {
return Infinity;
}
if (x < 0) {
x = -x;
}
if (x > 21) {
return exp(x) / 2;
}
return (exp(x) + exp(-x)) / 2;
}
function sinh(x) {
x = +x;
if (!$isFinite(x) || x === 0) {
return x;
}
return (exp(x) - exp(-x)) / 2;
}
function tanh(x) {
x = +x;
if (x === 0)
return x;
if (!$isFinite(x))
return sign(x);
var exp1 = exp(x);
var exp2 = exp(-x);
return (exp1 - exp2) / (exp1 + exp2);
}
function acosh(x) {
x = +x;
if (x < 1)
return NaN;
if (!$isFinite(x))
return x;
return log(x + sqrt(x + 1) * sqrt(x - 1));
}
function asinh(x) {
x = +x;
if (x === 0 || !$isFinite(x))
return x;
if (x > 0)
return log(x + sqrt(x * x + 1));
return -log(-x + sqrt(x * x + 1));
}
function atanh(x) {
x = +x;
if (x === -1) {
return -Infinity;
}
if (x === 1) {
return Infinity;
}
if (x === 0) {
return x;
}
if ($isNaN(x) || x < -1 || x > 1) {
return NaN;
}
return 0.5 * log((1 + x) / (1 - x));
}
function hypot(x, y) {
var length = arguments.length;
var args = new Array(length);
var max = 0;
for (var i = 0; i < length; i++) {
var n = arguments[i];
n = +n;
if (n === Infinity || n === -Infinity)
return Infinity;
n = abs(n);
if (n > max)
max = n;
args[i] = n;
}
if (max === 0)
max = 1;
var sum = 0;
var compensation = 0;
for (var i = 0; i < length; i++) {
var n = args[i] / max;
var summand = n * n - compensation;
var preliminary = sum + summand;
compensation = (preliminary - sum) - summand;
sum = preliminary;
}
return sqrt(sum) * max;
}
function trunc(x) {
x = +x;
if (x > 0)
return floor(x);
if (x < 0)
return ceil(x);
return x;
}
var fround,
f32;
if (typeof Float32Array === 'function') {
f32 = new Float32Array(1);
fround = function(x) {
f32[0] = Number(x);
return f32[0];
};
} else {
fround = jsFround;
}
;
function cbrt(x) {
x = +x;
if (x === 0)
return x;
var negate = x < 0;
if (negate)
x = -x;
var result = pow(x, 1 / 3);
return negate ? -result : result;
}
function polyfillMath(global) {
var Math = global.Math;
maybeAddFunctions(Math, ['acosh', acosh, 'asinh', asinh, 'atanh', atanh, 'cbrt', cbrt, 'clz32', clz32, 'cosh', cosh, 'expm1', expm1, 'fround', fround, 'hypot', hypot, 'imul', imul, 'log10', log10, 'log1p', log1p, 'log2', log2, 'sign', sign, 'sinh', sinh, 'tanh', tanh, 'trunc', trunc]);
}
registerPolyfill(polyfillMath);
return {
get clz32() {
return clz32;
},
get imul() {
return imul;
},
get sign() {
return sign;
},
get log10() {
return log10;
},
get log2() {
return log2;
},
get log1p() {
return log1p;
},
get expm1() {
return expm1;
},
get cosh() {
return cosh;
},
get sinh() {
return sinh;
},
get tanh() {
return tanh;
},
get acosh() {
return acosh;
},
get asinh() {
return asinh;
},
get atanh() {
return atanh;
},
get hypot() {
return hypot;
},
get trunc() {
return trunc;
},
get fround() {
return fround;
},
get cbrt() {
return cbrt;
},
get polyfillMath() {
return polyfillMath;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Math.js" + '');
System.registerModule("[email protected]/src/runtime/polyfills/polyfills.js", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/polyfills.js";
var polyfillAll = System.get("[email protected]/src/runtime/polyfills/utils.js").polyfillAll;
polyfillAll(Reflect.global);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfillAll(global);
};
return {};
});
System.get("[email protected]/src/runtime/polyfills/polyfills.js" + '');
|
frontend/src/Components/Page/Header/KeyboardShortcutsModal.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'Components/Modal/Modal';
import { sizes } from 'Helpers/Props';
import KeyboardShortcutsModalContentConnector from './KeyboardShortcutsModalContentConnector';
function KeyboardShortcutsModal(props) {
const {
isOpen,
onModalClose
} = props;
return (
<Modal
isOpen={isOpen}
size={sizes.SMALL}
onModalClose={onModalClose}
>
<KeyboardShortcutsModalContentConnector
onModalClose={onModalClose}
/>
</Modal>
);
}
KeyboardShortcutsModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default KeyboardShortcutsModal;
|
app/javascript/mastodon/features/hashtag_timeline/index.js | tri-star/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import ColumnSettingsContainer from './containers/column_settings_container';
import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { FormattedMessage } from 'react-intl';
import { connectHashtagStream } from '../../actions/streaming';
import { isEqual } from 'lodash';
const mapStateToProps = (state, props) => ({
hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}${props.params.local ? ':local' : ''}`, 'unread']) > 0,
});
export default @connect(mapStateToProps)
class HashtagTimeline extends React.PureComponent {
disconnects = [];
static propTypes = {
params: PropTypes.object.isRequired,
columnId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HASHTAG', { id: this.props.params.id }));
}
}
title = () => {
let title = [this.props.params.id];
if (this.additionalFor('any')) {
title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />);
}
if (this.additionalFor('all')) {
title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />);
}
if (this.additionalFor('none')) {
title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />);
}
return title;
}
additionalFor = (mode) => {
const { tags } = this.props.params;
if (tags && (tags[mode] || []).length > 0) {
return tags[mode].map(tag => tag.value).join('/');
} else {
return '';
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
_subscribe (dispatch, id, tags = {}, local) {
let any = (tags.any || []).map(tag => tag.value);
let all = (tags.all || []).map(tag => tag.value);
let none = (tags.none || []).map(tag => tag.value);
[id, ...any].map(tag => {
this.disconnects.push(dispatch(connectHashtagStream(id, tag, local, status => {
let tags = status.tags.map(tag => tag.name);
return all.filter(tag => tags.includes(tag)).length === all.length &&
none.filter(tag => tags.includes(tag)).length === 0;
})));
});
}
_unsubscribe () {
this.disconnects.map(disconnect => disconnect());
this.disconnects = [];
}
componentDidMount () {
const { dispatch } = this.props;
const { id, tags, local } = this.props.params;
this._subscribe(dispatch, id, tags, local);
dispatch(expandHashtagTimeline(id, { tags, local }));
}
componentWillReceiveProps (nextProps) {
const { dispatch, params } = this.props;
const { id, tags, local } = nextProps.params;
if (id !== params.id || !isEqual(tags, params.tags) || !isEqual(local, params.local)) {
this._unsubscribe();
this._subscribe(dispatch, id, tags, local);
dispatch(clearTimeline(`hashtag:${id}${local ? ':local' : ''}`));
dispatch(expandHashtagTimeline(id, { tags, local }));
}
}
componentWillUnmount () {
this._unsubscribe();
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { id, tags, local } = this.props.params;
this.props.dispatch(expandHashtagTimeline(id, { maxId, tags, local }));
}
render () {
const { shouldUpdateScroll, hasUnread, columnId, multiColumn } = this.props;
const { id, local } = this.props.params;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={`#${id}`}>
<ColumnHeader
icon='hashtag'
active={hasUnread}
title={this.title()}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
>
{columnId && <ColumnSettingsContainer columnId={columnId} />}
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`hashtag_timeline-${columnId}`}
timelineId={`hashtag:${id}${local ? ':local' : ''}`}
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
shouldUpdateScroll={shouldUpdateScroll}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
client/src/decorators/withViewport.js | pram/recipesearch | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
wp-content/plugins/jetpack/modules/sharedaddy/sharing.js | cybermanpy/ecommerce | /* global WPCOM_sharing_counts, Recaptcha */
var sharing_js_options;
if ( sharing_js_options && sharing_js_options.counts ) {
var WPCOMSharing = {
done_urls : [],
twitter_count : {},
get_counts : function() {
var facebookPostIds = [],
https_url, http_url, url, urls, id, service, service_url, path_ending;
if ( 'undefined' === typeof WPCOM_sharing_counts ) {
return;
}
for ( url in WPCOM_sharing_counts ) {
id = WPCOM_sharing_counts[ url ];
if ( 'undefined' !== typeof WPCOMSharing.done_urls[ id ] ) {
continue;
}
// get both the http and https version of these URLs
https_url = encodeURIComponent( url.replace( /^http:\/\//i, 'https://' ) );
http_url = encodeURIComponent( url.replace( /^https:\/\//i, 'http://' ) );
if ( jQuery( 'a[data-shared=sharing-facebook-' + id + ']' ).length ) {
facebookPostIds.push( id );
}
urls = {
twitter: [
'https://cdn.api.twitter.com/1/urls/count.json?callback=WPCOMSharing.update_twitter_count&url=' +
http_url,
'https://cdn.api.twitter.com/1/urls/count.json?callback=WPCOMSharing.update_twitter_count&url=' +
https_url
],
// LinkedIn actually gets the share count for both the http and https version automatically -- so we don't need to do extra magic
linkedin: [
window.location.protocol +
'//www.linkedin.com/countserv/count/share?format=jsonp&callback=WPCOMSharing.update_linkedin_count&url=' +
encodeURIComponent( url )
],
// Pinterest, like LinkedIn, handles share counts for both http and https
pinterest: [
window.location.protocol +
'//api.pinterest.com/v1/urls/count.json?callback=WPCOMSharing.update_pinterest_count&url=' +
encodeURIComponent( url )
]
};
for ( service in urls ) {
if ( ! jQuery( 'a[data-shared=sharing-' + service + '-' + id + ']' ).length ) {
continue;
}
while ( ( service_url = urls[ service ].pop() ) ) {
jQuery.getScript( service_url );
}
}
WPCOMSharing.done_urls[ id ] = true;
}
if ( facebookPostIds.length && ( 'WPCOM_site_ID' in window ) ) {
path_ending = window.WPCOM_jetpack ? 'jetpack-count' : 'count';
jQuery.ajax({
dataType: 'jsonp',
url: 'https://public-api.wordpress.com/rest/v1.1/sites/' + window.WPCOM_site_ID + '/sharing-buttons/facebook/' + path_ending,
jsonpCallback: 'WPCOMSharing.update_facebook_count',
data: { post_ID: facebookPostIds },
success: WPCOMSharing.update_facebook_count,
cache: true
});
}
},
// get the version of the url that was stored in the dom (sharing-$service-URL)
get_permalink: function( url ) {
var rxTrailingSlash, formattedSlashUrl;
if ( 'https:' === window.location.protocol ) {
url = url.replace( /^http:\/\//i, 'https://' );
} else {
url = url.replace( /^https:\/\//i, 'http://' );
}
// Some services (e.g. Twitter) canonicalize the URL with a trailing
// slash. We can account for this by checking whether either format
// exists as a known URL
if ( ! ( url in WPCOM_sharing_counts ) ) {
rxTrailingSlash = /\/$/,
formattedSlashUrl = rxTrailingSlash.test( url ) ?
url.replace( rxTrailingSlash, '' ) : url + '/';
if ( formattedSlashUrl in WPCOM_sharing_counts ) {
url = formattedSlashUrl;
}
}
return url;
},
update_facebook_count : function( data ) {
var index, length, post;
if ( ! data || ! data.counts ) {
return;
}
for ( index = 0, length = data.counts.length; index < length; index++ ) {
post = data.counts[ index ];
if ( ! post.post_ID || ! post.count ) {
continue;
}
WPCOMSharing.inject_share_count( 'sharing-facebook-' + post.post_ID, post.count );
}
},
update_twitter_count : function( data ) {
if ( 'number' === typeof data.count ) {
var permalink = WPCOMSharing.get_permalink( data.url );
if ( ! WPCOMSharing.twitter_count[ permalink ] ) {
WPCOMSharing.twitter_count[ permalink ] = 0;
}
WPCOMSharing.twitter_count[ permalink ] += data.count;
if ( WPCOMSharing.twitter_count[ permalink ] > 0 ) {
WPCOMSharing.inject_share_count( 'sharing-twitter-' + WPCOM_sharing_counts[ permalink ], WPCOMSharing.twitter_count[ permalink ] );
}
}
},
update_linkedin_count : function( data ) {
if ( 'undefined' !== typeof data.count && ( data.count * 1 ) > 0 ) {
WPCOMSharing.inject_share_count( 'sharing-linkedin-' + WPCOM_sharing_counts[ data.url ], data.count );
}
},
update_pinterest_count : function( data ) {
if ( 'undefined' !== typeof data.count && ( data.count * 1 ) > 0 ) {
WPCOMSharing.inject_share_count( 'sharing-pinterest-' + WPCOM_sharing_counts[ data.url ], data.count );
}
},
inject_share_count : function( id, count ) {
var $share = jQuery( 'a[data-shared=' + id + '] > span');
$share.find( '.share-count' ).remove();
$share.append( '<span class="share-count">' + WPCOMSharing.format_count( count ) + '</span>' );
},
format_count : function( count ) {
if ( count < 1000 ) {
return count;
}
if ( count >= 1000 && count < 10000 ) {
return String( count ).substring( 0, 1 ) + 'K+';
}
return '10K+';
}
};
}
(function($){
var $body, $sharing_email;
$.fn.extend( {
share_is_email: function() {
return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test( this.val() );
}
} );
$body = $( document.body ).on( 'post-load', WPCOMSharing_do );
$( document ).on( 'ready', function() {
$sharing_email = $( '#sharing_email' );
$body.append( $sharing_email );
WPCOMSharing_do();
} );
function WPCOMSharing_do() {
var $more_sharing_buttons;
WPCOMSharing.get_counts();
$more_sharing_buttons = $( '.sharedaddy a.sharing-anchor' );
$more_sharing_buttons.click( function() {
return false;
} );
$( '.sharedaddy a' ).each( function() {
if ( $( this ).attr( 'href' ) && $( this ).attr( 'href' ).indexOf( 'share=' ) !== -1 ) {
$( this ).attr( 'href', $( this ).attr( 'href' ) + '&nb=1' );
}
} );
// Show hidden buttons
// Touchscreen device: use click.
// Non-touchscreen device: use click if not already appearing due to a hover event
$more_sharing_buttons.on( 'click', function() {
var $more_sharing_button = $( this ),
$more_sharing_pane = $more_sharing_button.parents( 'div:first' ).find( '.inner' );
if ( $more_sharing_pane.is( ':animated' ) ) {
// We're in the middle of some other event's animation
return;
}
if ( true === $more_sharing_pane.data( 'justSlid' ) ) {
// We just finished some other event's animation - don't process click event so that slow-to-react-clickers don't get confused
return;
}
$sharing_email.slideUp( 200 );
$more_sharing_pane.css( {
left: $more_sharing_button.position().left + 'px',
top: $more_sharing_button.position().top + $more_sharing_button.height() + 3 + 'px'
} ).slideToggle( 200 );
} );
if ( document.ontouchstart === undefined ) {
// Non-touchscreen device: use hover/mouseout with delay
$more_sharing_buttons.hover( function() {
var $more_sharing_button = $( this ),
$more_sharing_pane = $more_sharing_button.parents( 'div:first' ).find( '.inner' ),
timer;
if ( ! $more_sharing_pane.is( ':animated' ) ) {
// Create a timer to make the area appear if the mouse hovers for a period
timer = setTimeout( function() {
var handler_item_leave, handler_item_enter, handler_original_leave, handler_original_enter, close_it;
$sharing_email.slideUp( 200 );
$more_sharing_pane.data( 'justSlid', true );
$more_sharing_pane.css( {
left: $more_sharing_button.position().left + 'px',
top: $more_sharing_button.position().top + $more_sharing_button.height() + 3 + 'px'
} ).slideDown( 200, function() {
// Mark the item as have being appeared by the hover
$more_sharing_button.data( 'hasoriginal', true ).data( 'hasitem', false );
setTimeout( function() {
$more_sharing_pane.data( 'justSlid', false );
}, 300 );
if ( $more_sharing_pane.find( '.share-google-plus-1' ).size() ) {
// The pane needs to stay open for the Google+ Button
return;
}
$more_sharing_pane.mouseleave( handler_item_leave ).mouseenter( handler_item_enter );
$more_sharing_button.mouseleave( handler_original_leave ).mouseenter( handler_original_enter );
} );
// The following handlers take care of the mouseenter/mouseleave for the share button and the share area - if both are left then we close the share area
handler_item_leave = function() {
$more_sharing_button.data( 'hasitem', false );
if ( $more_sharing_button.data( 'hasoriginal' ) === false ) {
var timer = setTimeout( close_it, 800 );
$more_sharing_button.data( 'timer2', timer );
}
};
handler_item_enter = function() {
$more_sharing_button.data( 'hasitem', true );
clearTimeout( $more_sharing_button.data( 'timer2' ) );
};
handler_original_leave = function() {
$more_sharing_button.data( 'hasoriginal', false );
if ( $more_sharing_button.data( 'hasitem' ) === false ) {
var timer = setTimeout( close_it, 800 );
$more_sharing_button.data( 'timer2', timer );
}
};
handler_original_enter = function() {
$more_sharing_button.data( 'hasoriginal', true );
clearTimeout( $more_sharing_button.data( 'timer2' ) );
};
close_it = function() {
$more_sharing_pane.data( 'justSlid', true );
$more_sharing_pane.slideUp( 200, function() {
setTimeout( function() {
$more_sharing_pane.data( 'justSlid', false );
}, 300 );
} );
// Clear all hooks
$more_sharing_button.unbind( 'mouseleave', handler_original_leave ).unbind( 'mouseenter', handler_original_enter );
$more_sharing_pane.unbind( 'mouseleave', handler_item_leave ).unbind( 'mouseenter', handler_item_leave );
return false;
};
}, 200 );
// Remember the timer so we can detect it on the mouseout
$more_sharing_button.data( 'timer', timer );
}
}, function() {
// Mouse out - remove any timer
$more_sharing_buttons.each( function() {
clearTimeout( $( this ).data( 'timer' ) );
} );
$more_sharing_buttons.data( 'timer', false );
} );
}
$( document ).click(function() {
// Click outside
// remove any timer
$more_sharing_buttons.each( function() {
clearTimeout( $( this ).data( 'timer' ) );
} );
$more_sharing_buttons.data( 'timer', false );
// slide down forcibly
$( '.sharedaddy .inner' ).slideUp();
});
// Add click functionality
$( '.sharedaddy ul' ).each( function() {
if ( 'yep' === $( this ).data( 'has-click-events' ) ) {
return;
}
$( this ).data( 'has-click-events', 'yep' );
var printUrl = function ( uniqueId, urlToPrint ) {
$( 'body:first' ).append( '<iframe style="position:fixed;top:100;left:100;height:1px;width:1px;border:none;" id="printFrame-' + uniqueId + '" name="printFrame-' + uniqueId + '" src="' + urlToPrint + '" onload="frames[\'printFrame-' + uniqueId + '\'].focus();frames[\'printFrame-' + uniqueId + '\'].print();"></iframe>' );
};
// Print button
$( this ).find( 'a.share-print' ).click( function() {
var ref = $( this ).attr( 'href' ),
do_print = function() {
if ( ref.indexOf( '#print' ) === -1 ) {
var uid = new Date().getTime();
printUrl( uid , ref );
} else {
print();
}
};
// Is the button in a dropdown?
if ( $( this ).parents( '.sharing-hidden' ).length > 0 ) {
$( this ).parents( '.inner' ).slideUp( 0, function() {
do_print();
} );
} else {
do_print();
}
return false;
} );
// Press This button
$( this ).find( 'a.share-press-this' ).click( function() {
var s = '';
if ( window.getSelection ) {
s = window.getSelection();
} else if( document.getSelection ) {
s = document.getSelection();
} else if( document.selection ) {
s = document.selection.createRange().text;
}
if ( s ) {
$( this ).attr( 'href', $( this ).attr( 'href' ) + '&sel=' + encodeURI( s ) );
}
if ( !window.open( $( this ).attr( 'href' ), 't', 'toolbar=0,resizable=1,scrollbars=1,status=1,width=720,height=570' ) ) {
document.location.href = $( this ).attr( 'href' );
}
return false;
} );
// Email button
$( 'a.share-email', this ).on( 'click', function() {
var url = $( this ).attr( 'href' ), key;
if ( $sharing_email.is( ':visible' ) ) {
$sharing_email.slideUp( 200 );
} else {
$( '.sharedaddy .inner' ).slideUp();
$( '#sharing_email .response' ).remove();
$( '#sharing_email form' ).show();
$( '#sharing_email form input[type=submit]' ).removeAttr( 'disabled' );
$( '#sharing_email form a.sharing_cancel' ).show();
key = '';
if ( $( '#recaptcha_public_key' ).length > 0 ) {
key = $( '#recaptcha_public_key' ).val();
}
// Update the recaptcha
Recaptcha.create( key, 'sharing_recaptcha', { lang : sharing_js_options.lang } );
// Show dialog
$sharing_email.css( {
left: $( this ).offset().left + 'px',
top: $( this ).offset().top + $( this ).height() + 'px'
} ).slideDown( 200 );
// Hook up other buttons
$( '#sharing_email a.sharing_cancel' ).unbind( 'click' ).click( function() {
$( '#sharing_email .errors' ).hide();
$sharing_email.slideUp( 200 );
$( '#sharing_background' ).fadeOut();
return false;
} );
// Submit validation
$( '#sharing_email input[type=submit]' ).unbind( 'click' ).click( function() {
var form = $( this ).parents( 'form' );
// Disable buttons + enable loading icon
$( this ).prop( 'disabled', true );
form.find( 'a.sharing_cancel' ).hide();
form.find( 'img.loading' ).show();
$( '#sharing_email .errors' ).hide();
$( '#sharing_email .error' ).removeClass( 'error' );
if ( ! $( '#sharing_email input[name=source_email]' ).share_is_email() ) {
$( '#sharing_email input[name=source_email]' ).addClass( 'error' );
}
if ( ! $( '#sharing_email input[name=target_email]' ).share_is_email() ) {
$( '#sharing_email input[name=target_email]' ).addClass( 'error' );
}
if ( $( '#sharing_email .error' ).length === 0 ) {
// AJAX send the form
$.ajax( {
url: url,
type: 'POST',
data: form.serialize(),
success: function( response ) {
form.find( 'img.loading' ).hide();
if ( response === '1' || response === '2' || response === '3' ) {
$( '#sharing_email .errors-' + response ).show();
form.find( 'input[type=submit]' ).removeAttr( 'disabled' );
form.find( 'a.sharing_cancel' ).show();
Recaptcha.reload();
}
else {
$( '#sharing_email form' ).hide();
$sharing_email.append( response );
$( '#sharing_email a.sharing_cancel' ).click( function() {
$sharing_email.slideUp( 200 );
$( '#sharing_background' ).fadeOut();
return false;
} );
}
}
} );
return false;
}
form.find( 'img.loading' ).hide();
form.find( 'input[type=submit]' ).removeAttr( 'disabled' );
form.find( 'a.sharing_cancel' ).show();
$( '#sharing_email .errors-1' ).show();
return false;
} );
}
return false;
} );
} );
$( 'li.share-email, li.share-custom a.sharing-anchor' ).addClass( 'share-service-visible' );
}
})( jQuery );
// Recaptcha code
/* jshint ignore:start */
var RecaptchaTemplates={};RecaptchaTemplates.VertHtml='<table id="recaptcha_table" class="recaptchatable" > <tr> <td colspan="6" class=\'recaptcha_r1_c1\'></td> </tr> <tr> <td class=\'recaptcha_r2_c1\'></td> <td colspan="4" class=\'recaptcha_image_cell\'><div id="recaptcha_image"></div></td> <td class=\'recaptcha_r2_c2\'></td> </tr> <tr> <td rowspan="6" class=\'recaptcha_r3_c1\'></td> <td colspan="4" class=\'recaptcha_r3_c2\'></td> <td rowspan="6" class=\'recaptcha_r3_c3\'></td> </tr> <tr> <td rowspan="3" class=\'recaptcha_r4_c1\' height="49"> <div class="recaptcha_input_area"> <label for="recaptcha_response_field" class="recaptcha_input_area_text"><span id="recaptcha_instructions_image" class="recaptcha_only_if_image recaptcha_only_if_no_incorrect_sol"></span><span id="recaptcha_instructions_audio" class="recaptcha_only_if_no_incorrect_sol recaptcha_only_if_audio"></span><span id="recaptcha_instructions_error" class="recaptcha_only_if_incorrect_sol"></span></label><br/> <input name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td rowspan="4" class=\'recaptcha_r4_c2\'></td> <td><a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="17" /></a></td> <td rowspan="4" class=\'recaptcha_r4_c4\'></td> </tr> <tr> <td><a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="16" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="16" alt=""/></a></td> </tr> <tr> <td><a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a></td> </tr> <tr> <td class=\'recaptcha_r7_c1\'></td> <td class=\'recaptcha_r8_c1\'></td> </tr> </table> ';RecaptchaTemplates.CleanCss=".recaptchatable td img{display:block}.recaptchatable .recaptcha_image_cell center img{height:57px}.recaptchatable .recaptcha_image_cell center{height:57px}.recaptchatable .recaptcha_image_cell{background-color:white;height:57px;padding:7px!important}.recaptchatable,#recaptcha_area tr,#recaptcha_area td,#recaptcha_area th{margin:0!important;border:0!important;border-collapse:collapse!important;vertical-align:middle!important}.recaptchatable *{margin:0;padding:0;border:0;color:black;position:static;top:auto;left:auto;right:auto;bottom:auto;text-align:left!important}.recaptchatable #recaptcha_image{margin:auto;border:1px solid #dfdfdf!important}.recaptchatable a img{border:0}.recaptchatable a,.recaptchatable a:hover{-moz-outline:none;border:0!important;padding:0!important;text-decoration:none;color:blue;background:none!important;font-weight:normal}.recaptcha_input_area{position:relative!important;background:none!important}.recaptchatable label.recaptcha_input_area_text{border:1px solid #dfdfdf!important;margin:0!important;padding:0!important;position:static!important;top:auto!important;left:auto!important;right:auto!important;bottom:auto!important}.recaptcha_theme_red label.recaptcha_input_area_text,.recaptcha_theme_white label.recaptcha_input_area_text{color:black!important}.recaptcha_theme_blackglass label.recaptcha_input_area_text{color:white!important}.recaptchatable #recaptcha_response_field{font-size:11pt}.recaptcha_theme_blackglass #recaptcha_response_field,.recaptcha_theme_white #recaptcha_response_field{border:1px solid gray}.recaptcha_theme_red #recaptcha_response_field{border:1px solid #cca940}.recaptcha_audio_cant_hear_link{font-size:7pt;color:black}.recaptchatable{line-height:1em;border:1px solid #dfdfdf!important}.recaptcha_error_text{color:red}";RecaptchaTemplates.CleanHtml='<table id="recaptcha_table" class="recaptchatable"> <tr height="73"> <td class=\'recaptcha_image_cell\' width="302"><center><div id="recaptcha_image"></div></center></td> <td style="padding: 10px 7px 7px 7px;"> <a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="18" alt="" /></a> <a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="15" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="15" alt=""/></a> <a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a> </td> <td style="padding: 18px 7px 18px 7px;"> <img id=\'recaptcha_logo\' alt="" width="71" height="36" /> </td> </tr> <tr> <td style="padding-left: 7px;"> <div class="recaptcha_input_area" style="padding-top: 2px; padding-bottom: 7px;"> <input style="border: 1px solid #3c3c3c; width: 302px;" name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td></td> <td style="padding: 4px 7px 12px 7px;"> <img id="recaptcha_tagline" width="71" height="17" /> </td> </tr> </table> ';RecaptchaTemplates.ContextHtml='<table id="recaptcha_table" class="recaptchatable"> <tr> <td colspan="6" class=\'recaptcha_r1_c1\'></td> </tr> <tr> <td class=\'recaptcha_r2_c1\'></td> <td colspan="4" class=\'recaptcha_image_cell\'><div id="recaptcha_image"></div></td> <td class=\'recaptcha_r2_c2\'></td> </tr> <tr> <td rowspan="6" class=\'recaptcha_r3_c1\'></td> <td colspan="4" class=\'recaptcha_r3_c2\'></td> <td rowspan="6" class=\'recaptcha_r3_c3\'></td> </tr> <tr> <td rowspan="3" class=\'recaptcha_r4_c1\' height="49"> <div class="recaptcha_input_area"> <label for="recaptcha_response_field" class="recaptcha_input_area_text"><span id="recaptcha_instructions_context" class="recaptcha_only_if_image recaptcha_only_if_no_incorrect_sol"></span><span id="recaptcha_instructions_audio" class="recaptcha_only_if_no_incorrect_sol recaptcha_only_if_audio"></span><span id="recaptcha_instructions_error" class="recaptcha_only_if_incorrect_sol"></span></label><br/> <input name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td rowspan="4" class=\'recaptcha_r4_c2\'></td> <td><a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="17" /></a></td> <td rowspan="4" class=\'recaptcha_r4_c4\'></td> </tr> <tr> <td><a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="16" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="16" alt=""/></a></td> </tr> <tr> <td><a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a></td> </tr> <tr> <td class=\'recaptcha_r7_c1\'></td> <td class=\'recaptcha_r8_c1\'></td> </tr> </table> ';RecaptchaTemplates.VertCss=".recaptchatable td img{display:block}.recaptchatable .recaptcha_r1_c1{background:url(IMGROOT/sprite.png) 0 -63px no-repeat;width:318px;height:9px}.recaptchatable .recaptcha_r2_c1{background:url(IMGROOT/sprite.png) -18px 0 no-repeat;width:9px;height:57px}.recaptchatable .recaptcha_r2_c2{background:url(IMGROOT/sprite.png) -27px 0 no-repeat;width:9px;height:57px}.recaptchatable .recaptcha_r3_c1{background:url(IMGROOT/sprite.png) 0 0 no-repeat;width:9px;height:63px}.recaptchatable .recaptcha_r3_c2{background:url(IMGROOT/sprite.png) -18px -57px no-repeat;width:300px;height:6px}.recaptchatable .recaptcha_r3_c3{background:url(IMGROOT/sprite.png) -9px 0 no-repeat;width:9px;height:63px}.recaptchatable .recaptcha_r4_c1{background:url(IMGROOT/sprite.png) -43px 0 no-repeat;width:171px;height:49px}.recaptchatable .recaptcha_r4_c2{background:url(IMGROOT/sprite.png) -36px 0 no-repeat;width:7px;height:57px}.recaptchatable .recaptcha_r4_c4{background:url(IMGROOT/sprite.png) -214px 0 no-repeat;width:97px;height:57px}.recaptchatable .recaptcha_r7_c1{background:url(IMGROOT/sprite.png) -43px -49px no-repeat;width:171px;height:8px}.recaptchatable .recaptcha_r8_c1{background:url(IMGROOT/sprite.png) -43px -49px no-repeat;width:25px;height:8px}.recaptchatable .recaptcha_image_cell center img{height:57px}.recaptchatable .recaptcha_image_cell center{height:57px}.recaptchatable .recaptcha_image_cell{background-color:white;height:57px}#recaptcha_area,#recaptcha_table{width:318px!important}.recaptchatable,#recaptcha_area tr,#recaptcha_area td,#recaptcha_area th{margin:0!important;border:0!important;padding:0!important;border-collapse:collapse!important;vertical-align:middle!important}.recaptchatable *{margin:0;padding:0;border:0;font-family:helvetica,sans-serif;font-size:8pt;color:black;position:static;top:auto;left:auto;right:auto;bottom:auto;text-align:left!important}.recaptchatable #recaptcha_image{margin:auto}.recaptchatable img{border:0!important;margin:0!important;padding:0!important}.recaptchatable a,.recaptchatable a:hover{-moz-outline:none;border:0!important;padding:0!important;text-decoration:none;color:blue;background:none!important;font-weight:normal}.recaptcha_input_area{position:relative!important;width:146px!important;height:45px!important;margin-left:20px!important;margin-right:5px!important;margin-top:4px!important;background:none!important}.recaptchatable label.recaptcha_input_area_text{margin:0!important;padding:0!important;position:static!important;top:auto!important;left:auto!important;right:auto!important;bottom:auto!important;background:none!important;height:auto!important;width:auto!important}.recaptcha_theme_red label.recaptcha_input_area_text,.recaptcha_theme_white label.recaptcha_input_area_text{color:black!important}.recaptcha_theme_blackglass label.recaptcha_input_area_text{color:white!important}.recaptchatable #recaptcha_response_field{width:145px!important;position:absolute!important;bottom:7px!important;padding:0!important;margin:0!important;font-size:10pt}.recaptcha_theme_blackglass #recaptcha_response_field,.recaptcha_theme_white #recaptcha_response_field{border:1px solid gray}.recaptcha_theme_red #recaptcha_response_field{border:1px solid #cca940}.recaptcha_audio_cant_hear_link{font-size:7pt;color:black}.recaptchatable{line-height:1em}#recaptcha_instructions_error{color:red!important}";var RecaptchaStr_en={visual_challenge:"Get a visual challenge",audio_challenge:"Get an audio challenge",refresh_btn:"Get a new challenge",instructions_visual:"Type the two words:",instructions_context:"Type the words in the boxes:",instructions_audio:"Type what you hear:",help_btn:"Help",play_again:"Play sound again",cant_hear_this:"Download sound as MP3",incorrect_try_again:"Incorrect. Try again."},RecaptchaStr_de={visual_challenge:"Visuelle Aufgabe generieren",audio_challenge:"Audio-Aufgabe generieren",
refresh_btn:"Neue Aufgabe generieren",instructions_visual:"Gib die 2 W\u00f6rter ein:",instructions_context:"",instructions_audio:"Gib die 8 Ziffern ein:",help_btn:"Hilfe",incorrect_try_again:"Falsch. Nochmals versuchen!"},RecaptchaStr_es={visual_challenge:"Obt\u00e9n un reto visual",audio_challenge:"Obt\u00e9n un reto audible",refresh_btn:"Obt\u00e9n un nuevo reto",instructions_visual:"Escribe las 2 palabras:",instructions_context:"",instructions_audio:"Escribe los 8 n\u00fameros:",help_btn:"Ayuda",
incorrect_try_again:"Incorrecto. Otro intento."},RecaptchaStr_fr={visual_challenge:"D\u00e9fi visuel",audio_challenge:"D\u00e9fi audio",refresh_btn:"Nouveau d\u00e9fi",instructions_visual:"Entrez les deux mots:",instructions_context:"",instructions_audio:"Entrez les huit chiffres:",help_btn:"Aide",incorrect_try_again:"Incorrect."},RecaptchaStr_nl={visual_challenge:"Test me via een afbeelding",audio_challenge:"Test me via een geluidsfragment",refresh_btn:"Nieuwe uitdaging",instructions_visual:"Type de twee woorden:",
instructions_context:"",instructions_audio:"Type de acht cijfers:",help_btn:"Help",incorrect_try_again:"Foute invoer."},RecaptchaStr_pt={visual_challenge:"Obter um desafio visual",audio_challenge:"Obter um desafio sonoro",refresh_btn:"Obter um novo desafio",instructions_visual:"Escreva as 2 palavras:",instructions_context:"",instructions_audio:"Escreva os 8 numeros:",help_btn:"Ajuda",incorrect_try_again:"Incorrecto. Tenta outra vez."},RecaptchaStr_ru={visual_challenge:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u0432\u0438\u0437\u0443\u0430\u043b\u044c\u043d\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443",
audio_challenge:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u0437\u0432\u0443\u043a\u043e\u0432\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443",refresh_btn:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u043d\u043e\u0432\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443",instructions_visual:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0434\u0432\u0430 \u0441\u043b\u043e\u0432\u0430:",instructions_context:"",instructions_audio:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0432\u043e\u0441\u0435\u043c\u044c \u0447\u0438\u0441\u0435\u043b:",
help_btn:"\u041f\u043e\u043c\u043e\u0449\u044c",incorrect_try_again:"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e."},RecaptchaStr_tr={visual_challenge:"G\u00f6rsel deneme",audio_challenge:"\u0130\u015fitsel deneme",refresh_btn:"Yeni deneme",instructions_visual:"\u0130ki kelimeyi yaz\u0131n:",instructions_context:"",instructions_audio:"Sekiz numaray\u0131 yaz\u0131n:",help_btn:"Yard\u0131m (\u0130ngilizce)",incorrect_try_again:"Yanl\u0131\u015f. Bir daha deneyin."},RecaptchaStr_it=
{visual_challenge:"Modalit\u00e0 visiva",audio_challenge:"Modalit\u00e0 auditiva",refresh_btn:"Chiedi due nuove parole",instructions_visual:"Scrivi le due parole:",instructions_context:"",instructions_audio:"Trascrivi ci\u00f2 che senti:",help_btn:"Aiuto",incorrect_try_again:"Scorretto. Riprova."},RecaptchaLangMap={en:RecaptchaStr_en,de:RecaptchaStr_de,es:RecaptchaStr_es,fr:RecaptchaStr_fr,nl:RecaptchaStr_nl,pt:RecaptchaStr_pt,ru:RecaptchaStr_ru,tr:RecaptchaStr_tr,it:RecaptchaStr_it};var RecaptchaStr=RecaptchaStr_en,RecaptchaOptions,RecaptchaDefaultOptions={tabindex:0,theme:"red",callback:null,lang:"en",custom_theme_widget:null,custom_translations:null,includeContext:false},Recaptcha={widget:null,timer_id:-1,style_set:false,theme:null,type:"image",ajax_verify_cb:null,$:function(a){return typeof a=="string"?document.getElementById(a):a},create:function(a,b,c){Recaptcha.destroy();if(b)Recaptcha.widget=Recaptcha.$(b);Recaptcha._init_options(c);Recaptcha._call_challenge(a)},destroy:function(){var a=
Recaptcha.$("recaptcha_challenge_field");a&&a.parentNode.removeChild(a);Recaptcha.timer_id!=-1&&clearInterval(Recaptcha.timer_id);Recaptcha.timer_id=-1;if(a=Recaptcha.$("recaptcha_image"))a.innerHTML="";if(Recaptcha.widget){if(Recaptcha.theme!="custom")Recaptcha.widget.innerHTML="";else Recaptcha.widget.style.display="none";Recaptcha.widget=null}},focus_response_field:function(){var a=Recaptcha.$;a=a("recaptcha_response_field");a.focus()},get_challenge:function(){if(typeof RecaptchaState=="undefined")return null;
return RecaptchaState.challenge},get_response:function(){var a=Recaptcha.$;a=a("recaptcha_response_field");if(!a)return null;return a.value},ajax_verify:function(a){Recaptcha.ajax_verify_cb=a;a=Recaptcha._get_api_server()+"/ajaxverify?c="+encodeURIComponent(Recaptcha.get_challenge())+"&response="+encodeURIComponent(Recaptcha.get_response());Recaptcha._add_script(a)},_ajax_verify_callback:function(a){Recaptcha.ajax_verify_cb(a)},_get_api_server:function(){var a=window.location.protocol,b;b=typeof _RecaptchaOverrideApiServer!=
"undefined"?_RecaptchaOverrideApiServer:"www.google.com/recaptcha/api";return a+"//"+b},_call_challenge:function(a){a=Recaptcha._get_api_server()+"/challenge?k="+a+"&ajax=1&cachestop="+Math.random();if(typeof RecaptchaOptions.extra_challenge_params!="undefined")a+="&"+RecaptchaOptions.extra_challenge_params;if(RecaptchaOptions.includeContext)a+="&includeContext=1";Recaptcha._add_script(a)},_add_script:function(a){var b=document.createElement("script");b.type="text/javascript";b.src=a;Recaptcha._get_script_area().appendChild(b)},
_get_script_area:function(){var a=document.getElementsByTagName("head");return a=!a||a.length<1?document.body:a[0]},_hash_merge:function(a){var b={};for(var c in a)for(var d in a[c])b[d]=a[c][d];if(b.theme=="context")b.includeContext=true;return b},_init_options:function(a){RecaptchaOptions=Recaptcha._hash_merge([RecaptchaDefaultOptions,a||{}])},challenge_callback:function(){Recaptcha._reset_timer();RecaptchaStr=Recaptcha._hash_merge([RecaptchaStr_en,RecaptchaLangMap[RecaptchaOptions.lang]||{},RecaptchaOptions.custom_translations||
{}]);window.addEventListener&&window.addEventListener("unload",function(){Recaptcha.destroy()},false);Recaptcha._is_ie()&&window.attachEvent&&window.attachEvent("onbeforeunload",function(){});if(navigator.userAgent.indexOf("KHTML")>0){var a=document.createElement("iframe");a.src="about:blank";a.style.height="0px";a.style.width="0px";a.style.visibility="hidden";a.style.border="none";var b=document.createTextNode("This frame prevents back/forward cache problems in Safari.");a.appendChild(b);document.body.appendChild(a)}Recaptcha._finish_widget()},
_add_css:function(a){var b=document.createElement("style");b.type="text/css";if(b.styleSheet)if(navigator.appVersion.indexOf("MSIE 5")!=-1)document.write("<style type='text/css'>"+a+"</style>");else b.styleSheet.cssText=a;else if(navigator.appVersion.indexOf("MSIE 5")!=-1)document.write("<style type='text/css'>"+a+"</style>");else{a=document.createTextNode(a);b.appendChild(a)}Recaptcha._get_script_area().appendChild(b)},_set_style:function(a){if(!Recaptcha.style_set){Recaptcha.style_set=true;Recaptcha._add_css(a+
"\n\n.recaptcha_is_showing_audio .recaptcha_only_if_image,.recaptcha_isnot_showing_audio .recaptcha_only_if_audio,.recaptcha_had_incorrect_sol .recaptcha_only_if_no_incorrect_sol,.recaptcha_nothad_incorrect_sol .recaptcha_only_if_incorrect_sol{display:none !important}")}},_init_builtin_theme:function(){var a=Recaptcha.$,b=RecaptchaStr,c=RecaptchaState,d,e;c=c.server;if(c[c.length-1]=="/")c=c.substring(0,c.length-1);var f=c+"/img/"+Recaptcha.theme;if(Recaptcha.theme=="clean"){c=RecaptchaTemplates.CleanCss;
d=RecaptchaTemplates.CleanHtml;e="png"}else{if(Recaptcha.theme=="context"){c=RecaptchaTemplates.VertCss;d=RecaptchaTemplates.ContextHtml}else{c=RecaptchaTemplates.VertCss;d=RecaptchaTemplates.VertHtml}e="gif"}c=c.replace(/IMGROOT/g,f);Recaptcha._set_style(c);Recaptcha.widget.innerHTML="<div id='recaptcha_area'>"+d+"</div>";a("recaptcha_reload").src=f+"/refresh."+e;a("recaptcha_switch_audio").src=f+"/audio."+e;a("recaptcha_switch_img").src=f+"/text."+e;a("recaptcha_whatsthis").src=f+"/help."+e;if(Recaptcha.theme==
"clean"){a("recaptcha_logo").src=f+"/logo."+e;a("recaptcha_tagline").src=f+"/tagline."+e}a("recaptcha_reload").alt=b.refresh_btn;a("recaptcha_switch_audio").alt=b.audio_challenge;a("recaptcha_switch_img").alt=b.visual_challenge;a("recaptcha_whatsthis").alt=b.help_btn;a("recaptcha_reload_btn").href="javascript:Recaptcha.reload ();";a("recaptcha_reload_btn").title=b.refresh_btn;a("recaptcha_switch_audio_btn").href="javascript:Recaptcha.switch_type('audio');";a("recaptcha_switch_audio_btn").title=b.audio_challenge;
a("recaptcha_switch_img_btn").href="javascript:Recaptcha.switch_type('image');";a("recaptcha_switch_img_btn").title=b.visual_challenge;a("recaptcha_whatsthis_btn").href=Recaptcha._get_help_link();a("recaptcha_whatsthis_btn").target="_blank";a("recaptcha_whatsthis_btn").title=b.help_btn;a("recaptcha_whatsthis_btn").onclick=function(){Recaptcha.showhelp();return false};a("recaptcha_table").className="recaptchatable recaptcha_theme_"+Recaptcha.theme;a("recaptcha_instructions_image")&&a("recaptcha_instructions_image").appendChild(document.createTextNode(b.instructions_visual));
a("recaptcha_instructions_context")&&a("recaptcha_instructions_context").appendChild(document.createTextNode(b.instructions_context));a("recaptcha_instructions_audio")&&a("recaptcha_instructions_audio").appendChild(document.createTextNode(b.instructions_audio));a("recaptcha_instructions_error")&&a("recaptcha_instructions_error").appendChild(document.createTextNode(b.incorrect_try_again))},_finish_widget:function(){var a=Recaptcha.$,b=RecaptchaState,c=RecaptchaOptions,d=c.theme;switch(d){case "red":case "white":case "blackglass":case "clean":case "custom":case "context":break;
default:d="red";break}if(!Recaptcha.theme)Recaptcha.theme=d;Recaptcha.theme!="custom"?Recaptcha._init_builtin_theme():Recaptcha._set_style("");d=document.createElement("span");d.id="recaptcha_challenge_field_holder";d.style.display="none";a("recaptcha_response_field").parentNode.insertBefore(d,a("recaptcha_response_field"));a("recaptcha_response_field").setAttribute("autocomplete","off");a("recaptcha_image").style.width="300px";a("recaptcha_image").style.height="57px";Recaptcha.should_focus=false;
Recaptcha._set_challenge(b.challenge,"image");if(c.tabindex){a("recaptcha_response_field").tabIndex=c.tabindex;if(Recaptcha.theme!="custom"){a("recaptcha_whatsthis_btn").tabIndex=c.tabindex;a("recaptcha_switch_img_btn").tabIndex=c.tabindex;a("recaptcha_switch_audio_btn").tabIndex=c.tabindex;a("recaptcha_reload_btn").tabIndex=c.tabindex}}if(Recaptcha.widget)Recaptcha.widget.style.display="";c.callback&&c.callback()},switch_type:function(a){var b=Recaptcha;b.type=a;b.reload(b.type=="audio"?"a":"v")},
reload:function(a){var b=Recaptcha,c=RecaptchaState;if(typeof a=="undefined")a="r";c=c.server+"reload?c="+c.challenge+"&k="+c.site+"&reason="+a+"&type="+b.type+"&lang="+RecaptchaOptions.lang;if(RecaptchaOptions.includeContext)c+="&includeContext=1";if(typeof RecaptchaOptions.extra_challenge_params!="undefined")c+="&"+RecaptchaOptions.extra_challenge_params;if(b.type=="audio")c+=RecaptchaOptions.audio_beta_12_08?"&audio_beta_12_08=1":"&new_audio_default=1";b.should_focus=a!="t";b._add_script(c)},finish_reload:function(a,
b){RecaptchaState.is_incorrect=false;Recaptcha._set_challenge(a,b)},_set_challenge:function(a,b){var c=Recaptcha,d=RecaptchaState,e=c.$;d.challenge=a;c.type=b;e("recaptcha_challenge_field_holder").innerHTML="<input type='hidden' name='recaptcha_challenge_field' id='recaptcha_challenge_field' value='"+d.challenge+"'/>";if(b=="audio")e("recaptcha_image").innerHTML=Recaptcha.getAudioCaptchaHtml();else if(b=="image"){var f=d.server+"image?c="+d.challenge;e("recaptcha_image").innerHTML="<img style='display:block;' height='57' width='300' src='"+
f+"'/>"}Recaptcha._css_toggle("recaptcha_had_incorrect_sol","recaptcha_nothad_incorrect_sol",d.is_incorrect);Recaptcha._css_toggle("recaptcha_is_showing_audio","recaptcha_isnot_showing_audio",b=="audio");c._clear_input();c.should_focus&&c.focus_response_field();c._reset_timer()},_reset_timer:function(){var a=RecaptchaState;clearInterval(Recaptcha.timer_id);Recaptcha.timer_id=setInterval("Recaptcha.reload('t');",(a.timeout-300)*1E3)},showhelp:function(){window.open(Recaptcha._get_help_link(),"recaptcha_popup",
"width=460,height=570,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes")},_clear_input:function(){var a=Recaptcha.$("recaptcha_response_field");a.value=""},_displayerror:function(a){var b=Recaptcha.$;b("recaptcha_image").innerHTML="";b("recaptcha_image").appendChild(document.createTextNode(a))},reloaderror:function(a){Recaptcha._displayerror(a)},_is_ie:function(){return navigator.userAgent.indexOf("MSIE")>0&&!window.opera},_css_toggle:function(a,b,c){var d=Recaptcha.widget;
if(!d)d=document.body;var e=d.className;e=e.replace(RegExp("(^|\\s+)"+a+"(\\s+|$)")," ");e=e.replace(RegExp("(^|\\s+)"+b+"(\\s+|$)")," ");e+=" "+(c?a:b);d.className=e},_get_help_link:function(){var a=RecaptchaOptions.lang;return"http://recaptcha.net/popuphelp/"+(a=="en"?"":a+".html")},playAgain:function(){var a=Recaptcha.$;a("recaptcha_image").innerHTML=Recaptcha.getAudioCaptchaHtml()},getAudioCaptchaHtml:function(){var a=Recaptcha,b=RecaptchaState,c=b.server+"image?c="+b.challenge;if(c.indexOf("https://")==
0)c="http://"+c.substring(8);b=b.server+"/img/audiocaptcha.swf?v2";a=a._is_ie()?'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="audiocaptcha" width="0" height="0" codebase="https://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="'+b+'" /><param name="quality" value="high" /><param name="bgcolor" value="#869ca7" /><param name="allowScriptAccess" value="always" /></object><br/>':'<embed src="'+b+'" quality="high" bgcolor="#869ca7" width="0" height="0" name="audiocaptcha" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"></embed> ';
c=(Recaptcha.checkFlashVer()?'<br/><a class="recaptcha_audio_cant_hear_link" href="#" onclick="Recaptcha.playAgain(); return false;">'+RecaptchaStr.play_again+"</a>":"")+'<br/><a class="recaptcha_audio_cant_hear_link" target="_blank" href="'+c+'">'+RecaptchaStr.cant_hear_this+"</a>";return a+c},gethttpwavurl:function(){var a=RecaptchaState;if(Recaptcha.type=="audio"){a=a.server+"image?c="+a.challenge;if(a.indexOf("https://")==0)a="http://"+a.substring(8);return a}return""},checkFlashVer:function(){var a=
navigator.appVersion.indexOf("MSIE")!=-1?true:false,b=navigator.appVersion.toLowerCase().indexOf("win")!=-1?true:false,c=navigator.userAgent.indexOf("Opera")!=-1?true:false,d=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){a=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";a=navigator.plugins["Shockwave Flash"+a].description;a=a.split(" ");a=a[2].split(".");d=a[0]}}else if(a&&b&&!c)try{var e=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),
f=e.GetVariable("$version");d=f.split(" ")[1].split(",")[0]}catch(g){}return d>=9},getlang:function(){return RecaptchaOptions.lang}};
/* jshint ignore:end */
|
example/src/index.js | Demi-IO/golden-type | import React from 'react';
import ReactDom from 'react-dom';
import App from './App';
ReactDom.render(<App/>, document.getElementById('root'));
|
src/components/FuelSavingsTextInput.spec.js | mikejablonski/newo-brew-web | import React from 'react';
import {shallow} from 'enzyme';
import FuelSavingsTextInput from './FuelSavingsTextInput';
describe('<FuelSavingsTextInput />', () => {
it('should be an input element', () => {
const props = {
name: 'testName',
onChange: jest.fn(),
placeholder: 'Type Here',
value: 100
};
const wrapper = shallow(<FuelSavingsTextInput {...props} />);
const actual = wrapper.type();
const expected = 'input';
expect(actual).toEqual(expected);
});
it('should handle change', () => {
const props = {
name: 'newMpg',
onChange: jest.fn(),
placeholder: 'Type Here',
value: 100
};
const wrapper = shallow(<FuelSavingsTextInput {...props} />);
const actual = wrapper.type();
const expected = 'input';
expect(actual).toEqual(expected);
expect(props.onChange).not.toBeCalled();
wrapper.simulate('change', {target: {value: 101}});
expect(props.onChange).toBeCalledWith('newMpg', 101);
});
});
|
node_modules/react-dropzone/src/index.js | EmersonAntonioDaSiilva/poc-dipol-nlc | /* eslint prefer-template: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import accepts from 'attr-accept';
import getDataTransferItems from './getDataTransferItems';
const supportMultiple = (typeof document !== 'undefined' && document && document.createElement) ?
'multiple' in document.createElement('input') :
true;
class Dropzone extends React.Component {
static onDocumentDragOver(e) {
// allow the entire document to be a drag target
e.preventDefault();
}
constructor(props, context) {
super(props, context);
this.onClick = this.onClick.bind(this);
this.onDocumentDrop = this.onDocumentDrop.bind(this);
this.onDragStart = this.onDragStart.bind(this);
this.onDragEnter = this.onDragEnter.bind(this);
this.onDragLeave = this.onDragLeave.bind(this);
this.onDragOver = this.onDragOver.bind(this);
this.onDrop = this.onDrop.bind(this);
this.onFileDialogCancel = this.onFileDialogCancel.bind(this);
this.fileAccepted = this.fileAccepted.bind(this);
this.setRef = this.setRef.bind(this);
this.isFileDialogActive = false;
this.state = {
isDragActive: false,
acceptedFiles: [],
rejectedFiles: []
};
}
componentDidMount() {
const { preventDropOnDocument } = this.props;
this.dragTargets = [];
if (preventDropOnDocument) {
document.addEventListener('dragover', Dropzone.onDocumentDragOver, false);
document.addEventListener('drop', this.onDocumentDrop, false);
}
// Tried implementing addEventListener, but didn't work out
document.body.onfocus = this.onFileDialogCancel;
}
componentWillUnmount() {
const { preventDropOnDocument } = this.props;
if (preventDropOnDocument) {
document.removeEventListener('dragover', Dropzone.onDocumentDragOver);
document.removeEventListener('drop', this.onDocumentDrop);
}
// Can be replaced with removeEventListener, if addEventListener works
document.body.onfocus = null;
}
onDocumentDrop(e) {
if (this.node.contains(e.target)) {
// if we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
return;
}
e.preventDefault();
this.dragTargets = [];
}
onDragStart(e) {
if (this.props.onDragStart) {
this.props.onDragStart.call(this, e);
}
}
onDragEnter(e) {
e.preventDefault();
// Count the dropzone and any children that are entered.
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
const allFilesAccepted = this.allFilesAccepted(getDataTransferItems(e, this.props.multiple));
this.setState({
isDragActive: allFilesAccepted,
isDragReject: !allFilesAccepted
});
if (this.props.onDragEnter) {
this.props.onDragEnter.call(this, e);
}
}
onDragOver(e) { // eslint-disable-line class-methods-use-this
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign
} catch (err) {
// continue regardless of error
}
if (this.props.onDragOver) {
this.props.onDragOver.call(this, e);
}
return false;
}
onDragLeave(e) {
e.preventDefault();
// Only deactivate once the dropzone and all children have been left.
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({
isDragActive: false,
isDragReject: false
});
if (this.props.onDragLeave) {
this.props.onDragLeave.call(this, e);
}
}
onDrop(e) {
const { onDrop, onDropAccepted, onDropRejected, multiple, disablePreview } = this.props;
const fileList = getDataTransferItems(e, multiple);
const acceptedFiles = [];
const rejectedFiles = [];
// Stop default browser behavior
e.preventDefault();
// Reset the counter along with the drag on a drop.
this.dragTargets = [];
this.isFileDialogActive = false;
fileList.forEach((file) => {
if (!disablePreview) {
try {
file.preview = window.URL.createObjectURL(file); // eslint-disable-line no-param-reassign
} catch (err) {
if (process.env.NODE_ENV !== 'production') {
console.error('Failed to generate preview for file', file, err); // eslint-disable-line no-console
}
}
}
if (this.fileAccepted(file) && this.fileMatchSize(file)) {
acceptedFiles.push(file);
} else {
rejectedFiles.push(file);
}
});
if (onDrop) {
onDrop.call(this, acceptedFiles, rejectedFiles, e);
}
if (rejectedFiles.length > 0 && onDropRejected) {
onDropRejected.call(this, rejectedFiles, e);
}
if (acceptedFiles.length > 0 && onDropAccepted) {
onDropAccepted.call(this, acceptedFiles, e);
}
// Reset drag state
this.setState({
isDragActive: false,
isDragReject: false,
acceptedFiles,
rejectedFiles
});
}
onClick(e) {
const { onClick, disableClick } = this.props;
if (!disableClick) {
e.stopPropagation();
this.open();
if (onClick) {
onClick.call(this, e);
}
}
}
onFileDialogCancel() {
// timeout will not recognize context of this method
const { onFileDialogCancel } = this.props;
const { fileInputEl } = this;
let { isFileDialogActive } = this;
// execute the timeout only if the onFileDialogCancel is defined and FileDialog
// is opened in the browser
if (onFileDialogCancel && isFileDialogActive) {
setTimeout(() => {
// Returns an object as FileList
const FileList = fileInputEl.files;
if (!FileList.length) {
isFileDialogActive = false;
onFileDialogCancel();
}
}, 300);
}
}
setRef(ref) {
this.node = ref;
}
fileAccepted(file) {
// Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
// that MIME type will always be accepted
return file.type === 'application/x-moz-file' || accepts(file, this.props.accept);
}
fileMatchSize(file) {
return file.size <= this.props.maxSize && file.size >= this.props.minSize;
}
allFilesAccepted(files) {
return files.every(this.fileAccepted);
}
/**
* Open system file upload dialog.
*
* @public
*/
open() {
this.isFileDialogActive = true;
this.fileInputEl.value = null;
this.fileInputEl.click();
}
renderChildren = (children) => {
if (typeof children === 'function') {
return children(this.state);
}
return children;
}
render() {
const {
accept,
activeClassName,
inputProps,
multiple,
name,
rejectClassName,
children,
...rest
} = this.props;
let {
activeStyle,
className,
rejectStyle,
style,
...props // eslint-disable-line prefer-const
} = rest;
const { isDragActive, isDragReject } = this.state;
className = className || '';
if (isDragActive && activeClassName) {
className += ' ' + activeClassName;
}
if (isDragReject && rejectClassName) {
className += ' ' + rejectClassName;
}
if (!className && !style && !activeStyle && !rejectStyle) {
style = {
width: 200,
height: 200,
borderWidth: 2,
borderColor: '#666',
borderStyle: 'dashed',
borderRadius: 5
};
activeStyle = {
borderStyle: 'solid',
borderColor: '#6c6',
backgroundColor: '#eee'
};
rejectStyle = {
borderStyle: 'solid',
borderColor: '#c66',
backgroundColor: '#eee'
};
}
let appliedStyle;
if (activeStyle && isDragActive) {
appliedStyle = {
...style,
...activeStyle
};
} else if (rejectStyle && isDragReject) {
appliedStyle = {
...style,
...rejectStyle
};
} else {
appliedStyle = {
...style
};
}
const inputAttributes = {
accept,
type: 'file',
style: { display: 'none' },
multiple: supportMultiple && multiple,
ref: el => this.fileInputEl = el, // eslint-disable-line
onChange: this.onDrop
};
if (name && name.length) {
inputAttributes.name = name;
}
// Remove custom properties before passing them to the wrapper div element
const customProps = [
'acceptedFiles',
'preventDropOnDocument',
'disablePreview',
'disableClick',
'onDropAccepted',
'onDropRejected',
'onFileDialogCancel',
'maxSize',
'minSize'
];
const divProps = { ...props };
customProps.forEach(prop => delete divProps[prop]);
return (
<div
className={className}
style={appliedStyle}
{...divProps/* expand user provided props first so event handlers are never overridden */}
onClick={this.onClick}
onDragStart={this.onDragStart}
onDragEnter={this.onDragEnter}
onDragOver={this.onDragOver}
onDragLeave={this.onDragLeave}
onDrop={this.onDrop}
ref={this.setRef}
>
{this.renderChildren(children)}
<input
{...inputProps/* expand user provided inputProps first so inputAttributes override them */}
{...inputAttributes}
/>
</div>
);
}
}
Dropzone.propTypes = {
/**
* Allow specific types of files. See https://github.com/okonet/attr-accept for more information.
* Keep in mind that mime type determination is not reliable accross platforms. CSV files,
* for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
* Windows. In some cases there might not be a mime type set at all.
* See: https://github.com/okonet/react-dropzone/issues/276
*/
accept: PropTypes.string,
/**
* Contents of the dropzone
*/
children: PropTypes.oneOfType([
PropTypes.node,
PropTypes.func
]),
/**
* Disallow clicking on the dropzone container to open file dialog
*/
disableClick: PropTypes.bool,
/**
* Enable/disable preview generation
*/
disablePreview: PropTypes.bool,
/**
* If false, allow dropped items to take over the current browser window
*/
preventDropOnDocument: PropTypes.bool,
/**
* Pass additional attributes to the `<input type="file"/>` tag
*/
inputProps: PropTypes.object,
/**
* Allow dropping multiple files
*/
multiple: PropTypes.bool,
/**
* `name` attribute for the input tag
*/
name: PropTypes.string,
/**
* Maximum file size
*/
maxSize: PropTypes.number,
/**
* Minimum file size
*/
minSize: PropTypes.number,
/**
* className
*/
className: PropTypes.string,
/**
* className for accepted state
*/
activeClassName: PropTypes.string,
/**
* className for rejected state
*/
rejectClassName: PropTypes.string,
/**
* CSS styles to apply
*/
style: PropTypes.object,
/**
* CSS styles to apply when drop will be accepted
*/
activeStyle: PropTypes.object,
/**
* CSS styles to apply when drop will be rejected
*/
rejectStyle: PropTypes.object,
/**
* onClick callback
* @param {Event} event
*/
onClick: PropTypes.func,
/**
* onDrop callback
*/
onDrop: PropTypes.func,
/**
* onDropAccepted callback
*/
onDropAccepted: PropTypes.func,
/**
* onDropRejected callback
*/
onDropRejected: PropTypes.func,
/**
* onDragStart callback
*/
onDragStart: PropTypes.func,
/**
* onDragEnter callback
*/
onDragEnter: PropTypes.func,
/**
* onDragOver callback
*/
onDragOver: PropTypes.func,
/**
* onDragLeave callback
*/
onDragLeave: PropTypes.func,
/**
* Provide a callback on clicking the cancel button of the file dialog
*/
onFileDialogCancel: PropTypes.func
};
Dropzone.defaultProps = {
preventDropOnDocument: true,
disablePreview: false,
disableClick: false,
multiple: true,
maxSize: Infinity,
minSize: 0
};
export default Dropzone;
|
webapp/src/components/geneOntologyRibbon/fixRibbonPlacement.js | alliance-genome/agr | import React from 'react';
// hack around margin issue in the gene-ontology-ribbon
// refer to issue: https://github.com/geneontology/ribbon/issues/13
export default function fixRibbonPlacement(RibbonComponent) {
return (props) => {
const wrapperStyle = {
position: 'relative',
height: '10em'
};
const contentStyle = {
position: 'absolute',
bottom: 0,
left: '-18pt'
};
return (
<div style={wrapperStyle}>
<div style={contentStyle}>
<RibbonComponent {...props} />
</div>
</div>
);
};
}
|
packages/wix-style-react/src/RichTextInputArea/RichTextInputArea.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import { EditorState, Editor, CompositeDecorator } from 'draft-js';
import { convertFromHTML } from 'draft-convert';
import { FontUpgradeContext } from '../FontUpgrade/context';
import { st, classes, vars } from './RichTextInputArea.st.css';
import RichTextToolbar from './Toolbar/RichTextToolbar';
import EditorUtilities from './EditorUtilities';
import { RichTextInputAreaContext } from './RichTextInputAreaContext';
import { defaultTexts } from './RichTextInputAreaTexts';
import StatusIndicator from '../StatusIndicator';
const decorator = new CompositeDecorator([
{
strategy: EditorUtilities.findLinkEntities,
component: ({ contentState, entityKey, children }) => {
const { url } = contentState.getEntity(entityKey).getData();
return (
<a
data-hook="richtextarea-link"
href={url}
className={classes.link}
target="_blank"
// Avoids a potentially serious vulnerability for '_blank' links
rel="noopener noreferrer"
>
{children}
</a>
);
},
},
]);
class RichTextInputArea extends React.PureComponent {
constructor(props) {
super(props);
const { texts: consumerTexts } = props;
this.state = {
editorState: EditorState.createEmpty(decorator),
texts: {
toolbarButtons: {
...defaultTexts.toolbarButtons,
...consumerTexts.toolbarButtons,
},
insertionForm: {
...defaultTexts.insertionForm,
...consumerTexts.insertionForm,
},
},
};
}
componentDidMount() {
const { initialValue } = this.props;
// TODO: currently it treats the value as an initial value
this._updateContentByValue(initialValue);
this.editorRef = React.createRef();
}
render() {
const {
dataHook,
className,
placeholder,
disabled,
minHeight,
maxHeight,
status,
statusMessage,
spellCheck,
} = this.props;
const isEditorEmpty = EditorUtilities.isEditorEmpty(this.state.editorState);
return (
<FontUpgradeContext.Consumer>
{({ active: isMadefor }) => (
<div
data-hook={dataHook}
className={st(
classes.root,
{
isMadefor,
hidePlaceholder: !isEditorEmpty,
disabled,
hasError: !disabled && status === 'error',
hasWarning: !disabled && status === 'warning',
},
className,
)}
// Using CSS variable instead of applying minHeight & maxHeight on each child, down to the editor's content
style={{
[vars.minHeight]: minHeight,
[vars.maxHeight]: maxHeight,
}}
>
<RichTextInputAreaContext.Provider
value={{
texts: this.state.texts,
}}
>
<RichTextToolbar
dataHook="richtextarea-toolbar"
className={classes.toolbar}
isDisabled={disabled}
editorState={this.state.editorState}
onBold={this._setEditorState}
onItalic={this._setEditorState}
onUnderline={this._setEditorState}
onLink={newEditorState => {
this._setEditorState(newEditorState, () =>
this.editorRef.current.focus(),
);
}}
onBulletedList={this._setEditorState}
onNumberedList={this._setEditorState}
/>
</RichTextInputAreaContext.Provider>
<div className={classes.editorWrapper}>
<Editor
ref={this.editorRef}
editorState={this.state.editorState}
onChange={this._setEditorState}
placeholder={placeholder}
readOnly={disabled}
spellCheck={spellCheck}
/>
{!disabled && status && (
<span className={classes.statusIndicator}>
<StatusIndicator
dataHook="richtextarea-status-indicator"
status={status}
message={statusMessage}
/>
</span>
)}
</div>
</div>
)}
</FontUpgradeContext.Consumer>
);
}
_setEditorState = (newEditorState, onStateChanged = () => {}) => {
this.setState({ editorState: newEditorState }, () => {
const { onChange = () => {} } = this.props;
const htmlText = EditorUtilities.convertToHtml(newEditorState);
const plainText = newEditorState.getCurrentContent().getPlainText();
onChange(htmlText, { plainText });
onStateChanged();
});
};
_updateContentByValue = value => {
const content = convertFromHTML({
htmlToEntity: (nodeName, node, createEntity) => {
if (nodeName === 'a') {
return createEntity('LINK', 'MUTABLE', { url: node.href });
}
},
})(value);
const updatedEditorState = EditorState.push(
this.state.editorState,
content,
);
this.setState({ editorState: updatedEditorState });
};
/** Set value to display in the editor */
setValue = value => {
this._updateContentByValue(value);
};
}
RichTextInputArea.displayName = 'RichTextInputArea';
RichTextInputArea.propTypes = {
/** A css class to be applied to the component’s root element */
className: PropTypes.string,
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** Initial value to display in the editor */
initialValue: PropTypes.string,
/** Placeholder to display in the editor */
placeholder: PropTypes.string,
/** Disables the editor and toolbar */
disabled: PropTypes.bool,
/** Displays a status indicator */
status: PropTypes.oneOf(['error', 'warning', 'loading']),
/** Text to be shown within the tooltip of the status indicator */
statusMessage: PropTypes.string,
/** Callback function for changes: `onChange(htmlText, { plainText })` */
onChange: PropTypes.func,
/** Defines a minimum height for the editor (it grows by default) */
minHeight: PropTypes.string,
/** Defines a maximum height for the editor (it grows by default) */
maxHeight: PropTypes.string,
/**
* Enables browser's spell checking.
* Doesn't affect IE.
* In Safari, autocorrects by default.
*/
spellCheck: PropTypes.bool,
/** Texts to be shown */
texts: PropTypes.shape({
toolbarButtons: PropTypes.shape({
boldButtonLabel: PropTypes.string,
italicButtonLabel: PropTypes.string,
underlineButtonLabel: PropTypes.string,
linkButtonLabel: PropTypes.string,
bulletedListButtonLabel: PropTypes.string,
numberedListButtonLabel: PropTypes.string,
}),
insertionForm: PropTypes.shape({
confirmButtonLabel: PropTypes.string,
cancelButtonLabel: PropTypes.string,
link: PropTypes.shape({
textInputPlaceholder: PropTypes.string,
urlInputPlaceholder: PropTypes.string,
}),
}),
}),
};
RichTextInputArea.defaultProps = {
initialValue: '<p/>',
texts: {},
disabled: false,
};
export default RichTextInputArea;
|
ScalingAndPerformanceSample/src/ScalingAndPerformanceSample.Web/Scripts/knockout-3.2.0.debug.js | XSockets/XSockets.Samples | /*!
* Knockout JavaScript library v3.2.0
* (c) Steven Sanderson - http://knockoutjs.com/
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
(function(){
var DEBUG=true;
(function(undefined){
// (0, eval)('this') is a robust way of getting a reference to the global object
// For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
var window = this || (0, eval)('this'),
document = window['document'],
navigator = window['navigator'],
jQueryInstance = window["jQuery"],
JSON = window["JSON"];
(function(factory) {
// Support three module loading scenarios
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
// [1] CommonJS/Node.js
var target = module['exports'] || exports; // module.exports is for Node.js
factory(target, require);
} else if (typeof define === 'function' && define['amd']) {
// [2] AMD anonymous module
define(['exports', 'require'], factory);
} else {
// [3] No module loader (plain <script> tag) - put directly in global namespace
factory(window['ko'] = {});
}
}(function(koExports, require){
// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
var ko = typeof koExports !== 'undefined' ? koExports : {};
// Google Closure Compiler helpers (used only to make the minified file smaller)
ko.exportSymbol = function(koPath, object) {
var tokens = koPath.split(".");
// In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
// At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
var target = ko;
for (var i = 0; i < tokens.length - 1; i++)
target = target[tokens[i]];
target[tokens[tokens.length - 1]] = object;
};
ko.exportProperty = function(owner, publicName, object) {
owner[publicName] = object;
};
ko.version = "3.2.0";
ko.exportSymbol('version', ko.version);
ko.utils = (function () {
function objectForEach(obj, action) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
action(prop, obj[prop]);
}
}
}
function extend(target, source) {
if (source) {
for(var prop in source) {
if(source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
}
return target;
}
function setPrototypeOf(obj, proto) {
obj.__proto__ = proto;
return obj;
}
var canSetPrototype = ({ __proto__: [] } instanceof Array);
// Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
var knownEvents = {}, knownEventTypesByEventName = {};
var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
objectForEach(knownEvents, function(eventType, knownEventsForType) {
if (knownEventsForType.length) {
for (var i = 0, j = knownEventsForType.length; i < j; i++)
knownEventTypesByEventName[knownEventsForType[i]] = eventType;
}
});
var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
// Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
// Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
// Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
// If there is a future need to detect specific versions of IE10+, we will amend this.
var ieVersion = document && (function() {
var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
// Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
while (
div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
iElems[0]
) {}
return version > 4 ? version : undefined;
}());
var isIe6 = ieVersion === 6,
isIe7 = ieVersion === 7;
function isClickOnCheckableElement(element, eventType) {
if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
if (eventType.toLowerCase() != "click") return false;
var inputType = element.type;
return (inputType == "checkbox") || (inputType == "radio");
}
return {
fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
arrayForEach: function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i], i);
},
arrayIndexOf: function (array, item) {
if (typeof Array.prototype.indexOf == "function")
return Array.prototype.indexOf.call(array, item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] === item)
return i;
return -1;
},
arrayFirst: function (array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++)
if (predicate.call(predicateOwner, array[i], i))
return array[i];
return null;
},
arrayRemoveItem: function (array, itemToRemove) {
var index = ko.utils.arrayIndexOf(array, itemToRemove);
if (index > 0) {
array.splice(index, 1);
}
else if (index === 0) {
array.shift();
}
},
arrayGetDistinctValues: function (array) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++) {
if (ko.utils.arrayIndexOf(result, array[i]) < 0)
result.push(array[i]);
}
return result;
},
arrayMap: function (array, mapping) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
result.push(mapping(array[i], i));
return result;
},
arrayFilter: function (array, predicate) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
if (predicate(array[i], i))
result.push(array[i]);
return result;
},
arrayPushAll: function (array, valuesToPush) {
if (valuesToPush instanceof Array)
array.push.apply(array, valuesToPush);
else
for (var i = 0, j = valuesToPush.length; i < j; i++)
array.push(valuesToPush[i]);
return array;
},
addOrRemoveItem: function(array, value, included) {
var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
if (existingEntryIndex < 0) {
if (included)
array.push(value);
} else {
if (!included)
array.splice(existingEntryIndex, 1);
}
},
canSetPrototype: canSetPrototype,
extend: extend,
setPrototypeOf: setPrototypeOf,
setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
objectForEach: objectForEach,
objectMap: function(source, mapping) {
if (!source)
return source;
var target = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = mapping(source[prop], prop, source);
}
}
return target;
},
emptyDomNode: function (domNode) {
while (domNode.firstChild) {
ko.removeNode(domNode.firstChild);
}
},
moveCleanedNodesToContainerElement: function(nodes) {
// Ensure it's a real array, as we're about to reparent the nodes and
// we don't want the underlying collection to change while we're doing that.
var nodesArray = ko.utils.makeArray(nodes);
var container = document.createElement('div');
for (var i = 0, j = nodesArray.length; i < j; i++) {
container.appendChild(ko.cleanNode(nodesArray[i]));
}
return container;
},
cloneNodes: function (nodesArray, shouldCleanNodes) {
for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
var clonedNode = nodesArray[i].cloneNode(true);
newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
}
return newNodesArray;
},
setDomNodeChildren: function (domNode, childNodes) {
ko.utils.emptyDomNode(domNode);
if (childNodes) {
for (var i = 0, j = childNodes.length; i < j; i++)
domNode.appendChild(childNodes[i]);
}
},
replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
if (nodesToReplaceArray.length > 0) {
var insertionPoint = nodesToReplaceArray[0];
var parent = insertionPoint.parentNode;
for (var i = 0, j = newNodesArray.length; i < j; i++)
parent.insertBefore(newNodesArray[i], insertionPoint);
for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
ko.removeNode(nodesToReplaceArray[i]);
}
}
},
fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
// Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
// them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
// new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
// leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
// So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
//
// Rules:
// [A] Any leading nodes that have been removed should be ignored
// These most likely correspond to memoization nodes that were already removed during binding
// See https://github.com/SteveSanderson/knockout/pull/440
// [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
// and include any nodes that have been inserted among the previous collection
if (continuousNodeArray.length) {
// The parent node can be a virtual element; so get the real parent node
parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
// Rule [A]
while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
continuousNodeArray.shift();
// Rule [B]
if (continuousNodeArray.length > 1) {
var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
// Replace with the actual new continuous node set
continuousNodeArray.length = 0;
while (current !== last) {
continuousNodeArray.push(current);
current = current.nextSibling;
if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
return;
}
continuousNodeArray.push(last);
}
}
return continuousNodeArray;
},
setOptionNodeSelectionState: function (optionNode, isSelected) {
// IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
if (ieVersion < 7)
optionNode.setAttribute("selected", isSelected);
else
optionNode.selected = isSelected;
},
stringTrim: function (string) {
return string === null || string === undefined ? '' :
string.trim ?
string.trim() :
string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
},
stringStartsWith: function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
},
domNodeIsContainedBy: function (node, containedByNode) {
if (node === containedByNode)
return true;
if (node.nodeType === 11)
return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
if (containedByNode.contains)
return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
if (containedByNode.compareDocumentPosition)
return (containedByNode.compareDocumentPosition(node) & 16) == 16;
while (node && node != containedByNode) {
node = node.parentNode;
}
return !!node;
},
domNodeIsAttachedToDocument: function (node) {
return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
},
anyDomNodeIsAttachedToDocument: function(nodes) {
return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
},
tagNameLower: function(element) {
// For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
// Possible future optimization: If we know it's an element from an XHTML document (not HTML),
// we don't need to do the .toLowerCase() as it will always be lower case anyway.
return element && element.tagName && element.tagName.toLowerCase();
},
registerEventHandler: function (element, eventType, handler) {
var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
if (!mustUseAttachEvent && jQueryInstance) {
jQueryInstance(element)['bind'](eventType, handler);
} else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
element.addEventListener(eventType, handler, false);
else if (typeof element.attachEvent != "undefined") {
var attachEventHandler = function (event) { handler.call(element, event); },
attachEventName = "on" + eventType;
element.attachEvent(attachEventName, attachEventHandler);
// IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
// so to avoid leaks, we have to remove them manually. See bug #856
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
element.detachEvent(attachEventName, attachEventHandler);
});
} else
throw new Error("Browser doesn't support addEventListener or attachEvent");
},
triggerEvent: function (element, eventType) {
if (!(element && element.nodeType))
throw new Error("element must be a DOM node when calling triggerEvent");
// For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
// event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
// IE doesn't change the checked state when you trigger the click event using "fireEvent".
// In both cases, we'll use the click method instead.
var useClickWorkaround = isClickOnCheckableElement(element, eventType);
if (jQueryInstance && !useClickWorkaround) {
jQueryInstance(element)['trigger'](eventType);
} else if (typeof document.createEvent == "function") {
if (typeof element.dispatchEvent == "function") {
var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
var event = document.createEvent(eventCategory);
event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
element.dispatchEvent(event);
}
else
throw new Error("The supplied element doesn't support dispatchEvent");
} else if (useClickWorkaround && element.click) {
element.click();
} else if (typeof element.fireEvent != "undefined") {
element.fireEvent("on" + eventType);
} else {
throw new Error("Browser doesn't support triggering events");
}
},
unwrapObservable: function (value) {
return ko.isObservable(value) ? value() : value;
},
peekObservable: function (value) {
return ko.isObservable(value) ? value.peek() : value;
},
toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
if (classNames) {
var cssClassNameRegex = /\S+/g,
currentClassNames = node.className.match(cssClassNameRegex) || [];
ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
});
node.className = currentClassNames.join(" ");
}
},
setTextContent: function(element, textContent) {
var value = ko.utils.unwrapObservable(textContent);
if ((value === null) || (value === undefined))
value = "";
// We need there to be exactly one child: a text node.
// If there are no children, more than one, or if it's not a text node,
// we'll clear everything and create a single text node.
var innerTextNode = ko.virtualElements.firstChild(element);
if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
} else {
innerTextNode.data = value;
}
ko.utils.forceRefresh(element);
},
setElementName: function(element, name) {
element.name = name;
// Workaround IE 6/7 issue
// - https://github.com/SteveSanderson/knockout/issues/197
// - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
if (ieVersion <= 7) {
try {
element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
}
catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
}
},
forceRefresh: function(node) {
// Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
if (ieVersion >= 9) {
// For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
var elem = node.nodeType == 1 ? node : node.parentNode;
if (elem.style)
elem.style.zoom = elem.style.zoom;
}
},
ensureSelectElementIsRenderedCorrectly: function(selectElement) {
// Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
// (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
// Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
if (ieVersion) {
var originalWidth = selectElement.style.width;
selectElement.style.width = 0;
selectElement.style.width = originalWidth;
}
},
range: function (min, max) {
min = ko.utils.unwrapObservable(min);
max = ko.utils.unwrapObservable(max);
var result = [];
for (var i = min; i <= max; i++)
result.push(i);
return result;
},
makeArray: function(arrayLikeObject) {
var result = [];
for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
result.push(arrayLikeObject[i]);
};
return result;
},
isIe6 : isIe6,
isIe7 : isIe7,
ieVersion : ieVersion,
getFormFields: function(form, fieldName) {
var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
var isMatchingField = (typeof fieldName == 'string')
? function(field) { return field.name === fieldName }
: function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
var matches = [];
for (var i = fields.length - 1; i >= 0; i--) {
if (isMatchingField(fields[i]))
matches.push(fields[i]);
};
return matches;
},
parseJson: function (jsonString) {
if (typeof jsonString == "string") {
jsonString = ko.utils.stringTrim(jsonString);
if (jsonString) {
if (JSON && JSON.parse) // Use native parsing where available
return JSON.parse(jsonString);
return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
}
}
return null;
},
stringifyJson: function (data, replacer, space) { // replacer and space are optional
if (!JSON || !JSON.stringify)
throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
},
postJson: function (urlOrForm, data, options) {
options = options || {};
var params = options['params'] || {};
var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
var url = urlOrForm;
// If we were given a form, use its 'action' URL and pick out any requested field values
if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
var originalForm = urlOrForm;
url = originalForm.action;
for (var i = includeFields.length - 1; i >= 0; i--) {
var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
for (var j = fields.length - 1; j >= 0; j--)
params[fields[j].name] = fields[j].value;
}
}
data = ko.utils.unwrapObservable(data);
var form = document.createElement("form");
form.style.display = "none";
form.action = url;
form.method = "post";
for (var key in data) {
// Since 'data' this is a model object, we include all properties including those inherited from its prototype
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
form.appendChild(input);
}
objectForEach(params, function(key, value) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = value;
form.appendChild(input);
});
document.body.appendChild(form);
options['submitter'] ? options['submitter'](form) : form.submit();
setTimeout(function () { form.parentNode.removeChild(form); }, 0);
}
}
}());
ko.exportSymbol('utils', ko.utils);
ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
ko.exportSymbol('utils.extend', ko.utils.extend);
ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
ko.exportSymbol('utils.postJson', ko.utils.postJson);
ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
ko.exportSymbol('utils.range', ko.utils.range);
ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
if (!Function.prototype['bind']) {
// Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
// In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
Function.prototype['bind'] = function (object) {
var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function () {
return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
ko.utils.domData = new (function () {
var uniqueId = 0;
var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
var dataStore = {};
function getAll(node, createIfNotFound) {
var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
if (!hasExistingDataStore) {
if (!createIfNotFound)
return undefined;
dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
dataStore[dataStoreKey] = {};
}
return dataStore[dataStoreKey];
}
return {
get: function (node, key) {
var allDataForNode = getAll(node, false);
return allDataForNode === undefined ? undefined : allDataForNode[key];
},
set: function (node, key, value) {
if (value === undefined) {
// Make sure we don't actually create a new domData key if we are actually deleting a value
if (getAll(node, false) === undefined)
return;
}
var allDataForNode = getAll(node, true);
allDataForNode[key] = value;
},
clear: function (node) {
var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
if (dataStoreKey) {
delete dataStore[dataStoreKey];
node[dataStoreKeyExpandoPropertyName] = null;
return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
}
return false;
},
nextKey: function () {
return (uniqueId++) + dataStoreKeyExpandoPropertyName;
}
};
})();
ko.exportSymbol('utils.domData', ko.utils.domData);
ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
ko.utils.domNodeDisposal = new (function () {
var domDataKey = ko.utils.domData.nextKey();
var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
function getDisposeCallbacksCollection(node, createIfNotFound) {
var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
if ((allDisposeCallbacks === undefined) && createIfNotFound) {
allDisposeCallbacks = [];
ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
}
return allDisposeCallbacks;
}
function destroyCallbacksCollection(node) {
ko.utils.domData.set(node, domDataKey, undefined);
}
function cleanSingleNode(node) {
// Run all the dispose callbacks
var callbacks = getDisposeCallbacksCollection(node, false);
if (callbacks) {
callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
for (var i = 0; i < callbacks.length; i++)
callbacks[i](node);
}
// Erase the DOM data
ko.utils.domData.clear(node);
// Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
ko.utils.domNodeDisposal["cleanExternalData"](node);
// Clear any immediate-child comment nodes, as these wouldn't have been found by
// node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
if (cleanableNodeTypesWithDescendants[node.nodeType])
cleanImmediateCommentTypeChildren(node);
}
function cleanImmediateCommentTypeChildren(nodeWithChildren) {
var child, nextChild = nodeWithChildren.firstChild;
while (child = nextChild) {
nextChild = child.nextSibling;
if (child.nodeType === 8)
cleanSingleNode(child);
}
}
return {
addDisposeCallback : function(node, callback) {
if (typeof callback != "function")
throw new Error("Callback must be a function");
getDisposeCallbacksCollection(node, true).push(callback);
},
removeDisposeCallback : function(node, callback) {
var callbacksCollection = getDisposeCallbacksCollection(node, false);
if (callbacksCollection) {
ko.utils.arrayRemoveItem(callbacksCollection, callback);
if (callbacksCollection.length == 0)
destroyCallbacksCollection(node);
}
},
cleanNode : function(node) {
// First clean this node, where applicable
if (cleanableNodeTypes[node.nodeType]) {
cleanSingleNode(node);
// ... then its descendants, where applicable
if (cleanableNodeTypesWithDescendants[node.nodeType]) {
// Clone the descendants list in case it changes during iteration
var descendants = [];
ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
for (var i = 0, j = descendants.length; i < j; i++)
cleanSingleNode(descendants[i]);
}
}
return node;
},
removeNode : function(node) {
ko.cleanNode(node);
if (node.parentNode)
node.parentNode.removeChild(node);
},
"cleanExternalData" : function (node) {
// Special support for jQuery here because it's so commonly used.
// Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
// so notify it to tear down any resources associated with the node & descendants here.
if (jQueryInstance && (typeof jQueryInstance['cleanData'] == "function"))
jQueryInstance['cleanData']([node]);
}
}
})();
ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
ko.exportSymbol('cleanNode', ko.cleanNode);
ko.exportSymbol('removeNode', ko.removeNode);
ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
(function () {
var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
function simpleHtmlParse(html) {
// Based on jQuery's "clean" function, but only accounting for table-related elements.
// If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
// Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
// a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
// This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
// (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
// Trim whitespace, otherwise indexOf won't work as expected
var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
// Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
!tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
(!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
/* anything else */ [0, "", ""];
// Go to html and back, then peel off extra wrappers
// Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
if (typeof window['innerShiv'] == "function") {
div.appendChild(window['innerShiv'](markup));
} else {
div.innerHTML = markup;
}
// Move to the right depth
while (wrap[0]--)
div = div.lastChild;
return ko.utils.makeArray(div.lastChild.childNodes);
}
function jQueryHtmlParse(html) {
// jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
if (jQueryInstance['parseHTML']) {
return jQueryInstance['parseHTML'](html) || []; // Ensure we always return an array and never null
} else {
// For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
var elems = jQueryInstance['clean']([html]);
// As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
// Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
// Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
if (elems && elems[0]) {
// Find the top-most parent element that's a direct child of a document fragment
var elem = elems[0];
while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
elem = elem.parentNode;
// ... then detach it
if (elem.parentNode)
elem.parentNode.removeChild(elem);
}
return elems;
}
}
ko.utils.parseHtmlFragment = function(html) {
return jQueryInstance ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
: simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
};
ko.utils.setHtml = function(node, html) {
ko.utils.emptyDomNode(node);
// There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
html = ko.utils.unwrapObservable(html);
if ((html !== null) && (html !== undefined)) {
if (typeof html != 'string')
html = html.toString();
// jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
// for example <tr> elements which are not normally allowed to exist on their own.
// If you've referenced jQuery we'll use that rather than duplicating its code.
if (jQueryInstance) {
jQueryInstance(node)['html'](html);
} else {
// ... otherwise, use KO's own parsing logic.
var parsedNodes = ko.utils.parseHtmlFragment(html);
for (var i = 0; i < parsedNodes.length; i++)
node.appendChild(parsedNodes[i]);
}
}
};
})();
ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
ko.memoization = (function () {
var memos = {};
function randomMax8HexChars() {
return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
}
function generateRandomId() {
return randomMax8HexChars() + randomMax8HexChars();
}
function findMemoNodes(rootNode, appendToArray) {
if (!rootNode)
return;
if (rootNode.nodeType == 8) {
var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
if (memoId != null)
appendToArray.push({ domNode: rootNode, memoId: memoId });
} else if (rootNode.nodeType == 1) {
for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
findMemoNodes(childNodes[i], appendToArray);
}
}
return {
memoize: function (callback) {
if (typeof callback != "function")
throw new Error("You can only pass a function to ko.memoization.memoize()");
var memoId = generateRandomId();
memos[memoId] = callback;
return "<!--[ko_memo:" + memoId + "]-->";
},
unmemoize: function (memoId, callbackParams) {
var callback = memos[memoId];
if (callback === undefined)
throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
try {
callback.apply(null, callbackParams || []);
return true;
}
finally { delete memos[memoId]; }
},
unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
var memos = [];
findMemoNodes(domNode, memos);
for (var i = 0, j = memos.length; i < j; i++) {
var node = memos[i].domNode;
var combinedParams = [node];
if (extraCallbackParamsArray)
ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
ko.memoization.unmemoize(memos[i].memoId, combinedParams);
node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
if (node.parentNode)
node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
}
},
parseMemoText: function (memoText) {
var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
return match ? match[1] : null;
}
};
})();
ko.exportSymbol('memoization', ko.memoization);
ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
ko.extenders = {
'throttle': function(target, timeout) {
// Throttling means two things:
// (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
// notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
target['throttleEvaluation'] = timeout;
// (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
// so the target cannot change value synchronously or faster than a certain rate
var writeTimeoutInstance = null;
return ko.dependentObservable({
'read': target,
'write': function(value) {
clearTimeout(writeTimeoutInstance);
writeTimeoutInstance = setTimeout(function() {
target(value);
}, timeout);
}
});
},
'rateLimit': function(target, options) {
var timeout, method, limitFunction;
if (typeof options == 'number') {
timeout = options;
} else {
timeout = options['timeout'];
method = options['method'];
}
limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
target.limit(function(callback) {
return limitFunction(callback, timeout);
});
},
'notify': function(target, notifyWhen) {
target["equalityComparer"] = notifyWhen == "always" ?
null : // null equalityComparer means to always notify
valuesArePrimitiveAndEqual;
}
};
var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
function valuesArePrimitiveAndEqual(a, b) {
var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
return oldValueIsPrimitive ? (a === b) : false;
}
function throttle(callback, timeout) {
var timeoutInstance;
return function () {
if (!timeoutInstance) {
timeoutInstance = setTimeout(function() {
timeoutInstance = undefined;
callback();
}, timeout);
}
};
}
function debounce(callback, timeout) {
var timeoutInstance;
return function () {
clearTimeout(timeoutInstance);
timeoutInstance = setTimeout(callback, timeout);
};
}
function applyExtenders(requestedExtenders) {
var target = this;
if (requestedExtenders) {
ko.utils.objectForEach(requestedExtenders, function(key, value) {
var extenderHandler = ko.extenders[key];
if (typeof extenderHandler == 'function') {
target = extenderHandler(target, value) || target;
}
});
}
return target;
}
ko.exportSymbol('extenders', ko.extenders);
ko.subscription = function (target, callback, disposeCallback) {
this.target = target;
this.callback = callback;
this.disposeCallback = disposeCallback;
this.isDisposed = false;
ko.exportProperty(this, 'dispose', this.dispose);
};
ko.subscription.prototype.dispose = function () {
this.isDisposed = true;
this.disposeCallback();
};
ko.subscribable = function () {
ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']);
this._subscriptions = {};
}
var defaultEvent = "change";
var ko_subscribable_fn = {
subscribe: function (callback, callbackTarget, event) {
var self = this;
event = event || defaultEvent;
var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
var subscription = new ko.subscription(self, boundCallback, function () {
ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
if (self.afterSubscriptionRemove)
self.afterSubscriptionRemove(event);
});
if (self.beforeSubscriptionAdd)
self.beforeSubscriptionAdd(event);
if (!self._subscriptions[event])
self._subscriptions[event] = [];
self._subscriptions[event].push(subscription);
return subscription;
},
"notifySubscribers": function (valueToNotify, event) {
event = event || defaultEvent;
if (this.hasSubscriptionsForEvent(event)) {
try {
ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
// In case a subscription was disposed during the arrayForEach cycle, check
// for isDisposed on each subscription before invoking its callback
if (!subscription.isDisposed)
subscription.callback(valueToNotify);
}
} finally {
ko.dependencyDetection.end(); // End suppressing dependency detection
}
}
},
limit: function(limitFunction) {
var self = this, selfIsObservable = ko.isObservable(self),
isPending, previousValue, pendingValue, beforeChange = 'beforeChange';
if (!self._origNotifySubscribers) {
self._origNotifySubscribers = self["notifySubscribers"];
self["notifySubscribers"] = function(value, event) {
if (!event || event === defaultEvent) {
self._rateLimitedChange(value);
} else if (event === beforeChange) {
self._rateLimitedBeforeChange(value);
} else {
self._origNotifySubscribers(value, event);
}
};
}
var finish = limitFunction(function() {
// If an observable provided a reference to itself, access it to get the latest value.
// This allows computed observables to delay calculating their value until needed.
if (selfIsObservable && pendingValue === self) {
pendingValue = self();
}
isPending = false;
if (self.isDifferent(previousValue, pendingValue)) {
self._origNotifySubscribers(previousValue = pendingValue);
}
});
self._rateLimitedChange = function(value) {
isPending = true;
pendingValue = value;
finish();
};
self._rateLimitedBeforeChange = function(value) {
if (!isPending) {
previousValue = value;
self._origNotifySubscribers(value, beforeChange);
}
};
},
hasSubscriptionsForEvent: function(event) {
return this._subscriptions[event] && this._subscriptions[event].length;
},
getSubscriptionsCount: function () {
var total = 0;
ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
total += subscriptions.length;
});
return total;
},
isDifferent: function(oldValue, newValue) {
return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
},
extend: applyExtenders
};
ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
// For browsers that support proto assignment, we overwrite the prototype of each
// observable instance. Since observables are functions, we need Function.prototype
// to still be in the prototype chain.
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
}
ko.subscribable['fn'] = ko_subscribable_fn;
ko.isSubscribable = function (instance) {
return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
};
ko.exportSymbol('subscribable', ko.subscribable);
ko.exportSymbol('isSubscribable', ko.isSubscribable);
ko.computedContext = ko.dependencyDetection = (function () {
var outerFrames = [],
currentFrame,
lastId = 0;
// Return a unique ID that can be assigned to an observable for dependency tracking.
// Theoretically, you could eventually overflow the number storage size, resulting
// in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
// or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
// take over 285 years to reach that number.
// Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
function getId() {
return ++lastId;
}
function begin(options) {
outerFrames.push(currentFrame);
currentFrame = options;
}
function end() {
currentFrame = outerFrames.pop();
}
return {
begin: begin,
end: end,
registerDependency: function (subscribable) {
if (currentFrame) {
if (!ko.isSubscribable(subscribable))
throw new Error("Only subscribable things can act as dependencies");
currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId()));
}
},
ignore: function (callback, callbackTarget, callbackArgs) {
try {
begin();
return callback.apply(callbackTarget, callbackArgs || []);
} finally {
end();
}
},
getDependenciesCount: function () {
if (currentFrame)
return currentFrame.computed.getDependenciesCount();
},
isInitial: function() {
if (currentFrame)
return currentFrame.isInitial;
}
};
})();
ko.exportSymbol('computedContext', ko.computedContext);
ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
ko.exportSymbol('computedContext.isSleeping', ko.computedContext.isSleeping);
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if (observable.isDifferent(_latestValue, arguments[0])) {
observable.valueWillMutate();
_latestValue = arguments[0];
if (DEBUG) observable._latestValue = _latestValue;
observable.valueHasMutated();
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return _latestValue;
}
}
ko.subscribable.call(observable);
ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
if (DEBUG) observable._latestValue = _latestValue;
observable.peek = function() { return _latestValue };
observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
ko.exportProperty(observable, 'peek', observable.peek);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
return observable;
}
ko.observable['fn'] = {
"equalityComparer": valuesArePrimitiveAndEqual
};
var protoProperty = ko.observable.protoProperty = "__ko_proto__";
ko.observable['fn'][protoProperty] = ko.observable;
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.observable constructor
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']);
}
ko.hasPrototype = function(instance, prototype) {
if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
if (instance[protoProperty] === prototype) return true;
return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
};
ko.isObservable = function (instance) {
return ko.hasPrototype(instance, ko.observable);
}
ko.isWriteableObservable = function (instance) {
// Observable
if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
return true;
// Writeable dependent observable
if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
return true;
// Anything else
return false;
}
ko.exportSymbol('observable', ko.observable);
ko.exportSymbol('isObservable', ko.isObservable);
ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
ko.exportSymbol('isWritableObservable', ko.isWriteableObservable);
ko.observableArray = function (initialValues) {
initialValues = initialValues || [];
if (typeof initialValues != 'object' || !('length' in initialValues))
throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
var result = ko.observable(initialValues);
ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
return result.extend({'trackArrayChanges':true});
};
ko.observableArray['fn'] = {
'remove': function (valueOrPredicate) {
var underlyingArray = this.peek();
var removedValues = [];
var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
for (var i = 0; i < underlyingArray.length; i++) {
var value = underlyingArray[i];
if (predicate(value)) {
if (removedValues.length === 0) {
this.valueWillMutate();
}
removedValues.push(value);
underlyingArray.splice(i, 1);
i--;
}
}
if (removedValues.length) {
this.valueHasMutated();
}
return removedValues;
},
'removeAll': function (arrayOfValues) {
// If you passed zero args, we remove everything
if (arrayOfValues === undefined) {
var underlyingArray = this.peek();
var allValues = underlyingArray.slice(0);
this.valueWillMutate();
underlyingArray.splice(0, underlyingArray.length);
this.valueHasMutated();
return allValues;
}
// If you passed an arg, we interpret it as an array of entries to remove
if (!arrayOfValues)
return [];
return this['remove'](function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
},
'destroy': function (valueOrPredicate) {
var underlyingArray = this.peek();
var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
this.valueWillMutate();
for (var i = underlyingArray.length - 1; i >= 0; i--) {
var value = underlyingArray[i];
if (predicate(value))
underlyingArray[i]["_destroy"] = true;
}
this.valueHasMutated();
},
'destroyAll': function (arrayOfValues) {
// If you passed zero args, we destroy everything
if (arrayOfValues === undefined)
return this['destroy'](function() { return true });
// If you passed an arg, we interpret it as an array of entries to destroy
if (!arrayOfValues)
return [];
return this['destroy'](function (value) {
return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
});
},
'indexOf': function (item) {
var underlyingArray = this();
return ko.utils.arrayIndexOf(underlyingArray, item);
},
'replace': function(oldItem, newItem) {
var index = this['indexOf'](oldItem);
if (index >= 0) {
this.valueWillMutate();
this.peek()[index] = newItem;
this.valueHasMutated();
}
}
};
// Populate ko.observableArray.fn with read/write functions from native arrays
// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
ko.observableArray['fn'][methodName] = function () {
// Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
// (for consistency with mutating regular observables)
var underlyingArray = this.peek();
this.valueWillMutate();
this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
this.valueHasMutated();
return methodCallResult;
};
});
// Populate ko.observableArray.fn with read-only functions from native arrays
ko.utils.arrayForEach(["slice"], function (methodName) {
ko.observableArray['fn'][methodName] = function () {
var underlyingArray = this();
return underlyingArray[methodName].apply(underlyingArray, arguments);
};
});
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.observableArray constructor
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
}
ko.exportSymbol('observableArray', ko.observableArray);
var arrayChangeEventName = 'arrayChange';
ko.extenders['trackArrayChanges'] = function(target) {
// Only modify the target observable once
if (target.cacheDiffForKnownOperation) {
return;
}
var trackingChanges = false,
cachedDiff = null,
pendingNotifications = 0,
underlyingSubscribeFunction = target.subscribe;
// Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) {
if (event === arrayChangeEventName) {
trackChanges();
}
return underlyingSubscribeFunction.apply(this, arguments);
};
function trackChanges() {
// Calling 'trackChanges' multiple times is the same as calling it once
if (trackingChanges) {
return;
}
trackingChanges = true;
// Intercept "notifySubscribers" to track how many times it was called.
var underlyingNotifySubscribersFunction = target['notifySubscribers'];
target['notifySubscribers'] = function(valueToNotify, event) {
if (!event || event === defaultEvent) {
++pendingNotifications;
}
return underlyingNotifySubscribersFunction.apply(this, arguments);
};
// Each time the array changes value, capture a clone so that on the next
// change it's possible to produce a diff
var previousContents = [].concat(target.peek() || []);
cachedDiff = null;
target.subscribe(function(currentContents) {
// Make a copy of the current contents and ensure it's an array
currentContents = [].concat(currentContents || []);
// Compute the diff and issue notifications, but only if someone is listening
if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
var changes = getChanges(previousContents, currentContents);
if (changes.length) {
target['notifySubscribers'](changes, arrayChangeEventName);
}
}
// Eliminate references to the old, removed items, so they can be GCed
previousContents = currentContents;
cachedDiff = null;
pendingNotifications = 0;
});
}
function getChanges(previousContents, currentContents) {
// We try to re-use cached diffs.
// The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
// plugin, which without this check would not be compatible with arrayChange notifications. Normally,
// notifications are issued immediately so we wouldn't be queueing up more than one.
if (!cachedDiff || pendingNotifications > 1) {
cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
}
return cachedDiff;
}
target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
// Only run if we're currently tracking changes for this observable array
// and there aren't any pending deferred notifications.
if (!trackingChanges || pendingNotifications) {
return;
}
var diff = [],
arrayLength = rawArray.length,
argsLength = args.length,
offset = 0;
function pushDiff(status, value, index) {
return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
}
switch (operationName) {
case 'push':
offset = arrayLength;
case 'unshift':
for (var index = 0; index < argsLength; index++) {
pushDiff('added', args[index], offset + index);
}
break;
case 'pop':
offset = arrayLength - 1;
case 'shift':
if (arrayLength) {
pushDiff('deleted', rawArray[offset], offset);
}
break;
case 'splice':
// Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
endAddIndex = startIndex + argsLength - 2,
endIndex = Math.max(endDeleteIndex, endAddIndex),
additions = [], deletions = [];
for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
if (index < endDeleteIndex)
deletions.push(pushDiff('deleted', rawArray[index], index));
if (index < endAddIndex)
additions.push(pushDiff('added', args[argsIndex], index));
}
ko.utils.findMovesInArrayComparison(deletions, additions);
break;
default:
return;
}
cachedDiff = diff;
};
};
ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
var _latestValue,
_needsEvaluation = true,
_isBeingEvaluated = false,
_suppressDisposalUntilDisposeWhenReturnsFalse = false,
_isDisposed = false,
readFunction = evaluatorFunctionOrOptions,
pure = false,
isSleeping = false;
if (readFunction && typeof readFunction == "object") {
// Single-parameter syntax - everything is on this "options" param
options = readFunction;
readFunction = options["read"];
} else {
// Multi-parameter syntax - construct the options according to the params passed
options = options || {};
if (!readFunction)
readFunction = options["read"];
}
if (typeof readFunction != "function")
throw new Error("Pass a function that returns the value of the ko.computed");
function addSubscriptionToDependency(subscribable, id) {
if (!_subscriptionsToDependencies[id]) {
_subscriptionsToDependencies[id] = subscribable.subscribe(evaluatePossiblyAsync);
++_dependenciesCount;
}
}
function disposeAllSubscriptionsToDependencies() {
ko.utils.objectForEach(_subscriptionsToDependencies, function (id, subscription) {
subscription.dispose();
});
_subscriptionsToDependencies = {};
}
function disposeComputed() {
disposeAllSubscriptionsToDependencies();
_dependenciesCount = 0;
_isDisposed = true;
_needsEvaluation = false;
}
function evaluatePossiblyAsync() {
var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
clearTimeout(evaluationTimeoutInstance);
evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
} else if (dependentObservable._evalRateLimited) {
dependentObservable._evalRateLimited();
} else {
evaluateImmediate();
}
}
function evaluateImmediate(suppressChangeNotification) {
if (_isBeingEvaluated) {
if (pure) {
throw Error("A 'pure' computed must not be called recursively");
}
// If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
// This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
// certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
// their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
return;
}
// Do not evaluate (and possibly capture new dependencies) if disposed
if (_isDisposed) {
return;
}
if (disposeWhen && disposeWhen()) {
// See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
dispose();
return;
}
} else {
// It just did return false, so we can stop suppressing now
_suppressDisposalUntilDisposeWhenReturnsFalse = false;
}
_isBeingEvaluated = true;
// When sleeping, recalculate the value and return.
if (isSleeping) {
try {
var dependencyTracking = {};
ko.dependencyDetection.begin({
callback: function (subscribable, id) {
if (!dependencyTracking[id]) {
dependencyTracking[id] = 1;
++_dependenciesCount;
}
},
computed: dependentObservable,
isInitial: undefined
});
_dependenciesCount = 0;
_latestValue = readFunction.call(evaluatorFunctionTarget);
} finally {
ko.dependencyDetection.end();
_isBeingEvaluated = false;
}
} else {
try {
// Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
// Then, during evaluation, we cross off any that are in fact still being used.
var disposalCandidates = _subscriptionsToDependencies, disposalCount = _dependenciesCount;
ko.dependencyDetection.begin({
callback: function(subscribable, id) {
if (!_isDisposed) {
if (disposalCount && disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
_subscriptionsToDependencies[id] = disposalCandidates[id];
++_dependenciesCount;
delete disposalCandidates[id];
--disposalCount;
} else {
// Brand new subscription - add it
addSubscriptionToDependency(subscribable, id);
}
}
},
computed: dependentObservable,
isInitial: pure ? undefined : !_dependenciesCount // If we're evaluating when there are no previous dependencies, it must be the first time
});
_subscriptionsToDependencies = {};
_dependenciesCount = 0;
try {
var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
} finally {
ko.dependencyDetection.end();
// For each subscription no longer being used, remove it from the active subscriptions list and dispose it
if (disposalCount) {
ko.utils.objectForEach(disposalCandidates, function(id, toDispose) {
toDispose.dispose();
});
}
_needsEvaluation = false;
}
if (dependentObservable.isDifferent(_latestValue, newValue)) {
dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
_latestValue = newValue;
if (DEBUG) dependentObservable._latestValue = _latestValue;
if (suppressChangeNotification !== true) { // Check for strict true value since setTimeout in Firefox passes a numeric value to the function
dependentObservable["notifySubscribers"](_latestValue);
}
}
} finally {
_isBeingEvaluated = false;
}
}
if (!_dependenciesCount)
dispose();
}
function dependentObservable() {
if (arguments.length > 0) {
if (typeof writeFunction === "function") {
// Writing a value
writeFunction.apply(evaluatorFunctionTarget, arguments);
} else {
throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
}
return this; // Permits chained assignments
} else {
// Reading the value
ko.dependencyDetection.registerDependency(dependentObservable);
if (_needsEvaluation)
evaluateImmediate(true /* suppressChangeNotification */);
return _latestValue;
}
}
function peek() {
// Peek won't re-evaluate, except to get the initial value when "deferEvaluation" is set, or while the computed is sleeping.
// Those are the only times that both of these conditions will be satisfied.
if (_needsEvaluation && !_dependenciesCount)
evaluateImmediate(true /* suppressChangeNotification */);
return _latestValue;
}
function isActive() {
return _needsEvaluation || _dependenciesCount > 0;
}
// By here, "options" is always non-null
var writeFunction = options["write"],
disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
disposeWhen = disposeWhenOption,
dispose = disposeComputed,
_subscriptionsToDependencies = {},
_dependenciesCount = 0,
evaluationTimeoutInstance = null;
if (!evaluatorFunctionTarget)
evaluatorFunctionTarget = options["owner"];
ko.subscribable.call(dependentObservable);
ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']);
dependentObservable.peek = peek;
dependentObservable.getDependenciesCount = function () { return _dependenciesCount; };
dependentObservable.hasWriteFunction = typeof options["write"] === "function";
dependentObservable.dispose = function () { dispose(); };
dependentObservable.isActive = isActive;
// Replace the limit function with one that delays evaluation as well.
var originalLimit = dependentObservable.limit;
dependentObservable.limit = function(limitFunction) {
originalLimit.call(dependentObservable, limitFunction);
dependentObservable._evalRateLimited = function() {
dependentObservable._rateLimitedBeforeChange(_latestValue);
_needsEvaluation = true; // Mark as dirty
// Pass the observable to the rate-limit code, which will access it when
// it's time to do the notification.
dependentObservable._rateLimitedChange(dependentObservable);
}
};
if (options['pure']) {
pure = true;
isSleeping = true; // Starts off sleeping; will awake on the first subscription
dependentObservable.beforeSubscriptionAdd = function () {
// If asleep, wake up the computed and evaluate to register any dependencies.
if (isSleeping) {
isSleeping = false;
evaluateImmediate(true /* suppressChangeNotification */);
}
}
dependentObservable.afterSubscriptionRemove = function () {
if (!dependentObservable.getSubscriptionsCount()) {
disposeAllSubscriptionsToDependencies();
isSleeping = _needsEvaluation = true;
}
}
} else if (options['deferEvaluation']) {
// This will force a computed with deferEvaluation to evaluate when the first subscriptions is registered.
dependentObservable.beforeSubscriptionAdd = function () {
peek();
delete dependentObservable.beforeSubscriptionAdd;
}
}
ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
// Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
if (disposeWhenNodeIsRemoved) {
// Since this computed is associated with a DOM node, and we don't want to dispose the computed
// until the DOM node is *removed* from the document (as opposed to never having been in the document),
// we'll prevent disposal until "disposeWhen" first returns false.
_suppressDisposalUntilDisposeWhenReturnsFalse = true;
// Only watch for the node's disposal if the value really is a node. It might not be,
// e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
// after first false result" behaviour even if there's no specific node to watch. This
// technique is intended for KO's internal use only and shouldn't be documented or used
// by application code, as it's likely to change in a future version of KO.
if (disposeWhenNodeIsRemoved.nodeType) {
disposeWhen = function () {
return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
};
}
}
// Evaluate, unless sleeping or deferEvaluation is true
if (!isSleeping && !options['deferEvaluation'])
evaluateImmediate();
// Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
// removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) {
dispose = function() {
ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
disposeComputed();
};
ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
}
return dependentObservable;
};
ko.isComputed = function(instance) {
return ko.hasPrototype(instance, ko.dependentObservable);
};
var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
ko.dependentObservable[protoProp] = ko.observable;
ko.dependentObservable['fn'] = {
"equalityComparer": valuesArePrimitiveAndEqual
};
ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.dependentObservable constructor
if (ko.utils.canSetPrototype) {
ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']);
}
ko.exportSymbol('dependentObservable', ko.dependentObservable);
ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
ko.exportSymbol('isComputed', ko.isComputed);
ko.pureComputed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget) {
if (typeof evaluatorFunctionOrOptions === 'function') {
return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, {'pure':true});
} else {
evaluatorFunctionOrOptions = ko.utils.extend({}, evaluatorFunctionOrOptions); // make a copy of the parameter object
evaluatorFunctionOrOptions['pure'] = true;
return ko.computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget);
}
}
ko.exportSymbol('pureComputed', ko.pureComputed);
(function() {
var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
ko.toJS = function(rootObject) {
if (arguments.length == 0)
throw new Error("When calling ko.toJS, pass the object you want to convert.");
// We just unwrap everything at every level in the object graph
return mapJsObjectGraph(rootObject, function(valueToMap) {
// Loop because an observable's value might in turn be another observable wrapper
for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
valueToMap = valueToMap();
return valueToMap;
});
};
ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
var plainJavaScriptObject = ko.toJS(rootObject);
return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
};
function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
visitedObjects = visitedObjects || new objectLookup();
rootObject = mapInputCallback(rootObject);
var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
if (!canHaveProperties)
return rootObject;
var outputProperties = rootObject instanceof Array ? [] : {};
visitedObjects.save(rootObject, outputProperties);
visitPropertiesOrArrayEntries(rootObject, function(indexer) {
var propertyValue = mapInputCallback(rootObject[indexer]);
switch (typeof propertyValue) {
case "boolean":
case "number":
case "string":
case "function":
outputProperties[indexer] = propertyValue;
break;
case "object":
case "undefined":
var previouslyMappedValue = visitedObjects.get(propertyValue);
outputProperties[indexer] = (previouslyMappedValue !== undefined)
? previouslyMappedValue
: mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
break;
}
});
return outputProperties;
}
function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
if (rootObject instanceof Array) {
for (var i = 0; i < rootObject.length; i++)
visitorCallback(i);
// For arrays, also respect toJSON property for custom mappings (fixes #278)
if (typeof rootObject['toJSON'] == 'function')
visitorCallback('toJSON');
} else {
for (var propertyName in rootObject) {
visitorCallback(propertyName);
}
}
};
function objectLookup() {
this.keys = [];
this.values = [];
};
objectLookup.prototype = {
constructor: objectLookup,
save: function(key, value) {
var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
if (existingIndex >= 0)
this.values[existingIndex] = value;
else {
this.keys.push(key);
this.values.push(value);
}
},
get: function(key) {
var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
}
};
})();
ko.exportSymbol('toJS', ko.toJS);
ko.exportSymbol('toJSON', ko.toJSON);
(function () {
var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
// Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
// are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
// that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
ko.selectExtensions = {
readValue : function(element) {
switch (ko.utils.tagNameLower(element)) {
case 'option':
if (element[hasDomDataExpandoProperty] === true)
return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
return ko.utils.ieVersion <= 7
? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
: element.value;
case 'select':
return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
default:
return element.value;
}
},
writeValue: function(element, value, allowUnset) {
switch (ko.utils.tagNameLower(element)) {
case 'option':
switch(typeof value) {
case "string":
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
delete element[hasDomDataExpandoProperty];
}
element.value = value;
break;
default:
// Store arbitrary object using DomData
ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
element[hasDomDataExpandoProperty] = true;
// Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
element.value = typeof value === "number" ? value : "";
break;
}
break;
case 'select':
if (value === "" || value === null) // A blank string or null value will select the caption
value = undefined;
var selection = -1;
for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
optionValue = ko.selectExtensions.readValue(element.options[i]);
// Include special check to handle selecting a caption with a blank string value
if (optionValue == value || (optionValue == "" && value === undefined)) {
selection = i;
break;
}
}
if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
element.selectedIndex = selection;
}
break;
default:
if ((value === null) || (value === undefined))
value = "";
element.value = value;
break;
}
}
};
})();
ko.exportSymbol('selectExtensions', ko.selectExtensions);
ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
ko.expressionRewriting = (function () {
var javaScriptReservedWords = ["true", "false", "null", "undefined"];
// Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
// This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
// This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
function getWriteableValue(expression) {
if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
return false;
var match = expression.match(javaScriptAssignmentTarget);
return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
}
// The following regular expressions will be used to split an object-literal string into tokens
// These two match strings, either with double quotes or single quotes
var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
// Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
// as a regular expression (this is handled by the parsing loop below).
stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
// These characters have special meaning to the parser and must not appear in the middle of a
// token, except as part of a string.
specials = ',"\'{}()/:[\\]',
// Match text (at least two characters) that does not contain any of the above special characters,
// although some of the special characters are allowed to start it (all but the colon and comma).
// The text can contain spaces, but leading or trailing spaces are skipped.
everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
// Match any non-space character not matched already. This will match colons and commas, since they're
// not matched by "everyThingElse", but will also match any other single character that wasn't already
// matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
oneNotSpace = '[^\\s]',
// Create the actual regular expression by or-ing the above strings. The order is important.
bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
// Match end of previous token to determine whether a slash is a division or regex.
divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
function parseObjectLiteral(objectLiteralString) {
// Trim leading and trailing spaces from the string
var str = ko.utils.stringTrim(objectLiteralString);
// Trim braces '{' surrounding the whole object literal
if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
// Split into tokens
var result = [], toks = str.match(bindingToken), key, values, depth = 0;
if (toks) {
// Append a comma so that we don't need a separate code block to deal with the last item
toks.push(',');
for (var i = 0, tok; tok = toks[i]; ++i) {
var c = tok.charCodeAt(0);
// A comma signals the end of a key/value pair if depth is zero
if (c === 44) { // ","
if (depth <= 0) {
if (key)
result.push(values ? {key: key, value: values.join('')} : {'unknown': key});
key = values = depth = 0;
continue;
}
// Simply skip the colon that separates the name and value
} else if (c === 58) { // ":"
if (!values)
continue;
// A set of slashes is initially matched as a regular expression, but could be division
} else if (c === 47 && i && tok.length > 1) { // "/"
// Look at the end of the previous token to determine if the slash is actually division
var match = toks[i-1].match(divisionLookBehind);
if (match && !keywordRegexLookBehind[match[0]]) {
// The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
str = str.substr(str.indexOf(tok) + 1);
toks = str.match(bindingToken);
toks.push(',');
i = -1;
// Continue with just the slash
tok = '/';
}
// Increment depth for parentheses, braces, and brackets so that interior commas are ignored
} else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
++depth;
} else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
--depth;
// The key must be a single token; if it's a string, trim the quotes
} else if (!key && !values) {
key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok;
continue;
}
if (values)
values.push(tok);
else
values = [tok];
}
}
return result;
}
// Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
var twoWayBindings = {};
function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
bindingOptions = bindingOptions || {};
function processKeyValue(key, val) {
var writableVal;
function callPreprocessHook(obj) {
return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
}
if (!bindingParams) {
if (!callPreprocessHook(ko['getBindingHandler'](key)))
return;
if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
// For two-way bindings, provide a write method in case the value
// isn't a writable observable.
propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
}
}
// Values are wrapped in a function so that each value can be accessed independently
if (makeValueAccessors) {
val = 'function(){return ' + val + ' }';
}
resultStrings.push("'" + key + "':" + val);
}
var resultStrings = [],
propertyAccessorResultStrings = [],
makeValueAccessors = bindingOptions['valueAccessors'],
bindingParams = bindingOptions['bindingParams'],
keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
ko.utils.arrayForEach(keyValueArray, function(keyValue) {
processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
});
if (propertyAccessorResultStrings.length)
processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
return resultStrings.join(",");
}
return {
bindingRewriteValidators: [],
twoWayBindings: twoWayBindings,
parseObjectLiteral: parseObjectLiteral,
preProcessBindings: preProcessBindings,
keyValueArrayContainsKey: function(keyValueArray, key) {
for (var i = 0; i < keyValueArray.length; i++)
if (keyValueArray[i]['key'] == key)
return true;
return false;
},
// Internal, private KO utility for updating model properties from within bindings
// property: If the property being updated is (or might be) an observable, pass it here
// If it turns out to be a writable observable, it will be written to directly
// allBindings: An object with a get method to retrieve bindings in the current execution context.
// This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
// key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
// value: The value to be written
// checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
// it is !== existing value on that writable observable
writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
if (!property || !ko.isObservable(property)) {
var propWriters = allBindings.get('_ko_property_writers');
if (propWriters && propWriters[key])
propWriters[key](value);
} else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
property(value);
}
}
};
})();
ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
// Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
// all bindings could use an official 'property writer' API without needing to declare that they might). However,
// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
// as an internal implementation detail in the short term.
// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
// public API, and we reserve the right to remove it at any time if we create a real public property writers API.
ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
(function() {
// "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
// may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
// If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
// of that virtual hierarchy
//
// The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
// without having to scatter special cases all over the binding and templating code.
// IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
// but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
// So, use node.text where available, and node.nodeValue elsewhere
var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
function isStartComment(node) {
return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}
function isEndComment(node) {
return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
}
function getVirtualChildren(startComment, allowUnbalanced) {
var currentNode = startComment;
var depth = 1;
var children = [];
while (currentNode = currentNode.nextSibling) {
if (isEndComment(currentNode)) {
depth--;
if (depth === 0)
return children;
}
children.push(currentNode);
if (isStartComment(currentNode))
depth++;
}
if (!allowUnbalanced)
throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
return null;
}
function getMatchingEndComment(startComment, allowUnbalanced) {
var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
if (allVirtualChildren) {
if (allVirtualChildren.length > 0)
return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
return startComment.nextSibling;
} else
return null; // Must have no matching end comment, and allowUnbalanced is true
}
function getUnbalancedChildTags(node) {
// e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
// from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
var childNode = node.firstChild, captureRemaining = null;
if (childNode) {
do {
if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
captureRemaining.push(childNode);
else if (isStartComment(childNode)) {
var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
childNode = matchingEndComment;
else
captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
} else if (isEndComment(childNode)) {
captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
}
} while (childNode = childNode.nextSibling);
}
return captureRemaining;
}
ko.virtualElements = {
allowedBindings: {},
childNodes: function(node) {
return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
},
emptyNode: function(node) {
if (!isStartComment(node))
ko.utils.emptyDomNode(node);
else {
var virtualChildren = ko.virtualElements.childNodes(node);
for (var i = 0, j = virtualChildren.length; i < j; i++)
ko.removeNode(virtualChildren[i]);
}
},
setDomNodeChildren: function(node, childNodes) {
if (!isStartComment(node))
ko.utils.setDomNodeChildren(node, childNodes);
else {
ko.virtualElements.emptyNode(node);
var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
for (var i = 0, j = childNodes.length; i < j; i++)
endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
}
},
prepend: function(containerNode, nodeToPrepend) {
if (!isStartComment(containerNode)) {
if (containerNode.firstChild)
containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
else
containerNode.appendChild(nodeToPrepend);
} else {
// Start comments must always have a parent and at least one following sibling (the end comment)
containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
}
},
insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
if (!insertAfterNode) {
ko.virtualElements.prepend(containerNode, nodeToInsert);
} else if (!isStartComment(containerNode)) {
// Insert after insertion point
if (insertAfterNode.nextSibling)
containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
else
containerNode.appendChild(nodeToInsert);
} else {
// Children of start comments must always have a parent and at least one following sibling (the end comment)
containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
}
},
firstChild: function(node) {
if (!isStartComment(node))
return node.firstChild;
if (!node.nextSibling || isEndComment(node.nextSibling))
return null;
return node.nextSibling;
},
nextSibling: function(node) {
if (isStartComment(node))
node = getMatchingEndComment(node);
if (node.nextSibling && isEndComment(node.nextSibling))
return null;
return node.nextSibling;
},
hasBindingValue: isStartComment,
virtualNodeBindingValue: function(node) {
var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
return regexMatch ? regexMatch[1] : null;
},
normaliseVirtualElementDomStructure: function(elementVerified) {
// Workaround for https://github.com/SteveSanderson/knockout/issues/155
// (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
// that are direct descendants of <ul> into the preceding <li>)
if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
return;
// Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
// must be intended to appear *after* that child, so move them there.
var childNode = elementVerified.firstChild;
if (childNode) {
do {
if (childNode.nodeType === 1) {
var unbalancedTags = getUnbalancedChildTags(childNode);
if (unbalancedTags) {
// Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
var nodeToInsertBefore = childNode.nextSibling;
for (var i = 0; i < unbalancedTags.length; i++) {
if (nodeToInsertBefore)
elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
else
elementVerified.appendChild(unbalancedTags[i]);
}
}
}
} while (childNode = childNode.nextSibling);
}
}
};
})();
ko.exportSymbol('virtualElements', ko.virtualElements);
ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
(function() {
var defaultBindingAttributeName = "data-bind";
ko.bindingProvider = function() {
this.bindingCache = {};
};
ko.utils.extend(ko.bindingProvider.prototype, {
'nodeHasBindings': function(node) {
switch (node.nodeType) {
case 1: // Element
return node.getAttribute(defaultBindingAttributeName) != null
|| ko.components['getComponentNameForNode'](node);
case 8: // Comment node
return ko.virtualElements.hasBindingValue(node);
default: return false;
}
},
'getBindings': function(node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext),
parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ false);
},
'getBindingAccessors': function(node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext),
parsedBindings = bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, { 'valueAccessors': true }) : null;
return ko.components.addBindingsForCustomElement(parsedBindings, node, bindingContext, /* valueAccessors */ true);
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'getBindingsString': function(node, bindingContext) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName); // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
default: return null;
}
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'parseBindingsString': function(bindingsString, bindingContext, node, options) {
try {
var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
return bindingFunction(bindingContext, node);
} catch (ex) {
ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
throw ex;
}
}
});
ko.bindingProvider['instance'] = new ko.bindingProvider();
function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
return cache[cacheKey]
|| (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
}
function createBindingsStringEvaluator(bindingsString, options) {
// Build the source for a function that evaluates "expression"
// For each scope variable, add an extra level of "with" nesting
// Example result: with(sc1) { with(sc0) { return (expression) } }
var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
return new Function("$context", "$element", functionBody);
}
})();
ko.exportSymbol('bindingProvider', ko.bindingProvider);
(function () {
ko.bindingHandlers = {};
// The following element types will not be recursed into during binding. In the future, we
// may consider adding <template> to this list, because such elements' contents are always
// intended to be bound in a different context from where they appear in the document.
var bindingDoesNotRecurseIntoElementTypes = {
// Don't want bindings that operate on text nodes to mutate <script> contents,
// because it's unexpected and a potential XSS issue
'script': true
};
// Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
ko['getBindingHandler'] = function(bindingKey) {
return ko.bindingHandlers[bindingKey];
};
// The ko.bindingContext constructor is only called directly to create the root context. For child
// contexts, use bindingContext.createChildContext or bindingContext.extend.
ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any obsevables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
ko.utils.extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
// During the first execution, "subscribable" isn't set, so don't bother doing the update then.
if (subscribable) {
self._subscribable = subscribable;
}
} else {
self['$parents'] = [];
self['$root'] = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self['ko'] = ko;
}
self['$rawData'] = dataItemOrObservable;
self['$data'] = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self['$data'];
}
function disposeWhen() {
return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
}
var self = this,
isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
nodes,
subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable['equalityComparer'] = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function(node) {
nodes.push(node);
ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
ko.utils.arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
}
// Extend the binding context hierarchy with a new view model object. If the parent context is watching
// any obsevables, the new child context will automatically get a dependency on the parent context.
// But this does not mean that the $data value of the child context will also get updated. If the child
// view model also depends on the parent view model, you must provide a function that returns the correct
// view model on each update.
ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
// Extend the context hierarchy by setting the appropriate pointers
self['$parentContext'] = parentContext;
self['$parent'] = parentContext['$data'];
self['$parents'] = (parentContext['$parents'] || []).slice(0);
self['$parents'].unshift(self['$parent']);
if (extendCallback)
extendCallback(self);
});
};
// Extend the binding context with new custom properties. This doesn't change the context hierarchy.
// Similarly to "child" contexts, provide a function here to make sure that the correct values are set
// when an observable view model is updated.
ko.bindingContext.prototype['extend'] = function(properties) {
// If the parent context references an observable view model, "_subscribable" will always be the
// latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
// This "child" context doesn't directly track a parent observable view model,
// so we need to manually set the $rawData value to match the parent.
self['$rawData'] = parentContext['$rawData'];
ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
});
};
// Returns the valueAccesor function for a binding value
function makeValueAccessor(value) {
return function() {
return value;
};
}
// Returns the value of a valueAccessor function
function evaluateValueAccessor(valueAccessor) {
return valueAccessor();
}
// Given a function that returns bindings, create and return a new object that contains
// binding value-accessors functions. Each accessor function calls the original function
// so that it always gets the latest value and all dependencies are captured. This is used
// by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
function makeAccessorsFromFunction(callback) {
return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
return function() {
return callback()[key];
};
});
}
// Given a bindings function or object, create and return a new object that contains
// binding value-accessors functions. This is used by ko.applyBindingsToNode.
function makeBindingAccessors(bindings, context, node) {
if (typeof bindings === 'function') {
return makeAccessorsFromFunction(bindings.bind(null, context, node));
} else {
return ko.utils.objectMap(bindings, makeValueAccessor);
}
}
// This function is used if the binding provider doesn't include a getBindingAccessors function.
// It must be called with 'this' set to the provider instance.
function getBindingsAndMakeAccessors(node, context) {
return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
}
function validateThatBindingIsAllowedForVirtualElements(bindingName) {
var validator = ko.virtualElements.allowedBindings[bindingName];
if (!validator)
throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
}
function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
var currentChild,
nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
provider = ko.bindingProvider['instance'],
preprocessNode = provider['preprocessNode'];
// Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
// possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
// implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
// trigger insertion of <template> contents at that point in the document.
if (preprocessNode) {
while (currentChild = nextInQueue) {
nextInQueue = ko.virtualElements.nextSibling(currentChild);
preprocessNode.call(provider, currentChild);
}
// Reset nextInQueue for the next loop
nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
}
while (currentChild = nextInQueue) {
// Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
nextInQueue = ko.virtualElements.nextSibling(currentChild);
applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
}
}
function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
var shouldBindDescendants = true;
// Perf optimisation: Apply bindings only if...
// (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
// Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
// (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
var isElement = (nodeVerified.nodeType === 1);
if (isElement) // Workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
|| ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
if (shouldApplyBindings)
shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
// We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
// * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
// hence bindingContextsMayDifferFromDomParentElement is false
// * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
// skip over any number of intermediate virtual elements, any of which might define a custom binding context,
// hence bindingContextsMayDifferFromDomParentElement is true
applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
}
}
var boundElementDomDataKey = ko.utils.domData.nextKey();
function topologicalSortBindings(bindings) {
// Depth-first sort
var result = [], // The list of key/handler pairs that we will return
bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
if (!bindingsConsidered[bindingKey]) {
var binding = ko['getBindingHandler'](bindingKey);
if (binding) {
// First add dependencies (if any) of the current binding
if (binding['after']) {
cyclicDependencyStack.push(bindingKey);
ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
if (bindings[bindingDependencyKey]) {
if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
} else {
pushBinding(bindingDependencyKey);
}
}
});
cyclicDependencyStack.length--;
}
// Next add the current binding
result.push({ key: bindingKey, handler: binding });
}
bindingsConsidered[bindingKey] = true;
}
});
return result;
}
function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
// Prevent multiple applyBindings calls for the same node, except when a binding value is specified
var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
if (!sourceBindings) {
if (alreadyBound) {
throw Error("You cannot apply bindings multiple times to the same element.");
}
ko.utils.domData.set(node, boundElementDomDataKey, true);
}
// Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
// we can easily recover it just by scanning up the node's ancestors in the DOM
// (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
ko.storedBindingContextForNode(node, bindingContext);
// Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
var bindings;
if (sourceBindings && typeof sourceBindings !== 'function') {
bindings = sourceBindings;
} else {
var provider = ko.bindingProvider['instance'],
getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
// Get the binding from the provider within a computed observable so that we can update the bindings whenever
// the binding context is updated or if the binding provider accesses observables.
var bindingsUpdater = ko.dependentObservable(
function() {
bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
// Register a dependency on the binding context to support obsevable view models.
if (bindings && bindingContext._subscribable)
bindingContext._subscribable();
return bindings;
},
null, { disposeWhenNodeIsRemoved: node }
);
if (!bindings || !bindingsUpdater.isActive())
bindingsUpdater = null;
}
var bindingHandlerThatControlsDescendantBindings;
if (bindings) {
// Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
// context update), just return the value accessor from the binding. Otherwise, return a function that always gets
// the latest binding value and registers a dependency on the binding updater.
var getValueAccessor = bindingsUpdater
? function(bindingKey) {
return function() {
return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
};
} : function(bindingKey) {
return bindings[bindingKey];
};
// Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
function allBindings() {
return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
}
// The following is the 3.x allBindings API
allBindings['get'] = function(key) {
return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
};
allBindings['has'] = function(key) {
return key in bindings;
};
// First put the bindings into the right order
var orderedBindings = topologicalSortBindings(bindings);
// Go through the sorted bindings, calling init and update for each
ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
// Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
// so bindingKeyAndHandler.handler will always be nonnull.
var handlerInitFn = bindingKeyAndHandler.handler["init"],
handlerUpdateFn = bindingKeyAndHandler.handler["update"],
bindingKey = bindingKeyAndHandler.key;
if (node.nodeType === 8) {
validateThatBindingIsAllowedForVirtualElements(bindingKey);
}
try {
// Run init, ignoring any dependencies
if (typeof handlerInitFn == "function") {
ko.dependencyDetection.ignore(function() {
var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
// If this binding handler claims to control descendant bindings, make a note of this
if (initResult && initResult['controlsDescendantBindings']) {
if (bindingHandlerThatControlsDescendantBindings !== undefined)
throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
bindingHandlerThatControlsDescendantBindings = bindingKey;
}
});
}
// Run update in its own computed wrapper
if (typeof handlerUpdateFn == "function") {
ko.dependentObservable(
function() {
handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
},
null,
{ disposeWhenNodeIsRemoved: node }
);
}
} catch (ex) {
ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
throw ex;
}
});
}
return {
'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
};
};
var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
ko.storedBindingContextForNode = function (node, bindingContext) {
if (arguments.length == 2) {
ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
if (bindingContext._subscribable)
bindingContext._subscribable._addNode(node);
} else {
return ko.utils.domData.get(node, storedBindingContextDomDataKey);
}
}
function getBindingContext(viewModelOrBindingContext) {
return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
? viewModelOrBindingContext
: new ko.bindingContext(viewModelOrBindingContext);
}
ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(node);
return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
};
ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
var context = getBindingContext(viewModelOrBindingContext);
return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
};
ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};
ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
// If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
if (!jQueryInstance && window['jQuery']) {
jQueryInstance = window['jQuery'];
}
if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};
// Retrieving binding context from arbitrary nodes
ko.contextFor = function(node) {
// We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
switch (node.nodeType) {
case 1:
case 8:
var context = ko.storedBindingContextForNode(node);
if (context) return context;
if (node.parentNode) return ko.contextFor(node.parentNode);
break;
}
return undefined;
};
ko.dataFor = function(node) {
var context = ko.contextFor(node);
return context ? context['$data'] : undefined;
};
ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
ko.exportSymbol('applyBindings', ko.applyBindings);
ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
ko.exportSymbol('contextFor', ko.contextFor);
ko.exportSymbol('dataFor', ko.dataFor);
})();
(function(undefined) {
var loadingSubscribablesCache = {}, // Tracks component loads that are currently in flight
loadedDefinitionsCache = {}; // Tracks component loads that have already completed
ko.components = {
get: function(componentName, callback) {
var cachedDefinition = getObjectOwnProperty(loadedDefinitionsCache, componentName);
if (cachedDefinition) {
// It's already loaded and cached. Reuse the same definition object.
// Note that for API consistency, even cache hits complete asynchronously.
setTimeout(function() { callback(cachedDefinition) }, 0);
} else {
// Join the loading process that is already underway, or start a new one.
loadComponentAndNotify(componentName, callback);
}
},
clearCachedDefinition: function(componentName) {
delete loadedDefinitionsCache[componentName];
},
_getFirstResultFromLoaders: getFirstResultFromLoaders
};
function getObjectOwnProperty(obj, propName) {
return obj.hasOwnProperty(propName) ? obj[propName] : undefined;
}
function loadComponentAndNotify(componentName, callback) {
var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
completedAsync;
if (!subscribable) {
// It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
beginLoadingComponent(componentName, function(definition) {
loadedDefinitionsCache[componentName] = definition;
delete loadingSubscribablesCache[componentName];
// For API consistency, all loads complete asynchronously. However we want to avoid
// adding an extra setTimeout if it's unnecessary (i.e., the completion is already
// async) since setTimeout(..., 0) still takes about 16ms or more on most browsers.
if (completedAsync) {
subscribable['notifySubscribers'](definition);
} else {
setTimeout(function() {
subscribable['notifySubscribers'](definition);
}, 0);
}
});
completedAsync = true;
}
subscribable.subscribe(callback);
}
function beginLoadingComponent(componentName, callback) {
getFirstResultFromLoaders('getConfig', [componentName], function(config) {
if (config) {
// We have a config, so now load its definition
getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
callback(definition);
});
} else {
// The component has no config - it's unknown to all the loaders.
// Note that this is not an error (e.g., a module loading error) - that would abort the
// process and this callback would not run. For this callback to run, all loaders must
// have confirmed they don't know about this component.
callback(null);
}
});
}
function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
// On the first call in the stack, start with the full set of loaders
if (!candidateLoaders) {
candidateLoaders = ko.components['loaders'].slice(0); // Use a copy, because we'll be mutating this array
}
// Try the next candidate
var currentCandidateLoader = candidateLoaders.shift();
if (currentCandidateLoader) {
var methodInstance = currentCandidateLoader[methodName];
if (methodInstance) {
var wasAborted = false,
synchronousReturnValue = methodInstance.apply(currentCandidateLoader, argsExceptCallback.concat(function(result) {
if (wasAborted) {
callback(null);
} else if (result !== null) {
// This candidate returned a value. Use it.
callback(result);
} else {
// Try the next candidate
getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
}
}));
// Currently, loaders may not return anything synchronously. This leaves open the possibility
// that we'll extend the API to support synchronous return values in the future. It won't be
// a breaking change, because currently no loader is allowed to return anything except undefined.
if (synchronousReturnValue !== undefined) {
wasAborted = true;
// Method to suppress exceptions will remain undocumented. This is only to keep
// KO's specs running tidily, since we can observe the loading got aborted without
// having exceptions cluttering up the console too.
if (!currentCandidateLoader['suppressLoaderExceptions']) {
throw new Error('Component loaders must supply values by invoking the callback, not by returning values synchronously.');
}
}
} else {
// This candidate doesn't have the relevant handler. Synchronously move on to the next one.
getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders);
}
} else {
// No candidates returned a value
callback(null);
}
}
// Reference the loaders via string name so it's possible for developers
// to replace the whole array by assigning to ko.components.loaders
ko.components['loaders'] = [];
ko.exportSymbol('components', ko.components);
ko.exportSymbol('components.get', ko.components.get);
ko.exportSymbol('components.clearCachedDefinition', ko.components.clearCachedDefinition);
})();
(function(undefined) {
// The default loader is responsible for two things:
// 1. Maintaining the default in-memory registry of component configuration objects
// (i.e., the thing you're writing to when you call ko.components.register(someName, ...))
// 2. Answering requests for components by fetching configuration objects
// from that default in-memory registry and resolving them into standard
// component definition objects (of the form { createViewModel: ..., template: ... })
// Custom loaders may override either of these facilities, i.e.,
// 1. To supply configuration objects from some other source (e.g., conventions)
// 2. Or, to resolve configuration objects by loading viewmodels/templates via arbitrary logic.
var defaultConfigRegistry = {};
ko.components.register = function(componentName, config) {
if (!config) {
throw new Error('Invalid configuration for ' + componentName);
}
if (ko.components.isRegistered(componentName)) {
throw new Error('Component ' + componentName + ' is already registered');
}
defaultConfigRegistry[componentName] = config;
}
ko.components.isRegistered = function(componentName) {
return componentName in defaultConfigRegistry;
}
ko.components.unregister = function(componentName) {
delete defaultConfigRegistry[componentName];
ko.components.clearCachedDefinition(componentName);
}
ko.components.defaultLoader = {
'getConfig': function(componentName, callback) {
var result = defaultConfigRegistry.hasOwnProperty(componentName)
? defaultConfigRegistry[componentName]
: null;
callback(result);
},
'loadComponent': function(componentName, config, callback) {
var errorCallback = makeErrorCallback(componentName);
possiblyGetConfigFromAmd(errorCallback, config, function(loadedConfig) {
resolveConfig(componentName, errorCallback, loadedConfig, callback);
});
},
'loadTemplate': function(componentName, templateConfig, callback) {
resolveTemplate(makeErrorCallback(componentName), templateConfig, callback);
},
'loadViewModel': function(componentName, viewModelConfig, callback) {
resolveViewModel(makeErrorCallback(componentName), viewModelConfig, callback);
}
};
var createViewModelKey = 'createViewModel';
// Takes a config object of the form { template: ..., viewModel: ... }, and asynchronously convert it
// into the standard component definition format:
// { template: <ArrayOfDomNodes>, createViewModel: function(params, componentInfo) { ... } }.
// Since both template and viewModel may need to be resolved asynchronously, both tasks are performed
// in parallel, and the results joined when both are ready. We don't depend on any promises infrastructure,
// so this is implemented manually below.
function resolveConfig(componentName, errorCallback, config, callback) {
var result = {},
makeCallBackWhenZero = 2,
tryIssueCallback = function() {
if (--makeCallBackWhenZero === 0) {
callback(result);
}
},
templateConfig = config['template'],
viewModelConfig = config['viewModel'];
if (templateConfig) {
possiblyGetConfigFromAmd(errorCallback, templateConfig, function(loadedConfig) {
ko.components._getFirstResultFromLoaders('loadTemplate', [componentName, loadedConfig], function(resolvedTemplate) {
result['template'] = resolvedTemplate;
tryIssueCallback();
});
});
} else {
tryIssueCallback();
}
if (viewModelConfig) {
possiblyGetConfigFromAmd(errorCallback, viewModelConfig, function(loadedConfig) {
ko.components._getFirstResultFromLoaders('loadViewModel', [componentName, loadedConfig], function(resolvedViewModel) {
result[createViewModelKey] = resolvedViewModel;
tryIssueCallback();
});
});
} else {
tryIssueCallback();
}
}
function resolveTemplate(errorCallback, templateConfig, callback) {
if (typeof templateConfig === 'string') {
// Markup - parse it
callback(ko.utils.parseHtmlFragment(templateConfig));
} else if (templateConfig instanceof Array) {
// Assume already an array of DOM nodes - pass through unchanged
callback(templateConfig);
} else if (isDocumentFragment(templateConfig)) {
// Document fragment - use its child nodes
callback(ko.utils.makeArray(templateConfig.childNodes));
} else if (templateConfig['element']) {
var element = templateConfig['element'];
if (isDomElement(element)) {
// Element instance - copy its child nodes
callback(cloneNodesFromTemplateSourceElement(element));
} else if (typeof element === 'string') {
// Element ID - find it, then copy its child nodes
var elemInstance = document.getElementById(element);
if (elemInstance) {
callback(cloneNodesFromTemplateSourceElement(elemInstance));
} else {
errorCallback('Cannot find element with ID ' + element);
}
} else {
errorCallback('Unknown element type: ' + element);
}
} else {
errorCallback('Unknown template value: ' + templateConfig);
}
}
function resolveViewModel(errorCallback, viewModelConfig, callback) {
if (typeof viewModelConfig === 'function') {
// Constructor - convert to standard factory function format
// By design, this does *not* supply componentInfo to the constructor, as the intent is that
// componentInfo contains non-viewmodel data (e.g., the component's element) that should only
// be used in factory functions, not viewmodel constructors.
callback(function (params /*, componentInfo */) {
return new viewModelConfig(params);
});
} else if (typeof viewModelConfig[createViewModelKey] === 'function') {
// Already a factory function - use it as-is
callback(viewModelConfig[createViewModelKey]);
} else if ('instance' in viewModelConfig) {
// Fixed object instance - promote to createViewModel format for API consistency
var fixedInstance = viewModelConfig['instance'];
callback(function (params, componentInfo) {
return fixedInstance;
});
} else if ('viewModel' in viewModelConfig) {
// Resolved AMD module whose value is of the form { viewModel: ... }
resolveViewModel(errorCallback, viewModelConfig['viewModel'], callback);
} else {
errorCallback('Unknown viewModel value: ' + viewModelConfig);
}
}
function cloneNodesFromTemplateSourceElement(elemInstance) {
switch (ko.utils.tagNameLower(elemInstance)) {
case 'script':
return ko.utils.parseHtmlFragment(elemInstance.text);
case 'textarea':
return ko.utils.parseHtmlFragment(elemInstance.value);
case 'template':
// For browsers with proper <template> element support (i.e., where the .content property
// gives a document fragment), use that document fragment.
if (isDocumentFragment(elemInstance.content)) {
return ko.utils.cloneNodes(elemInstance.content.childNodes);
}
}
// Regular elements such as <div>, and <template> elements on old browsers that don't really
// understand <template> and just treat it as a regular container
return ko.utils.cloneNodes(elemInstance.childNodes);
}
function isDomElement(obj) {
if (window['HTMLElement']) {
return obj instanceof HTMLElement;
} else {
return obj && obj.tagName && obj.nodeType === 1;
}
}
function isDocumentFragment(obj) {
if (window['DocumentFragment']) {
return obj instanceof DocumentFragment;
} else {
return obj && obj.nodeType === 11;
}
}
function possiblyGetConfigFromAmd(errorCallback, config, callback) {
if (typeof config['require'] === 'string') {
// The config is the value of an AMD module
if (require || window['require']) {
(require || window['require'])([config['require']], callback);
} else {
errorCallback('Uses require, but no AMD loader is present');
}
} else {
callback(config);
}
}
function makeErrorCallback(componentName) {
return function (message) {
throw new Error('Component \'' + componentName + '\': ' + message);
};
}
ko.exportSymbol('components.register', ko.components.register);
ko.exportSymbol('components.isRegistered', ko.components.isRegistered);
ko.exportSymbol('components.unregister', ko.components.unregister);
// Expose the default loader so that developers can directly ask it for configuration
// or to resolve configuration
ko.exportSymbol('components.defaultLoader', ko.components.defaultLoader);
// By default, the default loader is the only registered component loader
ko.components['loaders'].push(ko.components.defaultLoader);
// Privately expose the underlying config registry for use in old-IE shim
ko.components._allRegisteredComponents = defaultConfigRegistry;
})();
(function (undefined) {
// Overridable API for determining which component name applies to a given node. By overriding this,
// you can for example map specific tagNames to components that are not preregistered.
ko.components['getComponentNameForNode'] = function(node) {
var tagNameLower = ko.utils.tagNameLower(node);
return ko.components.isRegistered(tagNameLower) && tagNameLower;
};
ko.components.addBindingsForCustomElement = function(allBindings, node, bindingContext, valueAccessors) {
// Determine if it's really a custom element matching a component
if (node.nodeType === 1) {
var componentName = ko.components['getComponentNameForNode'](node);
if (componentName) {
// It does represent a component, so add a component binding for it
allBindings = allBindings || {};
if (allBindings['component']) {
// Avoid silently overwriting some other 'component' binding that may already be on the element
throw new Error('Cannot use the "component" binding on a custom element matching a component');
}
var componentBindingValue = { 'name': componentName, 'params': getComponentParamsFromCustomElement(node, bindingContext) };
allBindings['component'] = valueAccessors
? function() { return componentBindingValue; }
: componentBindingValue;
}
}
return allBindings;
}
var nativeBindingProviderInstance = new ko.bindingProvider();
function getComponentParamsFromCustomElement(elem, bindingContext) {
var paramsAttribute = elem.getAttribute('params');
if (paramsAttribute) {
var params = nativeBindingProviderInstance['parseBindingsString'](paramsAttribute, bindingContext, elem, { 'valueAccessors': true, 'bindingParams': true }),
rawParamComputedValues = ko.utils.objectMap(params, function(paramValue, paramName) {
return ko.computed(paramValue, null, { disposeWhenNodeIsRemoved: elem });
}),
result = ko.utils.objectMap(rawParamComputedValues, function(paramValueComputed, paramName) {
// Does the evaluation of the parameter value unwrap any observables?
if (!paramValueComputed.isActive()) {
// No it doesn't, so there's no need for any computed wrapper. Just pass through the supplied value directly.
// Example: "someVal: firstName, age: 123" (whether or not firstName is an observable/computed)
return paramValueComputed.peek();
} else {
// Yes it does. Supply a computed property that unwraps both the outer (binding expression)
// level of observability, and any inner (resulting model value) level of observability.
// This means the component doesn't have to worry about multiple unwrapping.
return ko.computed(function() {
return ko.utils.unwrapObservable(paramValueComputed());
}, null, { disposeWhenNodeIsRemoved: elem });
}
});
// Give access to the raw computeds, as long as that wouldn't overwrite any custom param also called '$raw'
// This is in case the developer wants to react to outer (binding) observability separately from inner
// (model value) observability, or in case the model value observable has subobservables.
if (!result.hasOwnProperty('$raw')) {
result['$raw'] = rawParamComputedValues;
}
return result;
} else {
// For consistency, absence of a "params" attribute is treated the same as the presence of
// any empty one. Otherwise component viewmodels need special code to check whether or not
// 'params' or 'params.$raw' is null/undefined before reading subproperties, which is annoying.
return { '$raw': {} };
}
}
// --------------------------------------------------------------------------------
// Compatibility code for older (pre-HTML5) IE browsers
if (ko.utils.ieVersion < 9) {
// Whenever you preregister a component, enable it as a custom element in the current document
ko.components['register'] = (function(originalFunction) {
return function(componentName) {
document.createElement(componentName); // Allows IE<9 to parse markup containing the custom element
return originalFunction.apply(this, arguments);
}
})(ko.components['register']);
// Whenever you create a document fragment, enable all preregistered component names as custom elements
// This is needed to make innerShiv/jQuery HTML parsing correctly handle the custom elements
document.createDocumentFragment = (function(originalFunction) {
return function() {
var newDocFrag = originalFunction(),
allComponents = ko.components._allRegisteredComponents;
for (var componentName in allComponents) {
if (allComponents.hasOwnProperty(componentName)) {
newDocFrag.createElement(componentName);
}
}
return newDocFrag;
};
})(document.createDocumentFragment);
}
})();(function(undefined) {
var componentLoadingOperationUniqueId = 0;
ko.bindingHandlers['component'] = {
'init': function(element, valueAccessor, ignored1, ignored2, bindingContext) {
var currentViewModel,
currentLoadingOperationId,
disposeAssociatedComponentViewModel = function () {
var currentViewModelDispose = currentViewModel && currentViewModel['dispose'];
if (typeof currentViewModelDispose === 'function') {
currentViewModelDispose.call(currentViewModel);
}
// Any in-flight loading operation is no longer relevant, so make sure we ignore its completion
currentLoadingOperationId = null;
};
ko.utils.domNodeDisposal.addDisposeCallback(element, disposeAssociatedComponentViewModel);
ko.computed(function () {
var value = ko.utils.unwrapObservable(valueAccessor()),
componentName, componentParams;
if (typeof value === 'string') {
componentName = value;
} else {
componentName = ko.utils.unwrapObservable(value['name']);
componentParams = ko.utils.unwrapObservable(value['params']);
}
if (!componentName) {
throw new Error('No component name specified');
}
var loadingOperationId = currentLoadingOperationId = ++componentLoadingOperationUniqueId;
ko.components.get(componentName, function(componentDefinition) {
// If this is not the current load operation for this element, ignore it.
if (currentLoadingOperationId !== loadingOperationId) {
return;
}
// Clean up previous state
disposeAssociatedComponentViewModel();
// Instantiate and bind new component. Implicitly this cleans any old DOM nodes.
if (!componentDefinition) {
throw new Error('Unknown component \'' + componentName + '\'');
}
cloneTemplateIntoElement(componentName, componentDefinition, element);
var componentViewModel = createViewModel(componentDefinition, element, componentParams),
childBindingContext = bindingContext['createChildContext'](componentViewModel);
currentViewModel = componentViewModel;
ko.applyBindingsToDescendants(childBindingContext, element);
});
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
}
};
ko.virtualElements.allowedBindings['component'] = true;
function cloneTemplateIntoElement(componentName, componentDefinition, element) {
var template = componentDefinition['template'];
if (!template) {
throw new Error('Component \'' + componentName + '\' has no template');
}
var clonedNodesArray = ko.utils.cloneNodes(template);
ko.virtualElements.setDomNodeChildren(element, clonedNodesArray);
}
function createViewModel(componentDefinition, element, componentParams) {
var componentViewModelFactory = componentDefinition['createViewModel'];
return componentViewModelFactory
? componentViewModelFactory.call(componentDefinition, componentParams, { element: element })
: componentParams; // Template-only component
}
})();
var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
ko.bindingHandlers['attr'] = {
'update': function(element, valueAccessor, allBindings) {
var value = ko.utils.unwrapObservable(valueAccessor()) || {};
ko.utils.objectForEach(value, function(attrName, attrValue) {
attrValue = ko.utils.unwrapObservable(attrValue);
// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp is a "no value"-like value (strictly null, false, or undefined)
// (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
if (toRemove)
element.removeAttribute(attrName);
// In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
// HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
// but instead of figuring out the mode, we'll just set the attribute through the Javascript
// property for IE <= 8.
if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
attrName = attrHtmlToJavascriptMap[attrName];
if (toRemove)
element.removeAttribute(attrName);
else
element[attrName] = attrValue;
} else if (!toRemove) {
element.setAttribute(attrName, attrValue.toString());
}
// Treat "name" specially - although you can think of it as an attribute, it also needs
// special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
// Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
// entirely, and there's no strong reason to allow for such casing in HTML.
if (attrName === "name") {
ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
}
});
}
};
(function() {
ko.bindingHandlers['checked'] = {
'after': ['value', 'attr'],
'init': function (element, valueAccessor, allBindings) {
var checkedValue = ko.pureComputed(function() {
// Treat "value" like "checkedValue" when it is included with "checked" binding
if (allBindings['has']('checkedValue')) {
return ko.utils.unwrapObservable(allBindings.get('checkedValue'));
} else if (allBindings['has']('value')) {
return ko.utils.unwrapObservable(allBindings.get('value'));
}
return element.value;
});
function updateModel() {
// This updates the model value from the view value.
// It runs in response to DOM events (click) and changes in checkedValue.
var isChecked = element.checked,
elemValue = useCheckedValue ? checkedValue() : isChecked;
// When we're first setting up this computed, don't change any model state.
if (ko.computedContext.isInitial()) {
return;
}
// We can ignore unchecked radio buttons, because some other radio
// button will be getting checked, and that one can take care of updating state.
if (isRadio && !isChecked) {
return;
}
var modelValue = ko.dependencyDetection.ignore(valueAccessor);
if (isValueArray) {
if (oldElemValue !== elemValue) {
// When we're responding to the checkedValue changing, and the element is
// currently checked, replace the old elem value with the new elem value
// in the model array.
if (isChecked) {
ko.utils.addOrRemoveItem(modelValue, elemValue, true);
ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
}
oldElemValue = elemValue;
} else {
// When we're responding to the user having checked/unchecked a checkbox,
// add/remove the element value to the model array.
ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
}
} else {
ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
}
};
function updateView() {
// This updates the view value from the model value.
// It runs in response to changes in the bound (checked) value.
var modelValue = ko.utils.unwrapObservable(valueAccessor());
if (isValueArray) {
// When a checkbox is bound to an array, being checked represents its value being present in that array
element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
} else if (isCheckbox) {
// When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
element.checked = modelValue;
} else {
// For radio buttons, being checked means that the radio button's value corresponds to the model value
element.checked = (checkedValue() === modelValue);
}
};
var isCheckbox = element.type == "checkbox",
isRadio = element.type == "radio";
// Only bind to check boxes and radio buttons
if (!isCheckbox && !isRadio) {
return;
}
var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
oldElemValue = isValueArray ? checkedValue() : undefined,
useCheckedValue = isRadio || isValueArray;
// IE 6 won't allow radio buttons to be selected unless they have a name
if (isRadio && !element.name)
ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
// Set up two computeds to update the binding:
// The first responds to changes in the checkedValue value and to element clicks
ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
ko.utils.registerEventHandler(element, "click", updateModel);
// The second responds to changes in the model value (the one associated with the checked binding)
ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
}
};
ko.expressionRewriting.twoWayBindings['checked'] = true;
ko.bindingHandlers['checkedValue'] = {
'update': function (element, valueAccessor) {
element.value = ko.utils.unwrapObservable(valueAccessor());
}
};
})();var classesWrittenByBindingKey = '__ko__cssValue';
ko.bindingHandlers['css'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (typeof value == "object") {
ko.utils.objectForEach(value, function(className, shouldHaveClass) {
shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
});
} else {
value = String(value || ''); // Make sure we don't try to store or set a non-string value
ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
element[classesWrittenByBindingKey] = value;
ko.utils.toggleDomNodeCssClass(element, value, true);
}
}
};
ko.bindingHandlers['enable'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value && element.disabled)
element.removeAttribute("disabled");
else if ((!value) && (!element.disabled))
element.disabled = true;
}
};
ko.bindingHandlers['disable'] = {
'update': function (element, valueAccessor) {
ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
}
};
// For certain common events (currently just 'click'), allow a simplified data-binding syntax
// e.g. click:handler instead of the usual full-length event:{click:handler}
function makeEventHandlerShortcut(eventName) {
ko.bindingHandlers[eventName] = {
'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var newValueAccessor = function () {
var result = {};
result[eventName] = valueAccessor();
return result;
};
return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
}
}
}
ko.bindingHandlers['event'] = {
'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var eventsToHandle = valueAccessor() || {};
ko.utils.objectForEach(eventsToHandle, function(eventName) {
if (typeof eventName == "string") {
ko.utils.registerEventHandler(element, eventName, function (event) {
var handlerReturnValue;
var handlerFunction = valueAccessor()[eventName];
if (!handlerFunction)
return;
try {
// Take all the event args, and prefix with the viewmodel
var argsForHandler = ko.utils.makeArray(arguments);
viewModel = bindingContext['$data'];
argsForHandler.unshift(viewModel);
handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
} finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
var bubble = allBindings.get(eventName + 'Bubble') !== false;
if (!bubble) {
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
}
});
}
});
}
};
// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
ko.bindingHandlers['foreach'] = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() {
var modelValue = valueAccessor(),
unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
// If unwrappedValue is the array, pass in the wrapped value on its own
// The value will be unwrapped and tracked within the template binding
// (See https://github.com/SteveSanderson/knockout/issues/523)
if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
// If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
ko.utils.unwrapObservable(modelValue);
return {
'foreach': unwrappedValue['data'],
'as': unwrappedValue['as'],
'includeDestroyed': unwrappedValue['includeDestroyed'],
'afterAdd': unwrappedValue['afterAdd'],
'beforeRemove': unwrappedValue['beforeRemove'],
'afterRender': unwrappedValue['afterRender'],
'beforeMove': unwrappedValue['beforeMove'],
'afterMove': unwrappedValue['afterMove'],
'templateEngine': ko.nativeTemplateEngine.instance
};
};
},
'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
},
'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
}
};
ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings['foreach'] = true;
var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
var hasfocusLastValue = '__ko_hasfocusLastValue';
ko.bindingHandlers['hasfocus'] = {
'init': function(element, valueAccessor, allBindings) {
var handleElementFocusChange = function(isFocused) {
// Where possible, ignore which event was raised and determine focus state using activeElement,
// as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
// However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
// prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
// from calling 'blur()' on the element when it loses focus.
// Discussion at https://github.com/SteveSanderson/knockout/pull/352
element[hasfocusUpdatingProperty] = true;
var ownerDoc = element.ownerDocument;
if ("activeElement" in ownerDoc) {
var active;
try {
active = ownerDoc.activeElement;
} catch(e) {
// IE9 throws if you access activeElement during page load (see issue #703)
active = ownerDoc.body;
}
isFocused = (active === element);
}
var modelValue = valueAccessor();
ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
//cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
element[hasfocusLastValue] = isFocused;
element[hasfocusUpdatingProperty] = false;
};
var handleElementFocusIn = handleElementFocusChange.bind(null, true);
var handleElementFocusOut = handleElementFocusChange.bind(null, false);
ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
},
'update': function(element, valueAccessor) {
var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
value ? element.focus() : element.blur();
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
}
}
};
ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
ko.bindingHandlers['html'] = {
'init': function() {
// Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
}
};
// Makes a binding like with or if
function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
ko.bindingHandlers[bindingKey] = {
'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
savedNodes;
ko.computed(function() {
var dataValue = ko.utils.unwrapObservable(valueAccessor()),
shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
isFirstRender = !savedNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
if (needsRefresh) {
// Save a copy of the inner nodes on the initial update, but only if we have dependencies.
if (isFirstRender && ko.computedContext.getDependenciesCount()) {
savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
}
if (shouldDisplay) {
if (!isFirstRender) {
ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
}
ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
} else {
ko.virtualElements.emptyNode(element);
}
didDisplayOnLastUpdate = shouldDisplay;
}
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
}
};
ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
ko.virtualElements.allowedBindings[bindingKey] = true;
}
// Construct the actual binding handlers
makeWithIfBinding('if');
makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
makeWithIfBinding('with', true /* isWith */, false /* isNot */,
function(bindingContext, dataValue) {
return bindingContext['createChildContext'](dataValue);
}
);
var captionPlaceholder = {};
ko.bindingHandlers['options'] = {
'init': function(element) {
if (ko.utils.tagNameLower(element) !== "select")
throw new Error("options binding applies only to SELECT elements");
// Remove all existing <option>s.
while (element.length > 0) {
element.remove(0);
}
// Ensures that the binding processor doesn't try to bind the options
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings) {
function selectedOptions() {
return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
}
var selectWasPreviouslyEmpty = element.length == 0;
var previousScrollTop = (!selectWasPreviouslyEmpty && element.multiple) ? element.scrollTop : null;
var unwrappedArray = ko.utils.unwrapObservable(valueAccessor());
var includeDestroyed = allBindings.get('optionsIncludeDestroyed');
var arrayToDomNodeChildrenOptions = {};
var captionValue;
var filteredArray;
var previousSelectedValues;
if (element.multiple) {
previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
} else {
previousSelectedValues = element.selectedIndex >= 0 ? [ ko.selectExtensions.readValue(element.options[element.selectedIndex]) ] : [];
}
if (unwrappedArray) {
if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
unwrappedArray = [unwrappedArray];
// Filter out any entries marked as destroyed
filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
});
// If caption is included, add it to the array
if (allBindings['has']('optionsCaption')) {
captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
// If caption value is null or undefined, don't show a caption
if (captionValue !== null && captionValue !== undefined) {
filteredArray.unshift(captionPlaceholder);
}
}
} else {
// If a falsy value is provided (e.g. null), we'll simply empty the select element
}
function applyToObject(object, predicate, defaultValue) {
var predicateType = typeof predicate;
if (predicateType == "function") // Given a function; run it against the data value
return predicate(object);
else if (predicateType == "string") // Given a string; treat it as a property name on the data value
return object[predicate];
else // Given no optionsText arg; use the data value itself
return defaultValue;
}
// The following functions can run at two different times:
// The first is when the whole array is being updated directly from this binding handler.
// The second is when an observable value for a specific array entry is updated.
// oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
var itemUpdate = false;
function optionForArrayItem(arrayEntry, index, oldOptions) {
if (oldOptions.length) {
previousSelectedValues = oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
itemUpdate = true;
}
var option = element.ownerDocument.createElement("option");
if (arrayEntry === captionPlaceholder) {
ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
ko.selectExtensions.writeValue(option, undefined);
} else {
// Apply a value to the option element
var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
// Apply some text to the option element
var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
ko.utils.setTextContent(option, optionText);
}
return [option];
}
// By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
// problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
arrayToDomNodeChildrenOptions['beforeRemove'] =
function (option) {
element.removeChild(option);
};
function setSelectionCallback(arrayEntry, newOptions) {
// IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
// That's why we first added them without selection. Now it's time to set the selection.
if (previousSelectedValues.length) {
var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
// If this option was changed from being selected during a single-item update, notify the change
if (itemUpdate && !isSelected)
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
}
}
var callback = setSelectionCallback;
if (allBindings['has']('optionsAfterRender')) {
callback = function(arrayEntry, newOptions) {
setSelectionCallback(arrayEntry, newOptions);
ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
}
}
ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
ko.dependencyDetection.ignore(function () {
if (allBindings.get('valueAllowUnset') && allBindings['has']('value')) {
// The model value is authoritative, so make sure its value is the one selected
ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
} else {
// Determine if the selection has changed as a result of updating the options list
var selectionChanged;
if (element.multiple) {
// For a multiple-select box, compare the new selection count to the previous one
// But if nothing was selected before, the selection can't have changed
selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
} else {
// For a single-select box, compare the current value to the previous value
// But if nothing was selected before or nothing is selected now, just look for a change in selection
selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
: (previousSelectedValues.length || element.selectedIndex >= 0);
}
// Ensure consistency between model value and selected option.
// If the dropdown was changed so that selection is no longer the same,
// notify the value or selectedOptions binding.
if (selectionChanged) {
ko.utils.triggerEvent(element, "change");
}
}
});
// Workaround for IE bug
ko.utils.ensureSelectElementIsRenderedCorrectly(element);
if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
element.scrollTop = previousScrollTop;
}
};
ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
ko.bindingHandlers['selectedOptions'] = {
'after': ['options', 'foreach'],
'init': function (element, valueAccessor, allBindings) {
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor(), valueToWrite = [];
ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
if (node.selected)
valueToWrite.push(ko.selectExtensions.readValue(node));
});
ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
});
},
'update': function (element, valueAccessor) {
if (ko.utils.tagNameLower(element) != "select")
throw new Error("values binding applies only to SELECT elements");
var newValue = ko.utils.unwrapObservable(valueAccessor());
if (newValue && typeof newValue.length == "number") {
ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
ko.utils.setOptionNodeSelectionState(node, isSelected);
});
}
}
};
ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
ko.bindingHandlers['style'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
ko.utils.objectForEach(value, function(styleName, styleValue) {
styleValue = ko.utils.unwrapObservable(styleValue);
if (styleValue === null || styleValue === undefined || styleValue === false) {
// Empty string removes the value, whereas null/undefined have no effect
styleValue = "";
}
element.style[styleName] = styleValue;
});
}
};
ko.bindingHandlers['submit'] = {
'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
if (typeof valueAccessor() != "function")
throw new Error("The value for a submit binding must be a function");
ko.utils.registerEventHandler(element, "submit", function (event) {
var handlerReturnValue;
var value = valueAccessor();
try { handlerReturnValue = value.call(bindingContext['$data'], element); }
finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
});
}
};
ko.bindingHandlers['text'] = {
'init': function() {
// Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
// It should also make things faster, as we no longer have to consider whether the text node might be bindable.
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor) {
ko.utils.setTextContent(element, valueAccessor());
}
};
ko.virtualElements.allowedBindings['text'] = true;
(function () {
if (window && window.navigator) {
var parseVersion = function (matches) {
if (matches) {
return parseFloat(matches[1]);
}
};
// Detect various browser versions because some old versions don't fully support the 'input' event
var operaVersion = window.opera && window.opera.version && parseInt(window.opera.version()),
userAgent = window.navigator.userAgent,
safariVersion = parseVersion(userAgent.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),
firefoxVersion = parseVersion(userAgent.match(/Firefox\/([^ ]*)/));
}
// IE 8 and 9 have bugs that prevent the normal events from firing when the value changes.
// But it does fire the 'selectionchange' event on many of those, presumably because the
// cursor is moving and that counts as the selection changing. The 'selectionchange' event is
// fired at the document level only and doesn't directly indicate which element changed. We
// set up just one event handler for the document and use 'activeElement' to determine which
// element was changed.
if (ko.utils.ieVersion < 10) {
var selectionChangeRegisteredName = ko.utils.domData.nextKey(),
selectionChangeHandlerName = ko.utils.domData.nextKey();
var selectionChangeHandler = function(event) {
var target = this.activeElement,
handler = target && ko.utils.domData.get(target, selectionChangeHandlerName);
if (handler) {
handler(event);
}
};
var registerForSelectionChangeEvent = function (element, handler) {
var ownerDoc = element.ownerDocument;
if (!ko.utils.domData.get(ownerDoc, selectionChangeRegisteredName)) {
ko.utils.domData.set(ownerDoc, selectionChangeRegisteredName, true);
ko.utils.registerEventHandler(ownerDoc, 'selectionchange', selectionChangeHandler);
}
ko.utils.domData.set(element, selectionChangeHandlerName, handler);
};
}
ko.bindingHandlers['textInput'] = {
'init': function (element, valueAccessor, allBindings) {
var previousElementValue = element.value,
timeoutHandle,
elementValueBeforeEvent;
var updateModel = function (event) {
clearTimeout(timeoutHandle);
elementValueBeforeEvent = timeoutHandle = undefined;
var elementValue = element.value;
if (previousElementValue !== elementValue) {
// Provide a way for tests to know exactly which event was processed
if (DEBUG && event) element['_ko_textInputProcessedEvent'] = event.type;
previousElementValue = elementValue;
ko.expressionRewriting.writeValueToProperty(valueAccessor(), allBindings, 'textInput', elementValue);
}
};
var deferUpdateModel = function (event) {
if (!timeoutHandle) {
// The elementValueBeforeEvent variable is set *only* during the brief gap between an
// event firing and the updateModel function running. This allows us to ignore model
// updates that are from the previous state of the element, usually due to techniques
// such as rateLimit. Such updates, if not ignored, can cause keystrokes to be lost.
elementValueBeforeEvent = element.value;
var handler = DEBUG ? updateModel.bind(element, {type: event.type}) : updateModel;
timeoutHandle = setTimeout(handler, 4);
}
};
var updateView = function () {
var modelValue = ko.utils.unwrapObservable(valueAccessor());
if (modelValue === null || modelValue === undefined) {
modelValue = '';
}
if (elementValueBeforeEvent !== undefined && modelValue === elementValueBeforeEvent) {
setTimeout(updateView, 4);
return;
}
// Update the element only if the element and model are different. On some browsers, updating the value
// will move the cursor to the end of the input, which would be bad while the user is typing.
if (element.value !== modelValue) {
previousElementValue = modelValue; // Make sure we ignore events (propertychange) that result from updating the value
element.value = modelValue;
}
};
var onEvent = function (event, handler) {
ko.utils.registerEventHandler(element, event, handler);
};
if (DEBUG && ko.bindingHandlers['textInput']['_forceUpdateOn']) {
// Provide a way for tests to specify exactly which events are bound
ko.utils.arrayForEach(ko.bindingHandlers['textInput']['_forceUpdateOn'], function(eventName) {
if (eventName.slice(0,5) == 'after') {
onEvent(eventName.slice(5), deferUpdateModel);
} else {
onEvent(eventName, updateModel);
}
});
} else {
if (ko.utils.ieVersion < 10) {
// Internet Explorer <= 8 doesn't support the 'input' event, but does include 'propertychange' that fires whenever
// any property of an element changes. Unlike 'input', it also fires if a property is changed from JavaScript code,
// but that's an acceptable compromise for this binding. IE 9 does support 'input', but since it doesn't fire it
// when using autocomplete, we'll use 'propertychange' for it also.
onEvent('propertychange', function(event) {
if (event.propertyName === 'value') {
updateModel(event);
}
});
if (ko.utils.ieVersion == 8) {
// IE 8 has a bug where it fails to fire 'propertychange' on the first update following a value change from
// JavaScript code. It also doesn't fire if you clear the entire value. To fix this, we bind to the following
// events too.
onEvent('keyup', updateModel); // A single keystoke
onEvent('keydown', updateModel); // The first character when a key is held down
}
if (ko.utils.ieVersion >= 8) {
// Internet Explorer 9 doesn't fire the 'input' event when deleting text, including using
// the backspace, delete, or ctrl-x keys, clicking the 'x' to clear the input, dragging text
// out of the field, and cutting or deleting text using the context menu. 'selectionchange'
// can detect all of those except dragging text out of the field, for which we use 'dragend'.
// These are also needed in IE8 because of the bug described above.
registerForSelectionChangeEvent(element, updateModel); // 'selectionchange' covers cut, paste, drop, delete, etc.
onEvent('dragend', deferUpdateModel);
}
} else {
// All other supported browsers support the 'input' event, which fires whenever the content of the element is changed
// through the user interface.
onEvent('input', updateModel);
if (safariVersion < 5 && ko.utils.tagNameLower(element) === "textarea") {
// Safari <5 doesn't fire the 'input' event for <textarea> elements (it does fire 'textInput'
// but only when typing). So we'll just catch as much as we can with keydown, cut, and paste.
onEvent('keydown', deferUpdateModel);
onEvent('paste', deferUpdateModel);
onEvent('cut', deferUpdateModel);
} else if (operaVersion < 11) {
// Opera 10 doesn't always fire the 'input' event for cut, paste, undo & drop operations.
// We can try to catch some of those using 'keydown'.
onEvent('keydown', deferUpdateModel);
} else if (firefoxVersion < 4.0) {
// Firefox <= 3.6 doesn't fire the 'input' event when text is filled in through autocomplete
onEvent('DOMAutoComplete', updateModel);
// Firefox <=3.5 doesn't fire the 'input' event when text is dropped into the input.
onEvent('dragdrop', updateModel); // <3.5
onEvent('drop', updateModel); // 3.5
}
}
}
// Bind to the change event so that we can catch programmatic updates of the value that fire this event.
onEvent('change', updateModel);
ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
}
};
ko.expressionRewriting.twoWayBindings['textInput'] = true;
// textinput is an alias for textInput
ko.bindingHandlers['textinput'] = {
// preprocess is the only way to set up a full alias
'preprocess': function (value, name, addBinding) {
addBinding('textInput', value);
}
};
})();ko.bindingHandlers['uniqueName'] = {
'init': function (element, valueAccessor) {
if (valueAccessor()) {
var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
ko.utils.setElementName(element, name);
}
}
};
ko.bindingHandlers['uniqueName'].currentIndex = 0;
ko.bindingHandlers['value'] = {
'after': ['options', 'foreach'],
'init': function (element, valueAccessor, allBindings) {
// If the value binding is placed on a radio/checkbox, then just pass through to checkedValue and quit
if (element.tagName.toLowerCase() == "input" && (element.type == "checkbox" || element.type == "radio")) {
ko.applyBindingAccessorsToNode(element, { 'checkedValue': valueAccessor });
return;
}
// Always catch "change" event; possibly other events too if asked
var eventsToCatch = ["change"];
var requestedEventsToCatch = allBindings.get("valueUpdate");
var propertyChangedFired = false;
var elementValueBeforeEvent = null;
if (requestedEventsToCatch) {
if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
requestedEventsToCatch = [requestedEventsToCatch];
ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
}
var valueUpdateHandler = function() {
elementValueBeforeEvent = null;
propertyChangedFired = false;
var modelValue = valueAccessor();
var elementValue = ko.selectExtensions.readValue(element);
ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
}
// Workaround for https://github.com/SteveSanderson/knockout/issues/122
// IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
&& element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
ko.utils.registerEventHandler(element, "blur", function() {
if (propertyChangedFired) {
valueUpdateHandler();
}
});
}
ko.utils.arrayForEach(eventsToCatch, function(eventName) {
// The syntax "after<eventname>" means "run the handler asynchronously after the event"
// This is useful, for example, to catch "keydown" events after the browser has updated the control
// (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
var handler = valueUpdateHandler;
if (ko.utils.stringStartsWith(eventName, "after")) {
handler = function() {
// The elementValueBeforeEvent variable is non-null *only* during the brief gap between
// a keyX event firing and the valueUpdateHandler running, which is scheduled to happen
// at the earliest asynchronous opportunity. We store this temporary information so that
// if, between keyX and valueUpdateHandler, the underlying model value changes separately,
// we can overwrite that model value change with the value the user just typed. Otherwise,
// techniques like rateLimit can trigger model changes at critical moments that will
// override the user's inputs, causing keystrokes to be lost.
elementValueBeforeEvent = ko.selectExtensions.readValue(element);
setTimeout(valueUpdateHandler, 0);
};
eventName = eventName.substring("after".length);
}
ko.utils.registerEventHandler(element, eventName, handler);
});
var updateFromModel = function () {
var newValue = ko.utils.unwrapObservable(valueAccessor());
var elementValue = ko.selectExtensions.readValue(element);
if (elementValueBeforeEvent !== null && newValue === elementValueBeforeEvent) {
setTimeout(updateFromModel, 0);
return;
}
var valueHasChanged = (newValue !== elementValue);
if (valueHasChanged) {
if (ko.utils.tagNameLower(element) === "select") {
var allowUnset = allBindings.get('valueAllowUnset');
var applyValueAction = function () {
ko.selectExtensions.writeValue(element, newValue, allowUnset);
};
applyValueAction();
if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
// If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
// because you're not allowed to have a model value that disagrees with a visible UI selection.
ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
} else {
// Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
// right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
// to apply the value as well.
setTimeout(applyValueAction, 0);
}
} else {
ko.selectExtensions.writeValue(element, newValue);
}
}
};
ko.computed(updateFromModel, null, { disposeWhenNodeIsRemoved: element });
},
'update': function() {} // Keep for backwards compatibility with code that may have wrapped value binding
};
ko.expressionRewriting.twoWayBindings['value'] = true;
ko.bindingHandlers['visible'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var isCurrentlyVisible = !(element.style.display == "none");
if (value && !isCurrentlyVisible)
element.style.display = "";
else if ((!value) && isCurrentlyVisible)
element.style.display = "none";
}
};
// 'click' is just a shorthand for the usual full-length event:{click:handler}
makeEventHandlerShortcut('click');
// If you want to make a custom template engine,
//
// [1] Inherit from this class (like ko.nativeTemplateEngine does)
// [2] Override 'renderTemplateSource', supplying a function with this signature:
//
// function (templateSource, bindingContext, options) {
// // - templateSource.text() is the text of the template you should render
// // - bindingContext.$data is the data you should pass into the template
// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
// // and bindingContext.$root available in the template too
// // - options gives you access to any other properties set on "data-bind: { template: options }"
// //
// // Return value: an array of DOM nodes
// }
//
// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
//
// function (script) {
// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
// }
//
// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
ko.templateEngine = function () { };
ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
throw new Error("Override renderTemplateSource");
};
ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
throw new Error("Override createJavaScriptEvaluatorBlock");
};
ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
// Named template
if (typeof template == "string") {
templateDocument = templateDocument || document;
var elem = templateDocument.getElementById(template);
if (!elem)
throw new Error("Cannot find template with ID " + template);
return new ko.templateSources.domElement(elem);
} else if ((template.nodeType == 1) || (template.nodeType == 8)) {
// Anonymous template
return new ko.templateSources.anonymousTemplate(template);
} else
throw new Error("Unknown template type: " + template);
};
ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
var templateSource = this['makeTemplateSource'](template, templateDocument);
return this['renderTemplateSource'](templateSource, bindingContext, options);
};
ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
// Skip rewriting if requested
if (this['allowTemplateRewriting'] === false)
return true;
return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
};
ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
var templateSource = this['makeTemplateSource'](template, templateDocument);
var rewritten = rewriterCallback(templateSource['text']());
templateSource['text'](rewritten);
templateSource['data']("isRewritten", true);
};
ko.exportSymbol('templateEngine', ko.templateEngine);
ko.templateRewriting = (function () {
var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
function validateDataBindValuesForRewriting(keyValueArray) {
var allValidators = ko.expressionRewriting.bindingRewriteValidators;
for (var i = 0; i < keyValueArray.length; i++) {
var key = keyValueArray[i]['key'];
if (allValidators.hasOwnProperty(key)) {
var validator = allValidators[key];
if (typeof validator === "function") {
var possibleErrorMessage = validator(keyValueArray[i]['value']);
if (possibleErrorMessage)
throw new Error(possibleErrorMessage);
} else if (!validator) {
throw new Error("This template engine does not support the '" + key + "' binding within its templates");
}
}
}
}
function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
validateDataBindValuesForRewriting(dataBindKeyValueArray);
var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
// For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
// anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
// extra indirection.
var applyBindingsToNextSiblingScript =
"ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
}
return {
ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
if (!templateEngine['isTemplateRewritten'](template, templateDocument))
templateEngine['rewriteTemplate'](template, function (htmlString) {
return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
}, templateDocument);
},
memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
}).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
});
},
applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
return ko.memoization.memoize(function (domNode, bindingContext) {
var nodeToBind = domNode.nextSibling;
if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
}
});
}
}
})();
// Exported only because it has to be referenced by string lookup from within rewritten template
ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
(function() {
// A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
// logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
//
// Two are provided by default:
// 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
// 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
// without reading/writing the actual element text content, since it will be overwritten
// with the rendered template output.
// You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
// Template sources need to have the following functions:
// text() - returns the template text from your storage location
// text(value) - writes the supplied template text to your storage location
// data(key) - reads values stored using data(key, value) - see below
// data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
//
// Optionally, template sources can also have the following functions:
// nodes() - returns a DOM element containing the nodes of this template, where available
// nodes(value) - writes the given DOM element to your storage location
// If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
// for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
//
// Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
// using and overriding "makeTemplateSource" to return an instance of your custom template source.
ko.templateSources = {};
// ---- ko.templateSources.domElement -----
ko.templateSources.domElement = function(element) {
this.domElement = element;
}
ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
var tagNameLower = ko.utils.tagNameLower(this.domElement),
elemContentsProperty = tagNameLower === "script" ? "text"
: tagNameLower === "textarea" ? "value"
: "innerHTML";
if (arguments.length == 0) {
return this.domElement[elemContentsProperty];
} else {
var valueToWrite = arguments[0];
if (elemContentsProperty === "innerHTML")
ko.utils.setHtml(this.domElement, valueToWrite);
else
this.domElement[elemContentsProperty] = valueToWrite;
}
};
var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
if (arguments.length === 1) {
return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
} else {
ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
}
};
// ---- ko.templateSources.anonymousTemplate -----
// Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
// For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
// Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
ko.templateSources.anonymousTemplate = function(element) {
this.domElement = element;
}
ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
if (arguments.length == 0) {
var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
if (templateData.textData === undefined && templateData.containerData)
templateData.textData = templateData.containerData.innerHTML;
return templateData.textData;
} else {
var valueToWrite = arguments[0];
ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
}
};
ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
if (arguments.length == 0) {
var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
return templateData.containerData;
} else {
var valueToWrite = arguments[0];
ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
}
};
ko.exportSymbol('templateSources', ko.templateSources);
ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
})();
(function () {
var _templateEngine;
ko.setTemplateEngine = function (templateEngine) {
if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
throw new Error("templateEngine must inherit from ko.templateEngine");
_templateEngine = templateEngine;
}
function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
nextInQueue = ko.virtualElements.nextSibling(node);
action(node, nextInQueue);
}
}
function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
// To be used on any nodes that have been rendered by a template and have been inserted into some parent element
// Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
// the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
// (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
// (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
if (continuousNodeArray.length) {
var firstNode = continuousNodeArray[0],
lastNode = continuousNodeArray[continuousNodeArray.length - 1],
parentNode = firstNode.parentNode,
provider = ko.bindingProvider['instance'],
preprocessNode = provider['preprocessNode'];
if (preprocessNode) {
invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
var nodePreviousSibling = node.previousSibling;
var newNodes = preprocessNode.call(provider, node);
if (newNodes) {
if (node === firstNode)
firstNode = newNodes[0] || nextNodeInRange;
if (node === lastNode)
lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
}
});
// Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
// We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
// first node needs to be in the array).
continuousNodeArray.length = 0;
if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
return;
}
if (firstNode === lastNode) {
continuousNodeArray.push(firstNode);
} else {
continuousNodeArray.push(firstNode, lastNode);
ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
}
}
// Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
// whereas a regular applyBindings won't introduce new memoized nodes
invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
if (node.nodeType === 1 || node.nodeType === 8)
ko.applyBindings(bindingContext, node);
});
invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
if (node.nodeType === 1 || node.nodeType === 8)
ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
});
// Make sure any changes done by applyBindings or unmemoize are reflected in the array
ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
}
}
function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
return nodeOrNodeArray.nodeType ? nodeOrNodeArray
: nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
: null;
}
function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
options = options || {};
var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
var templateEngineToUse = (options['templateEngine'] || _templateEngine);
ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
// Loosely check result is an array of DOM nodes
if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
throw new Error("Template engine must return an array of DOM nodes");
var haveAddedNodesToParent = false;
switch (renderMode) {
case "replaceChildren":
ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
haveAddedNodesToParent = true;
break;
case "replaceNode":
ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
haveAddedNodesToParent = true;
break;
case "ignoreTargetNode": break;
default:
throw new Error("Unknown renderMode: " + renderMode);
}
if (haveAddedNodesToParent) {
activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
if (options['afterRender'])
ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
}
return renderedNodesArray;
}
function resolveTemplateName(template, data, context) {
// The template can be specified as:
if (ko.isObservable(template)) {
// 1. An observable, with string value
return template();
} else if (typeof template === 'function') {
// 2. A function of (data, context) returning a string
return template(data, context);
} else {
// 3. A string
return template;
}
}
ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
options = options || {};
if ((options['templateEngine'] || _templateEngine) == undefined)
throw new Error("Set a template engine before calling renderTemplate");
renderMode = renderMode || "replaceChildren";
if (targetNodeOrNodeArray) {
var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
function () {
// Ensure we've got a proper binding context to work with
var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
? dataOrBindingContext
: new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
var templateName = resolveTemplateName(template, bindingContext['$data'], bindingContext),
renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
if (renderMode == "replaceNode") {
targetNodeOrNodeArray = renderedNodesArray;
firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
}
},
null,
{ disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
);
} else {
// We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
return ko.memoization.memoize(function (domNode) {
ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
});
}
};
ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
// Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
// activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
var arrayItemContext;
// This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
var executeTemplateForArrayItem = function (arrayValue, index) {
// Support selecting template as a function of the data being rendered
arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
context['$index'] = index;
});
var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
}
// This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
if (options['afterRender'])
options['afterRender'](addedNodesArray, arrayValue);
};
return ko.dependentObservable(function () {
var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
unwrappedArray = [unwrappedArray];
// Filter out any entries marked as destroyed
var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
});
// Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
// If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
}, null, { disposeWhenNodeIsRemoved: targetNode });
};
var templateComputedDomDataKey = ko.utils.domData.nextKey();
function disposeOldComputedAndStoreNewOne(element, newComputed) {
var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
oldComputed.dispose();
ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
}
ko.bindingHandlers['template'] = {
'init': function(element, valueAccessor) {
// Support anonymous templates
var bindingValue = ko.utils.unwrapObservable(valueAccessor());
if (typeof bindingValue == "string" || bindingValue['name']) {
// It's a named template - clear the element
ko.virtualElements.emptyNode(element);
} else {
// It's an anonymous template - store the element contents, then clear the element
var templateNodes = ko.virtualElements.childNodes(element),
container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
new ko.templateSources.anonymousTemplate(element)['nodes'](container);
}
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor(),
dataValue,
options = ko.utils.unwrapObservable(value),
shouldDisplay = true,
templateComputed = null,
templateName;
if (typeof options == "string") {
templateName = value;
options = {};
} else {
templateName = options['name'];
// Support "if"/"ifnot" conditions
if ('if' in options)
shouldDisplay = ko.utils.unwrapObservable(options['if']);
if (shouldDisplay && 'ifnot' in options)
shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
dataValue = ko.utils.unwrapObservable(options['data']);
}
if ('foreach' in options) {
// Render once for each data point (treating data set as empty if shouldDisplay==false)
var dataArray = (shouldDisplay && options['foreach']) || [];
templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
} else if (!shouldDisplay) {
ko.virtualElements.emptyNode(element);
} else {
// Render once for this single data point (or use the viewModel if no data was provided)
var innerBindingContext = ('data' in options) ?
bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
bindingContext; // Given no explicit 'data' value, we retain the same binding context
templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
}
// It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
disposeOldComputedAndStoreNewOne(element, templateComputed);
}
};
// Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
return null; // Named templates can be rewritten, so return "no error"
return "This template engine does not support anonymous templates nested within its templates";
};
ko.virtualElements.allowedBindings['template'] = true;
})();
ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
ko.exportSymbol('renderTemplate', ko.renderTemplate);
// Go through the items that have been added and deleted and try to find matches between them.
ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
if (left.length && right.length) {
var failedCompares, l, r, leftItem, rightItem;
for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
for (r = 0; rightItem = right[r]; ++r) {
if (leftItem['value'] === rightItem['value']) {
leftItem['moved'] = rightItem['index'];
rightItem['moved'] = leftItem['index'];
right.splice(r, 1); // This item is marked as moved; so remove it from right list
failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
break;
}
}
failedCompares += r;
}
}
};
ko.utils.compareArrays = (function () {
var statusNotInOld = 'added', statusNotInNew = 'deleted';
// Simple calculation based on Levenshtein distance.
function compareArrays(oldArray, newArray, options) {
// For backward compatibility, if the third arg is actually a bool, interpret
// it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
oldArray = oldArray || [];
newArray = newArray || [];
if (oldArray.length <= newArray.length)
return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
else
return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
}
function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
var myMin = Math.min,
myMax = Math.max,
editDistanceMatrix = [],
smlIndex, smlIndexMax = smlArray.length,
bigIndex, bigIndexMax = bigArray.length,
compareRange = (bigIndexMax - smlIndexMax) || 1,
maxDistance = smlIndexMax + bigIndexMax + 1,
thisRow, lastRow,
bigIndexMaxForRow, bigIndexMinForRow;
for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
lastRow = thisRow;
editDistanceMatrix.push(thisRow = []);
bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
bigIndexMinForRow = myMax(0, smlIndex - 1);
for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
if (!bigIndex)
thisRow[bigIndex] = smlIndex + 1;
else if (!smlIndex) // Top row - transform empty array into new array via additions
thisRow[bigIndex] = bigIndex + 1;
else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
else {
var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
}
}
}
var editScript = [], meMinusOne, notInSml = [], notInBig = [];
for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
notInSml.push(editScript[editScript.length] = { // added
'status': statusNotInSml,
'value': bigArray[--bigIndex],
'index': bigIndex });
} else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
notInBig.push(editScript[editScript.length] = { // deleted
'status': statusNotInBig,
'value': smlArray[--smlIndex],
'index': smlIndex });
} else {
--bigIndex;
--smlIndex;
if (!options['sparse']) {
editScript.push({
'status': "retained",
'value': bigArray[bigIndex] });
}
}
}
// Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
// smlIndexMax keeps the time complexity of this algorithm linear.
ko.utils.findMovesInArrayComparison(notInSml, notInBig, smlIndexMax * 10);
return editScript.reverse();
}
return compareArrays;
})();
ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
(function () {
// Objective:
// * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
// map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
// * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
// so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
// previously mapped - retain those nodes, and just insert/delete other ones
// "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
// You can use this, for example, to activate bindings on those nodes.
function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
// Map this array value inside a dependentObservable so we re-map when any dependency changes
var mappedNodes = [];
var dependentObservable = ko.dependentObservable(function() {
var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
// On subsequent evaluations, just replace the previously-inserted DOM nodes
if (mappedNodes.length > 0) {
ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
if (callbackAfterAddingNodes)
ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
}
// Replace the contents of the mappedNodes array, thereby updating the record
// of which nodes would be deleted if valueToMap was itself later removed
mappedNodes.length = 0;
ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
}, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
}
var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
// Compare the provided array against the previous one
array = array || [];
options = options || {};
var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
// Build the new mapping result
var newMappingResult = [];
var lastMappingResultIndex = 0;
var newMappingResultIndex = 0;
var nodesToDelete = [];
var itemsToProcess = [];
var itemsForBeforeRemoveCallbacks = [];
var itemsForMoveCallbacks = [];
var itemsForAfterAddCallbacks = [];
var mapData;
function itemMovedOrRetained(editScriptIndex, oldPosition) {
mapData = lastMappingResult[oldPosition];
if (newMappingResultIndex !== oldPosition)
itemsForMoveCallbacks[editScriptIndex] = mapData;
// Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
mapData.indexObservable(newMappingResultIndex++);
ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
newMappingResult.push(mapData);
itemsToProcess.push(mapData);
}
function callCallback(callback, items) {
if (callback) {
for (var i = 0, n = items.length; i < n; i++) {
if (items[i]) {
ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
callback(node, i, items[i].arrayEntry);
});
}
}
}
}
for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
movedIndex = editScriptItem['moved'];
switch (editScriptItem['status']) {
case "deleted":
if (movedIndex === undefined) {
mapData = lastMappingResult[lastMappingResultIndex];
// Stop tracking changes to the mapping for these nodes
if (mapData.dependentObservable)
mapData.dependentObservable.dispose();
// Queue these nodes for later removal
nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
if (options['beforeRemove']) {
itemsForBeforeRemoveCallbacks[i] = mapData;
itemsToProcess.push(mapData);
}
}
lastMappingResultIndex++;
break;
case "retained":
itemMovedOrRetained(i, lastMappingResultIndex++);
break;
case "added":
if (movedIndex !== undefined) {
itemMovedOrRetained(i, movedIndex);
} else {
mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
newMappingResult.push(mapData);
itemsToProcess.push(mapData);
if (!isFirstExecution)
itemsForAfterAddCallbacks[i] = mapData;
}
break;
}
}
// Call beforeMove first before any changes have been made to the DOM
callCallback(options['beforeMove'], itemsForMoveCallbacks);
// Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
// Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
// Get nodes for newly added items
if (!mapData.mappedNodes)
ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
// Put nodes in the right place if they aren't there already
for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
if (node !== nextNode)
ko.virtualElements.insertAfter(domNode, node, lastNode);
}
// Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
if (!mapData.initialized && callbackAfterAddingNodes) {
callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
mapData.initialized = true;
}
}
// If there's a beforeRemove callback, call it after reordering.
// Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
// some sort of animation, which is why we first reorder the nodes that will be removed. If the
// callback instead removes the nodes right away, it would be more efficient to skip reordering them.
// Perhaps we'll make that change in the future if this scenario becomes more common.
callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
// Finally call afterMove and afterAdd callbacks
callCallback(options['afterMove'], itemsForMoveCallbacks);
callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
// Store a copy of the array items we just considered so we can difference it next time
ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
}
})();
ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
ko.nativeTemplateEngine = function () {
this['allowTemplateRewriting'] = false;
}
ko.nativeTemplateEngine.prototype = new ko.templateEngine();
ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
if (templateNodes) {
return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
} else {
var templateText = templateSource['text']();
return ko.utils.parseHtmlFragment(templateText);
}
};
ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
(function() {
ko.jqueryTmplTemplateEngine = function () {
// Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
// doesn't expose a version number, so we have to infer it.
// Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
// which KO internally refers to as version "2", so older versions are no longer detected.
var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
if (!jQueryInstance || !(jQueryInstance['tmpl']))
return 0;
// Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
try {
if (jQueryInstance['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
// Since 1.0.0pre, custom tags should append markup to an array called "__"
return 2; // Final version of jquery.tmpl
}
} catch(ex) { /* Apparently not the version we were looking for */ }
return 1; // Any older version that we don't support
})();
function ensureHasReferencedJQueryTemplates() {
if (jQueryTmplVersion < 2)
throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
}
function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
return jQueryInstance['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
}
this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
options = options || {};
ensureHasReferencedJQueryTemplates();
// Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
var precompiled = templateSource['data']('precompiled');
if (!precompiled) {
var templateText = templateSource['text']() || "";
// Wrap in "with($whatever.koBindingContext) { ... }"
templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
precompiled = jQueryInstance['template'](null, templateText);
templateSource['data']('precompiled', precompiled);
}
var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
var jQueryTemplateOptions = jQueryInstance['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
jQueryInstance['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
return resultNodes;
};
this['createJavaScriptEvaluatorBlock'] = function(script) {
return "{{ko_code ((function() { return " + script + " })()) }}";
};
this['addTemplate'] = function(templateName, templateMarkup) {
document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
};
if (jQueryTmplVersion > 0) {
jQueryInstance['tmpl']['tag']['ko_code'] = {
open: "__.push($1 || '');"
};
jQueryInstance['tmpl']['tag']['ko_with'] = {
open: "with($1) {",
close: "} "
};
}
};
ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
// Use this one by default *only if jquery.tmpl is referenced*
var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
})();
}));
}());
})();
|
src/React/Widgets/TogglePanelWidget/example/index.js | Kitware/paraviewweb | // Load CSS
import 'normalize.css';
import 'font-awesome/css/font-awesome.css';
import React from 'react';
import ReactDOM from 'react-dom';
import TogglePanelWidget from 'paraviewweb/src/React/Widgets/TogglePanelWidget';
const container = document.querySelector('.content');
document.body.style.padding = '10px';
document.body.style.background = '#ccc';
ReactDOM.render(
<div>
<div
style={{
position: 'relative',
width: '2em',
border: 'solid 1px black',
borderRadius: '5px',
}}
>
<TogglePanelWidget anchor={['top', 'right']} position={['top', 'left']}>
<div
style={{
padding: '50px',
background: 'red',
border: 'solid 1px black',
borderRadius: '5px',
}}
>
Some content here
</div>
</TogglePanelWidget>
<TogglePanelWidget anchor={['bottom', 'left']} position={['top', 'left']}>
<div
style={{
padding: '50px',
background: 'red',
border: 'solid 1px black',
borderRadius: '5px',
}}
>
Some other here
</div>
</TogglePanelWidget>
</div>
</div>,
container
);
|
cellbase-server/src/main/webapp/webservices/swagger-ui/lib/jquery-1.8.0.min.js | dapregi/cellbase | /*! jQuery [email protected] jquery.com | jquery.org/license */
(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); |
packages/material-ui-icons/src/InputSharp.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><g fill="none"><path d="M0 0h24v24H0V0z" /><path d="M0 0h24v24H0V0z" opacity=".87" /></g><path d="M21 3.01H3c-1.1 0-2 .9-2 2V9h2V4.99h18v14.03H3V15H1v4.01c0 1.1.9 1.98 2 1.98h18c1.1 0 2-.88 2-1.98v-14c0-1.11-.9-2-2-2zM11 16l4-4-4-4v3H1v2h10v3z" /><path d="M23 3.01H1V9h2V4.99h18v14.03H3V15H1v5.99h22V3.01zM11 16l4-4-4-4v3H1v2h10v3z" /></React.Fragment>
, 'InputSharp');
|
src/pages/index.js | meerasahib/meerablog1 | import React from 'react';
import Link from 'gatsby-link';
import Helmet from 'react-helmet';
import PostDate from '../components/Date';
import Preview from '../components/Preview';
import Tags from '../components/Tags';
const getParams = search => {
return search.replace('?', '').split('&').reduce((params, keyValue) => {
const [key, value = ''] = keyValue.split('=');
if (key && value) {
params[key] = value.match(/^\d+$/) ? +value : value;
}
return params;
}, {});
};
export default function Index({ data, location }) {
const { edges: posts } = data.allMarkdownRemark;
const { start = 0, end = 10 } = getParams(location.search);
return (
<div>
{posts
.filter(post => post.node.frontmatter.title.length > 0)
.slice(start, end)
.map(({ node: post }) => {
return (
<div key={post.id}>
<Preview
excerpt={post.frontmatter.description || post.excerpt}
date={post.frontmatter.date}
title={post.frontmatter.title}
to={post.frontmatter.path}
/>
</div>
);
})}
</div>
);
}
export const pageQuery = graphql`
query IndexQuery {
site {
siteMetadata {
title
author
}
}
allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
edges {
node {
excerpt(pruneLength: 250)
id
frontmatter {
date(formatString: "MMMM DD, YYYY")
path
tags
title
}
}
}
}
}
`;
|
client/src/app.js | MOOCFetcher/moocfetcher-appliance | import Main from './Main'
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(<Main />, document.getElementById('app'))
|
tests/routes/Home/components/HomeView.spec.js | vijayasankar/ML2.0 | import HomeView from 'routes/Home/components/HomeView'
import Link from 'react-router/lib/Link'
import React from 'react'
import { shallow, render, mount } from 'enzyme'
import ReduxFormStub from '../../../ReduxFormStub'
describe('(View) HomeView - instantiate', () => {
let component
beforeEach(() => {
component = new HomeView()
})
describe('tests for correct constructor', () => {
it('has a limit of 15', () => {
expect(component.limit).to.equal(6)
})
it('has 6 columns', () => {
expect(component.renderPreApprovalsColumns).to.have.length(6)
expect(component.renderPaymentsColumns).to.have.length(6)
})
describe('for this.renderPreApprovalsColumns', () => {
it('has correct headers', () => {
expect(render(component.renderPreApprovalsColumns[0].Header()).html()).to.equal('<span>Name</span>')
expect(render(component.renderPreApprovalsColumns[1].Header()).html()).to.equal('<span>Submitted</span>')
expect(render(component.renderPreApprovalsColumns[2].Header()).html()).to.equal('<span>Proposed date</span>')
expect(render(component.renderPreApprovalsColumns[3].Header()).html()).to.equal('<span>Status</span>')
expect(render(component.renderPreApprovalsColumns[4].Header()).html()).to.equal('<span>Pre-approval</span>')
expect(render(component.renderPreApprovalsColumns[5].Header()).html()).to.equal('<span>Payment</span>')
})
it('has correct accessor', () => {
expect(component.renderPreApprovalsColumns[0].accessor).to.equal('insuredPersonName')
expect(component.renderPreApprovalsColumns[1].accessor).to.equal('dateLodged')
expect(component.renderPreApprovalsColumns[2].accessor).to.equal('proposedDateOfProcedure')
expect(component.renderPreApprovalsColumns[3].accessor).to.equal('status')
expect(component.renderPreApprovalsColumns[4].accessor).to.equal('reference')
expect(component.renderPreApprovalsColumns[5].accessor).to.equal('payment')
})
it('has correct headerClassName', () => {
expect(component.renderPreApprovalsColumns[0].headerClassName).to.equal('is-name')
expect(component.renderPreApprovalsColumns[1].headerClassName).to.equal('is-submitted')
expect(component.renderPreApprovalsColumns[2].headerClassName).to.equal('is-proposed-date')
expect(component.renderPreApprovalsColumns[3].headerClassName).to.equal('is-status')
expect(component.renderPreApprovalsColumns[4].headerClassName).to.equal('is-pre-approval-number')
expect(component.renderPreApprovalsColumns[5].headerClassName).to.equal('is-payment')
})
it('has correct cells', () => {
expect(component.renderPreApprovalsColumns[0].Cell).to.not.exist
expect(render(component.renderPreApprovalsColumns[1].Cell({ value: '' })).html()).to.equal('<div></div>')
expect(render(component.renderPreApprovalsColumns[2].Cell({ value: '' })).html()).to.equal('<div></div>')
expect(component.renderPreApprovalsColumns[3].Cell).to.not.exist
expect(render(component.renderPreApprovalsColumns[4].Cell({
original: {}
})).html()).to.equal('<span></span>')
expect(render(component.renderPreApprovalsColumns[4].Cell({
original: {},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPreApprovalsColumns[4].Cell({
original: {
links: []
},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPreApprovalsColumns[4].Cell({
original: {
links: [
{
rel: '',
url: ''
}
]
},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPreApprovalsColumns[4].Cell({
original: {
links: [
{
rel: 'self',
url: ''
}
]
},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPreApprovalsColumns[4].Cell({
original: {
links: [
{
rel: 'pre-approval-advice-document',
url: 'aaa'
}
]
},
value: 'value'
})).html()).to.equal('<a target="_blank" href="aaa">value</a>')
expect(render(component.renderPreApprovalsColumns[5].Cell({ value: '' })).html()).to.equal('<span>Request payment</span>')
expect(render(component.renderPreApprovalsColumns[5].Cell({
value: 'Approved',
original: {
links: []
}
})).html()).to.equal('<span>Request payment</span>')
expect(render(component.renderPreApprovalsColumns[5].Cell({
value: '',
original: {
reference: undefined
}
})).html()).to.equal('<span>Request payment</span>')
expect(render(component.renderPreApprovalsColumns[5].Cell({
value: '',
original: {
reference: 123
}
})).html()).to.equal('<span>Request payment</span>')
expect(render(component.renderPreApprovalsColumns[5].Cell({
value: '',
original: {
reference: null
}
})).html()).to.equal('<span>Request payment</span>')
expect(component.renderPreApprovalsColumns[5].Cell({
value: '',
original: {
reference: 'aaa'
}
})).to.deep.equal(<Link to={`/providerportal/request-payment?preApprovalNumber=aaa`}>Request payment</Link>)
})
})
describe('for this.renderPaymentsColumns', () => {
it('has correct headers', () => {
expect(render(component.renderPaymentsColumns[0].Header()).html()).to.equal('<span>Name</span>')
expect(render(component.renderPaymentsColumns[1].Header()).html()).to.equal('<span>Submitted</span>')
expect(render(component.renderPaymentsColumns[2].Header()).html()).to.equal('<span>Date paid</span>')
expect(render(component.renderPaymentsColumns[3].Header()).html()).to.equal('<span>Status</span>')
expect(render(component.renderPaymentsColumns[4].Header()).html()).to.equal('<span>Pre-approval</span>')
expect(render(component.renderPaymentsColumns[5].Header()).html()).to.equal('<span>Payment</span>')
})
it('has correct cells', () => {
expect(component.renderPaymentsColumns[0].Cell).to.not.exist
expect(render(component.renderPaymentsColumns[1].Cell({ value: '' })).html()).to.equal('<div></div>')
expect(render(component.renderPaymentsColumns[2].Cell({ value: '' })).html()).to.equal('<div></div>')
expect(component.renderPaymentsColumns[3].Cell).to.not.exist
expect(render(component.renderPaymentsColumns[4].Cell({
original: {}
})).html()).to.equal('<span></span>')
expect(render(component.renderPaymentsColumns[4].Cell({
original: {},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPaymentsColumns[4].Cell({
original: {
links: []
},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPaymentsColumns[4].Cell({
original: {
links: [
{
rel: '',
url: ''
}
]
},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPaymentsColumns[4].Cell({
original: {
links: [
{
rel: 'self',
url: ''
}
]
},
value: 'value'
})).html()).to.equal('<span>value</span>')
expect(render(component.renderPaymentsColumns[4].Cell({
original: {
links: [
{
rel: 'claim-advice-document',
url: 'aaa'
}
]
},
value: 'value'
})).html()).to.equal('<a target="_blank" href="aaa">value</a>')
expect(render(component.renderPaymentsColumns[5].Cell({ value: '' })).html()).to.equal('<span></span>')
expect(render(component.renderPaymentsColumns[5].Cell({ value: 'something' })).html()).to.equal('<span class="is-payment">$ something</span>')
})
it('has correct accessor', () => {
expect(component.renderPaymentsColumns[0].accessor).to.equal('insuredPersonName')
expect(component.renderPaymentsColumns[1].accessor).to.equal('dateLodged')
expect(component.renderPaymentsColumns[2].accessor).to.equal('dateOfPayment')
expect(component.renderPaymentsColumns[3].accessor).to.equal('status')
expect(component.renderPaymentsColumns[4].accessor).to.equal('reference')
expect(component.renderPaymentsColumns[5].accessor).to.equal('paymentAmount')
})
it('has correct headerClassName', () => {
expect(component.renderPaymentsColumns[0].headerClassName).to.equal('is-name')
expect(component.renderPaymentsColumns[1].headerClassName).to.equal('is-submitted')
expect(component.renderPaymentsColumns[2].headerClassName).to.equal('is-date-paid')
expect(component.renderPaymentsColumns[3].headerClassName).to.equal('is-status')
expect(component.renderPaymentsColumns[4].headerClassName).to.equal('is-pre-approval-number')
expect(component.renderPaymentsColumns[5].headerClassName).to.equal('is-payment')
})
})
})
})
describe('(View) HomeView - shallow', () => {
let wrapper
let props
const spyLoadHomeLists = sinon.spy()
beforeEach(() => {
props = {
cssName: 'home',
currentProvider: {
name: ''
},
currentProviderDetails: {},
loadHomeLists: spyLoadHomeLists,
loadPaymentsList: () => {},
loadPreApprovalsList: () => {},
value: ''
}
wrapper = shallow(<HomeView {...props} />)
})
it('renders correct h1', () => {
wrapper.setProps({ currentProvider: { name: 'Provider Name' } })
expect(wrapper.find('h1').text()).to.equal('Provider Name')
})
it('has componentDidMount which calls prop loadHomeLists if there is a prop currentProviderDetails', () => {
wrapper.instance().componentDidMount()
expect(spyLoadHomeLists.callCount).to.equal(0)
wrapper.setProps({ currentProviderDetails: {} })
wrapper.instance().componentDidMount()
expect(spyLoadHomeLists.callCount).to.equal(0)
wrapper.setProps({ currentProviderDetails: { id: undefined } })
wrapper.instance().componentDidMount()
expect(spyLoadHomeLists.callCount).to.equal(0)
wrapper.setProps({ currentProviderDetails: { id: 123 } })
wrapper.instance().componentDidMount()
expect(spyLoadHomeLists.callCount).to.equal(0)
wrapper.setProps({ currentProviderDetails: { id: '' } })
wrapper.instance().componentDidMount()
expect(spyLoadHomeLists.callCount).to.equal(0)
wrapper.setProps({ currentProviderDetails: { id: 'aaa' } })
wrapper.instance().componentDidMount()
expect(spyLoadHomeLists.callCount).to.equal(1)
})
it('renders pre-approvals section if currentProvider is a specialist', () => {
expect(wrapper.find(`section.${props.cssName}__pre-approvals-section`)).to.not.exist
wrapper.setProps({
currentProvider: {
name: 'Provider Name'
},
currentProviderDetails: {
serviceTypes: 'Specialist'
},
preApprovalsList: [],
paymentsList: []
})
expect(wrapper.find(`section.${props.cssName}__pre-approvals-section`)).to.exist
})
it('prints out error messages for both preapprovals and payment', () => {
expect(wrapper.find(`div.${props.cssName}__pre-approvals-list-message`)).to.not.exist
expect(wrapper.find(`div.${props.cssName}__payments-list-message`)).to.not.exist
wrapper.setProps({
currentProvider: {
name: 'Provider Name'
},
currentProviderDetails: {
serviceTypes: 'Specialist'
},
preApprovalsList: [],
paymentsList: []
})
expect(wrapper.find(`div.${props.cssName}__pre-approvals-list-message`)).to.exist
expect(wrapper.find(`div.${props.cssName}__payments-list-message`)).to.exist
})
it('prints out two unique ReactTables when the lists are populated', () => {
expect(wrapper.find('ReactTable').find({ data: [{ name: 'preApprovals' }] })).to.have.length(0)
expect(wrapper.find('ReactTable').find({ data: [{ name: 'payments' }] })).to.have.length(0)
wrapper.setProps({
currentProvider: {
name: 'Provider Name'
},
currentProviderDetails: {
serviceTypes: 'Specialist'
},
preApprovalsList: [{
name: 'preApprovals'
}],
paymentsList: [{
name: 'payments'
}]
})
expect(wrapper.find('ReactTable').find({ data: [{ name: 'preApprovals' }] })).to.have.length(1)
expect(wrapper.find('ReactTable').find({ data: [{ name: 'payments' }] })).to.have.length(1)
})
it('prints out two "View all" links when two ReactTables are rendered (per table)', () => {
expect(wrapper.find('Link.is-pre-approvals')).to.have.length(0)
expect(wrapper.find('Link.is-payments')).to.have.length(0)
wrapper.setProps({
currentProvider: {
name: 'Provider Name'
},
currentProviderDetails: {
serviceTypes: 'Specialist'
},
preApprovalsList: [{
name: 'preApprovals'
}],
paymentsList: [{
name: 'payments'
}]
})
expect(wrapper.find('Link.is-pre-approvals')).to.have.length(1)
expect(wrapper.find('Link.is-payments')).to.have.length(1)
})
})
describe('(View) HomeView - mount', () => {
let props
let state
beforeEach(() => {
props = {
cssName: 'home',
currentProvider: {
name: ''
},
currentProviderDetails: {},
loadHomeLists: () => {},
loadPaymentsList: () => {},
loadPreApprovalsList: () => {},
value: ''
}
state = {}
})
it('componentDidMount is triggered successfully upon mount', () => {
const spyComponentDidMount = sinon.spy(HomeView.prototype, 'componentDidMount')
expect(spyComponentDidMount.callCount).to.equal(0)
mount(<ReduxFormStub><HomeView {...props} {...state} /></ReduxFormStub>)
expect(spyComponentDidMount.callCount).to.equal(1)
})
})
|
src/svg-icons/action/assignment-ind.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentInd = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 4c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H6v-1.4c0-2 4-3.1 6-3.1s6 1.1 6 3.1V19z"/>
</SvgIcon>
);
ActionAssignmentInd = pure(ActionAssignmentInd);
ActionAssignmentInd.displayName = 'ActionAssignmentInd';
ActionAssignmentInd.muiName = 'SvgIcon';
export default ActionAssignmentInd;
|
test/getApplicationKeyMap/GettingApplicationKeyMap.js | Chrisui/react-hotkeys | import React from 'react';
import {mount} from 'enzyme';
import {expect} from 'chai';
import sinon from 'sinon';
import {HotKeys, GlobalHotKeys} from '../../src/';
import {getApplicationKeyMap} from '../../src/';
describe('Getting the application key map:', () => {
context('when a keydown keymap is specified as string', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': 'enter'
};
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': { sequences: [{ sequence: 'enter' }] }
})
});
});
context('when a keydown keymap is specified as an object', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': {
sequence: 'enter',
action: 'keydown',
name: 'NAME',
description: 'DESC',
group: 'GROUP'
},
};
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': {
sequences: [{ sequence: 'enter', action: 'keydown' }],
name: 'NAME',
description: 'DESC',
group: 'GROUP'
}
})
});
});
context('when a keydown keymap is specified as an array of strings', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': ['enter','shift'],
};
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': { sequences: [{ sequence: 'enter' }, { sequence: 'shift' }] }
})
});
});
context('when a keydown keymap is specified as an array of objects', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': [{
sequence: 'enter',
action: 'keydown',
}, {
sequence: 'shift',
action: 'keydown',
}],
};
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': { sequences: [
{ sequence: 'enter', action: 'keydown' },
{ sequence: 'shift', action: 'keydown' }]
}
})
});
});
context('when a keydown keymap is specified as object with sequences attribute of an array of strings', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': {
sequences: ['enter', 'shift'],
name: 'NAME',
description: 'DESC',
group: 'GROUP'
},
};
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': {
sequences: [
{ sequence: 'enter' },
{ sequence: 'shift' }
],
name: 'NAME',
description: 'DESC',
group: 'GROUP'
}
})
});
});
context('when a keydown keymap is specified as object with sequences attribute of an array of objects', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': {
sequences: [
{sequence: 'enter', action: 'keydown'},
{sequence: 'shift', action: 'keydown'}
],
name: 'NAME',
description: 'DESC',
group: 'GROUP'
},
};
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': {
sequences: [
{ sequence: 'enter', action: 'keydown' },
{ sequence: 'shift', action: 'keydown' }
],
name: 'NAME',
description: 'DESC',
group: 'GROUP'
}
})
});
});
context('when component doesn\'t define any handlers', () => {
beforeEach(function () {
this.keyMap = {
'ACTION1': 'enter'
};
this.wrapper = mount(
<HotKeys keyMap={this.keyMap}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': {
sequences: [
{ sequence: 'enter' }
]
}
})
});
});
context('when component doesn\'t define any keyMap', () => {
beforeEach(function () {
this.handler = sinon.spy();
this.handlers = {
'ACTION1': this.handler,
};
this.wrapper = mount(
<HotKeys handlers={this.handlers}>
<div className="childElement" />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({})
});
});
context('when components are nested', () => {
beforeEach(function () {
this.wrapper = mount(
<HotKeys keyMap={{ 'ACTION1': 'enter' }}>
<HotKeys keyMap={{ 'ACTION2': 'enter' }}>
</HotKeys>
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': { sequences: [{ sequence: 'enter' }] },
'ACTION2': { sequences: [{ sequence: 'enter' }] }
})
});
});
context('when components are siblings', () => {
beforeEach(function () {
this.wrapper = mount(
<HotKeys keyMap={{ 'ACTION1': 'enter' }}>
<HotKeys keyMap={{ 'ACTION2': 'enter' }} />
<HotKeys keyMap={{ 'ACTION3': 'shift' }} />
</HotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION1': { sequences: [{ sequence: 'enter' }] },
'ACTION2': { sequences: [{ sequence: 'enter' }] },
'ACTION3': { sequences: [{ sequence: 'shift' }] }
})
});
});
context('when there are GlobalHotkeys and HotKeys components', () => {
beforeEach(function () {
this.wrapper = mount(
<GlobalHotKeys keyMap={{ 'ACTION0': 'cmd' }}>
<HotKeys keyMap={{ 'ACTION1': 'enter' }}>
<GlobalHotKeys keyMap={{ 'ACTION2': 'enter' }} />
<HotKeys keyMap={{ 'ACTION3': 'shift' }} />
</HotKeys>
</GlobalHotKeys>
);
});
it('generates the correct application key map', function() {
expect(getApplicationKeyMap()).to.eql({
'ACTION0': { sequences: [{ sequence: 'cmd' }] },
'ACTION1': { sequences: [{ sequence: 'enter' }] },
'ACTION2': { sequences: [{ sequence: 'enter' }] },
'ACTION3': { sequences: [{ sequence: 'shift' }] }
})
});
});
});
|
ajax/libs/ember-data.js/1.0.0-beta.19.2/ember-data.prod.js | wout/cdnjs | (function() {
"use strict";
var ember$data$lib$system$model$errors$invalid$$create = Ember.create;
var ember$data$lib$system$model$errors$invalid$$EmberError = Ember.Error;
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
For Ember Data to correctly map errors to their corresponding
properties on the model, Ember Data expects each error to be
namespaced under a key that matches the property name. For example
if you had a Post model that looked like this.
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string')
});
```
To show an error from the server related to the `title` and
`content` properties your adapter could return a promise that
rejects with a `DS.InvalidError` object that looks like this:
```app/adapters/post.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
updateRecord: function() {
// Fictional adapter that always rejects
return Ember.RSVP.reject(new DS.InvalidError({
title: ['Must be unique'],
content: ['Must not be blank'],
}));
}
});
```
Your backend may use different property names for your records the
store will attempt extract and normalize the errors using the
serializer's `extractErrors` method before the errors get added to
the the model. As a result, it is safe for the `InvalidError` to
wrap the error payload unaltered.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
// 422 is used by this fictional server to signal a validation error
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError(jsonErrors);
} else {
// The ajax request failed however it is not a result of this
// record being in an invalid state so we do not return a
// `InvalidError` object.
return error;
}
}
});
```
@class InvalidError
@namespace DS
*/
function ember$data$lib$system$model$errors$invalid$$InvalidError(errors) {
ember$data$lib$system$model$errors$invalid$$EmberError.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
}
ember$data$lib$system$model$errors$invalid$$InvalidError.prototype = ember$data$lib$system$model$errors$invalid$$create(ember$data$lib$system$model$errors$invalid$$EmberError.prototype);
var ember$data$lib$system$model$errors$invalid$$default = ember$data$lib$system$model$errors$invalid$$InvalidError;
/**
@module ember-data
*/
var ember$data$lib$system$adapter$$get = Ember.get;
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but
may be anything, such as the browser's local storage. Typically the
adapter is not invoked directly instead its functionality is accessed
through the `store`.
### Creating an Adapter
Create a new subclass of `DS.Adapter` in the `app/adapters` folder:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
// ...your code here
});
```
Model-specific adapters can be created by putting your adapter
class in an `app/adapters/` + `model-name` + `.js` file of the application.
```app/adapters/post.js
import DS from 'ember-data';
export default DS.Adapter.extend({
// ...Post-specific adapter code goes here
});
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
* `findAll()`
* `findQuery()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
var ember$data$lib$system$adapter$$Adapter = Ember.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority than
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```app/adapters/django.js
import DS from 'ember-data';
export default DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
defaultSerializer: '-default',
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
find: function(store, type, id, snapshot) {
var url = [type.modelName, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method find
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
find: null,
/**
The `findAll()` method is called when you call `find` on the store
without an ID (i.e. `store.find('post')`).
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
findAll: function(store, type, sinceToken) {
var url = type;
var query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `find` on the store with a
query object as the second parameter (i.e. `store.find('person', {
page: 1 })`).
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
findQuery: function(store, type, query) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findQuery
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, inputProperties) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {(String|Number)} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var url = type;
// ...
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} serialized snapshot
*/
serialize: function (snapshot, options) {
return ember$data$lib$system$adapter$$get(snapshot.record, 'store').serializerFor(snapshot.modelName).serialize(snapshot, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: null,
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
updateRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var id = snapshot.id;
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: null,
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
deleteRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var id = snapshot.id;
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'DELETE',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: null,
/**
By default the store will try to coalesce all `fetchRecord` calls within the same runloop
into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call.
You can opt out of this behaviour by either not implementing the findMany hook or by setting
coalesceFindRequests to false
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: true,
/**
Find multiple records at once if coalesceFindRequests is true
@method findMany
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the records
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
For example, if your api has nested URLs that depend on the parent, you will
want to group records by their parent.
The default implementation returns the records as a single group.
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} snapshots
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, snapshots) {
return [snapshots];
}
});
var ember$data$lib$system$adapter$$default = ember$data$lib$system$adapter$$Adapter;
/**
@module ember-data
*/
var ember$data$lib$adapters$fixture$adapter$$get = Ember.get;
var ember$data$lib$adapters$fixture$adapter$$fmt = Ember.String.fmt;
var ember$data$lib$adapters$fixture$adapter$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$adapters$fixture$adapter$$counter = 0;
var ember$data$lib$adapters$fixture$adapter$$default = ember$data$lib$system$adapter$$default.extend({
// by default, fixtures are already in normalized form
serializer: null,
// The fixture adapter does not support coalesceFindRequests
coalesceFindRequests: false,
/**
If `simulateRemoteResponse` is `true` the `FixtureAdapter` will
wait a number of milliseconds before resolving promises with the
fixture values. The wait time can be configured via the `latency`
property.
@property simulateRemoteResponse
@type {Boolean}
@default true
*/
simulateRemoteResponse: true,
/**
By default the `FixtureAdapter` will simulate a wait of the
`latency` milliseconds before resolving promises with the fixture
values. This behavior can be turned off via the
`simulateRemoteResponse` property.
@property latency
@type {Number}
@default 50
*/
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param {DS.Model} typeClass
@return {Array}
*/
fixturesForType: function (typeClass) {
if (typeClass.FIXTURES) {
var fixtures = Ember.A(typeClass.FIXTURES);
return fixtures.map(function (fixture) {
var fixtureIdType = typeof fixture.id;
if (fixtureIdType !== "number" && fixtureIdType !== "string") {
throw new Error(ember$data$lib$adapters$fixture$adapter$$fmt("the id property must be defined as a number or string for fixture %@", [fixture]));
}
fixture.id = fixture.id + "";
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param {Array} fixtures
@param {Object} query
@param {DS.Model} typeClass
@return {(Promise|Array)}
*/
queryFixtures: function (fixtures, query, typeClass) {
},
/**
@method updateFixtures
@param {DS.Model} typeClass
@param {Array} fixture
*/
updateFixtures: function (typeClass, fixture) {
if (!typeClass.FIXTURES) {
typeClass.FIXTURES = [];
}
var fixtures = typeClass.FIXTURES;
this.deleteLoadedFixture(typeClass, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
*/
mockJSON: function (store, typeClass, snapshot) {
return store.serializerFor(snapshot.modelName).serialize(snapshot, { includeId: true });
},
/**
@method generateIdForRecord
@param {DS.Store} store
@return {String} id
*/
generateIdForRecord: function (store) {
return "fixture-" + ember$data$lib$adapters$fixture$adapter$$counter++;
},
/**
@method find
@param {DS.Store} store
@param {DS.Model} typeClass
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
find: function (store, typeClass, id, snapshot) {
var fixtures = this.fixturesForType(typeClass);
var fixture;
if (fixtures) {
fixture = Ember.A(fixtures).findBy("id", id);
}
if (fixture) {
return this.simulateRemoteCall(function () {
return fixture;
}, this);
}
},
/**
@method findMany
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: function (store, typeClass, ids, snapshots) {
var fixtures = this.fixturesForType(typeClass);
if (fixtures) {
fixtures = fixtures.filter(function (item) {
return ember$data$lib$adapters$fixture$adapter$$indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function () {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param {DS.Store} store
@param {DS.Model} typeClass
@return {Promise} promise
*/
findAll: function (store, typeClass) {
var fixtures = this.fixturesForType(typeClass);
return this.simulateRemoteCall(function () {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} array
@return {Promise} promise
*/
findQuery: function (store, typeClass, query, array) {
var fixtures = this.fixturesForType(typeClass);
fixtures = this.queryFixtures(fixtures, query, typeClass);
if (fixtures) {
return this.simulateRemoteCall(function () {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: function (store, typeClass, snapshot) {
var fixture = this.mockJSON(store, typeClass, snapshot);
this.updateFixtures(typeClass, fixture);
return this.simulateRemoteCall(function () {
return fixture;
}, this);
},
/**
@method updateRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function (store, typeClass, snapshot) {
var fixture = this.mockJSON(store, typeClass, snapshot);
this.updateFixtures(typeClass, fixture);
return this.simulateRemoteCall(function () {
return fixture;
}, this);
},
/**
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: function (store, typeClass, snapshot) {
this.deleteLoadedFixture(typeClass, snapshot);
return this.simulateRemoteCall(function () {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param typeClass
@param snapshot
*/
deleteLoadedFixture: function (typeClass, snapshot) {
var existingFixture = this.findExistingFixture(typeClass, snapshot);
if (existingFixture) {
var index = ember$data$lib$adapters$fixture$adapter$$indexOf(typeClass.FIXTURES, existingFixture);
typeClass.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param typeClass
@param snapshot
*/
findExistingFixture: function (typeClass, snapshot) {
var fixtures = this.fixturesForType(typeClass);
var id = snapshot.id;
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param fixtures
@param id
*/
findFixtureById: function (fixtures, id) {
return Ember.A(fixtures).find(function (r) {
if ("" + ember$data$lib$adapters$fixture$adapter$$get(r, "id") === "" + id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function (callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function (resolve) {
var value = Ember.copy(callback.call(context), true);
if (ember$data$lib$adapters$fixture$adapter$$get(adapter, "simulateRemoteResponse")) {
// Schedule with setTimeout
Ember.run.later(function () {
resolve(value);
}, ember$data$lib$adapters$fixture$adapter$$get(adapter, "latency"));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule("actions", null, function () {
resolve(value);
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
var ember$data$lib$system$map$$Map = Ember.Map;
var ember$data$lib$system$map$$MapWithDefault = Ember.MapWithDefault;
var ember$data$lib$system$map$$default = ember$data$lib$system$map$$Map;
var ember$data$lib$adapters$build$url$mixin$$get = Ember.get;
var ember$data$lib$adapters$build$url$mixin$$default = Ember.Mixin.create({
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
When called by RESTAdapter.findMany() the `id` and `snapshot` parameters
will be arrays of ids and snapshots.
@method buildURL
@param {String} modelName
@param {(String|Array|Object)} id single id or array of ids or query
@param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots
@param {String} requestType
@param {Object} query object of query parameters to send for findQuery requests.
@return {String} url
*/
buildURL: function (modelName, id, snapshot, requestType, query) {
switch (requestType) {
case 'find':
return this.urlForFind(id, modelName, snapshot);
case 'findAll':
return this.urlForFindAll(modelName);
case 'findQuery':
return this.urlForFindQuery(query, modelName);
case 'findMany':
return this.urlForFindMany(id, modelName, snapshot);
case 'findHasMany':
return this.urlForFindHasMany(id, modelName);
case 'findBelongsTo':
return this.urlForFindBelongsTo(id, modelName);
case 'createRecord':
return this.urlForCreateRecord(modelName, snapshot);
case 'updateRecord':
return this.urlForUpdateRecord(id, modelName, snapshot);
case 'deleteRecord':
return this.urlForDeleteRecord(id, modelName, snapshot);
default:
return this._buildURL(modelName, id);
}
},
/**
@method _buildURL
@private
@param {String} modelName
@param {String} id
@return {String} url
*/
_buildURL: function (modelName, id) {
var url = [];
var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host');
var prefix = this.urlPrefix();
var path;
if (modelName) {
path = this.pathForType(modelName);
if (path) {
url.push(path);
}
}
if (id) {
url.push(encodeURIComponent(id));
}
if (prefix) {
url.unshift(prefix);
}
url = url.join('/');
if (!host && url && url.charAt(0) !== '/') {
url = '/' + url;
}
return url;
},
/**
* @method urlForFind
* @param {String} id
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForFind: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
* @method urlForFindAll
* @param {String} modelName
* @return {String} url
*/
urlForFindAll: function (modelName) {
return this._buildURL(modelName);
},
/**
* @method urlForFindQuery
* @param {Object} query
* @param {String} modelName
* @return {String} url
*/
urlForFindQuery: function (query, modelName) {
return this._buildURL(modelName);
},
/**
* @method urlForFindMany
* @param {Array} ids
* @param {String} modelName
* @param {Array} snapshots
* @return {String} url
*/
urlForFindMany: function (ids, modelName, snapshots) {
return this._buildURL(modelName);
},
/**
* @method urlForFindHasMany
* @param {String} id
* @param {String} modelName
* @return {String} url
*/
urlForFindHasMany: function (id, modelName) {
return this._buildURL(modelName, id);
},
/**
* @method urlForFindBelongTo
* @param {String} id
* @param {String} modelName
* @return {String} url
*/
urlForFindBelongsTo: function (id, modelName) {
return this._buildURL(modelName, id);
},
/**
* @method urlForCreateRecord
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForCreateRecord: function (modelName, snapshot) {
return this._buildURL(modelName);
},
/**
* @method urlForUpdateRecord
* @param {String} id
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForUpdateRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
* @method urlForDeleteRecord
* @param {String} id
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForDeleteRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentURL
@return {String} urlPrefix
*/
urlPrefix: function (path, parentURL) {
var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host');
var namespace = ember$data$lib$adapters$build$url$mixin$$get(this, 'namespace');
var url = [];
if (path) {
// Protocol relative url
//jscs:disable disallowEmptyBlocks
if (/^\/\//.test(path)) {} else if (path.charAt(0) === '/') {
//jscs:enable disallowEmptyBlocks
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) {
url.push(host);
}
if (namespace) {
url.push(namespace);
}
}
if (path) {
url.push(path);
}
return url.join('/');
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
pathForType: function(modelName) {
var decamelized = Ember.String.decamelize(modelName);
return Ember.String.pluralize(decamelized);
}
});
```
@method pathForType
@param {String} modelName
@return {String} path
**/
pathForType: function (modelName) {
var camelized = Ember.String.camelize(modelName);
return Ember.String.pluralize(camelized);
}
});
var ember$data$lib$adapters$rest$adapter$$get = Ember.get;
var ember$data$lib$adapters$rest$adapter$$set = Ember.set;
var ember$data$lib$adapters$rest$adapter$$forEach = Ember.ArrayPolyfills.forEach;/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"post": {
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
Similarly, in response to a `GET` request for `/posts`, the JSON should
look like this:
```js
{
"posts": [
{
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
},
{
"id": 2,
"title": "Rails is omakase",
"author": "D2H"
}
]
}
```
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"person": {
"id": 5,
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
}
```
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for `App.Person` would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
object and Ember Data will send them along with each ajax request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
`headers` can also be used as a computed property to support dynamic
headers. In the example below, the `session` object has been
injected into an adapter by Ember's container.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: function() {
return {
"API_KEY": this.get("session.authToken"),
"ANOTHER_HEADER": "Some header value"
};
}.property("session.authToken")
});
```
In some cases, your dynamic headers may require data from some
object outside of Ember's observer system (for example
`document.cookie`). You can use the
[volatile](/api/classes/Ember.ComputedProperty.html#method_volatile)
function to set the property into a non-cached mode causing the headers to
be recomputed with every request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: function() {
return {
"API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"),
"ANOTHER_HEADER": "Some header value"
};
}.property().volatile()
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
@uses DS.BuildURLMixin
*/
var ember$data$lib$adapters$rest$adapter$$RestAdapter = ember$data$lib$system$adapter$$Adapter.extend(ember$data$lib$adapters$build$url$mixin$$default, {
defaultSerializer: "-rest",
/**
By default, the RESTAdapter will send the query params sorted alphabetically to the
server.
For example:
```js
store.find('posts', {sort: 'price', category: 'pets'});
```
will generate a requests like this `/posts?category=pets&sort=price`, even if the
parameters were specified in a different order.
That way the generated URL will be deterministic and that simplifies caching mechanisms
in the backend.
Setting `sortQueryParams` to a falsey value will respect the original order.
In case you want to sort the query parameters with a different criteria, set
`sortQueryParams` to your custom sort function.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
sortQueryParams: function(params) {
var sortedKeys = Object.keys(params).sort().reverse();
var len = sortedKeys.length, newParams = {};
for (var i = 0; i < len; i++) {
newParams[sortedKeys[i]] = params[sortedKeys[i]];
}
return newParams;
}
});
```
@method sortQueryParams
@param {Object} obj
@return {Object}
*/
sortQueryParams: function (obj) {
var keys = Ember.keys(obj);
var len = keys.length;
if (len < 2) {
return obj;
}
var newQueryParams = {};
var sortedKeys = keys.sort();
for (var i = 0; i < len; i++) {
newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]];
}
return newQueryParams;
},
/**
By default the RESTAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
```javascript
{
post: {
id: 1,
comments: [1, 2]
}
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?ids[]=1&ids[]=2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.find('comment', 1);
store.find('comment', 2);
```
will also send a request to: `GET /comments?ids[]=1&ids[]=2`
Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app
`groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for `App.Post` would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
Requests for `App.Post` would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API
key. Arbitrary headers can be set as key/value pairs on the
`RESTAdapter`'s `headers` object and Ember Data will send them
along with each ajax request. For dynamic headers see [headers
customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@method find
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
find: function (store, type, id, snapshot) {
return this.ajax(this.buildURL(type.modelName, id, snapshot, "find"), "GET");
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function (store, type, sinceToken) {
var query, url;
if (sinceToken) {
query = { since: sinceToken };
}
url = this.buildURL(type.modelName, null, null, "findAll");
return this.ajax(url, "GET", { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
findQuery: function (store, type, query) {
var url = this.buildURL(type.modelName, null, null, "findQuery", query);
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(url, "GET", { data: query });
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {DS.Model} type
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: function (store, type, ids, snapshots) {
var url = this.buildURL(type.modelName, ids, snapshots, "findMany");
return this.ajax(url, "GET", { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findHasMany
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@param {String} url
@return {Promise} promise
*/
findHasMany: function (store, snapshot, url, relationship) {
var id = snapshot.id;
var type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, null, "findHasMany"));
return this.ajax(url, "GET");
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@param {String} url
@return {Promise} promise
*/
findBelongsTo: function (store, snapshot, url, relationship) {
var id = snapshot.id;
var type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, null, "findBelongsTo"));
return this.ajax(url, "GET");
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: function (store, type, snapshot) {
var data = {};
var serializer = store.serializerFor(type.modelName);
var url = this.buildURL(type.modelName, null, snapshot, "createRecord");
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
return this.ajax(url, "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function (store, type, snapshot) {
var data = {};
var serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot);
var id = snapshot.id;
var url = this.buildURL(type.modelName, id, snapshot, "updateRecord");
return this.ajax(url, "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: function (store, type, snapshot) {
var id = snapshot.id;
return this.ajax(this.buildURL(type.modelName, id, snapshot, "deleteRecord"), "DELETE");
},
_stripIDFromURL: function (store, snapshot) {
var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot);
var expandedURL = url.split("/");
//Case when the url is of the format ...something/:id
var lastSegment = expandedURL[expandedURL.length - 1];
var id = snapshot.id;
if (lastSegment === id) {
expandedURL[expandedURL.length - 1] = "";
} else if (ember$data$lib$adapters$rest$adapter$$endsWith(lastSegment, "?id=" + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
return expandedURL.join("/");
},
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
maxURLLength: 2048,
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
This implementation groups together records that have the same base URL but
differing ids. For example `/comments/1` and `/comments/2` will be grouped together
because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2`
It also supports urls where ids are passed as a query param, such as `/comments?id=1`
but not those where there is more than 1 query param such as `/comments?id=2&name=David`
Currently only the query param of `id` is supported. If you need to support others, please
override this or the `_stripIDFromURL` method.
It does not group records that have differing base urls, such as for example: `/posts/1/comments/2`
and `/posts/2/comments/3`
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} snapshots
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, snapshots) {
var groups = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function () {
return [];
} });
var adapter = this;
var maxURLLength = this.maxURLLength;
ember$data$lib$adapters$rest$adapter$$forEach.call(snapshots, function (snapshot) {
var baseUrl = adapter._stripIDFromURL(store, snapshot);
groups.get(baseUrl).push(snapshot);
});
function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) {
var baseUrl = adapter._stripIDFromURL(store, group[0]);
var idsSize = 0;
var splitGroups = [[]];
ember$data$lib$adapters$rest$adapter$$forEach.call(group, function (snapshot) {
var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength;
if (baseUrl.length + idsSize + additionalLength >= maxURLLength) {
idsSize = 0;
splitGroups.push([]);
}
idsSize += additionalLength;
var lastGroupIndex = splitGroups.length - 1;
splitGroups[lastGroupIndex].push(snapshot);
});
return splitGroups;
}
var groupsArray = [];
groups.forEach(function (group, key) {
var paramNameLength = "&ids%5B%5D=".length;
var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength);
ember$data$lib$adapters$rest$adapter$$forEach.call(splitGroups, function (splitGroup) {
groupsArray.push(splitGroup);
});
});
return groupsArray;
},
/**
Takes an ajax response, and returns an error payload.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record. When returning an
`InvalidError` the store will attempt to normalize the error data
returned from the server using the serializer's `extractErrors`
method.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
Note: As a correctness optimization, the default implementation of
the `ajaxError` method strips out the `then` method from jquery's
ajax response (jqXHR). This is important because the jqXHR's
`then` method fulfills the promise with itself resulting in a
circular "thenable" chain which may cause problems for some
promise libraries.
@method ajaxError
@param {Object} jqXHR
@param {Object} responseText
@param {Object} errorThrown
@return {Object} jqXHR
*/
ajaxError: function (jqXHR, responseText, errorThrown) {
var isObject = jqXHR !== null && typeof jqXHR === "object";
if (isObject) {
jqXHR.then = null;
if (!jqXHR.errorThrown) {
if (typeof errorThrown === "string") {
jqXHR.errorThrown = new Error(errorThrown);
} else {
jqXHR.errorThrown = errorThrown;
}
}
}
return jqXHR;
},
/**
Takes an ajax response, and returns the json payload.
By default this hook just returns the jsonPayload passed to it.
You might want to override it in two cases:
1. Your API might return useful results in the request headers.
If you need to access these, you can override this hook to copy them
from jqXHR to the payload object so they can be processed in you serializer.
2. Your API might return errors as successful responses with status code
200 and an Errors text or object. You can return a DS.InvalidError from
this hook and it will automatically reject the promise and put your record
into the invalid state.
@method ajaxSuccess
@param {Object} jqXHR
@param {Object} jsonPayload
@return {Object} jsonPayload
*/
ajaxSuccess: function (jqXHR, jsonPayload) {
return jsonPayload;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Promise} promise
*/
ajax: function (url, type, options) {
var adapter = this;
return new Ember.RSVP.Promise(function (resolve, reject) {
var hash = adapter.ajaxOptions(url, type, options);
hash.success = function (json, textStatus, jqXHR) {
json = adapter.ajaxSuccess(jqXHR, json);
if (json instanceof ember$data$lib$system$model$errors$invalid$$default) {
Ember.run(null, reject, json);
} else {
Ember.run(null, resolve, json);
}
};
hash.error = function (jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText, errorThrown));
};
Ember.$.ajax(hash);
}, "DS: RESTAdapter#ajax " + type + " to " + url);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Object}
*/
ajaxOptions: function (url, type, options) {
var hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = "json";
hash.context = this;
if (hash.data && type !== "GET") {
hash.contentType = "application/json; charset=utf-8";
hash.data = JSON.stringify(hash.data);
}
var headers = ember$data$lib$adapters$rest$adapter$$get(this, "headers");
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
ember$data$lib$adapters$rest$adapter$$forEach.call(Ember.keys(headers), function (key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function ember$data$lib$adapters$rest$adapter$$endsWith(string, suffix) {
if (typeof String.prototype.endsWith !== "function") {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
} else {
return string.endsWith(suffix);
}
}
if (Ember.platform.hasPropertyAccessors) {
Ember.defineProperty(ember$data$lib$adapters$rest$adapter$$RestAdapter.prototype, "maxUrlLength", {
enumerable: false,
get: function () {
return this.maxURLLength;
},
set: function (value) {
ember$data$lib$adapters$rest$adapter$$set(this, "maxURLLength", value);
}
});
}
var ember$data$lib$adapters$rest$adapter$$default = ember$data$lib$adapters$rest$adapter$$RestAdapter;
var ember$lib$main$$default = Ember;
var ember$inflector$lib$lib$system$inflector$$capitalize = ember$lib$main$$default.String.capitalize;
var ember$inflector$lib$lib$system$inflector$$BLANK_REGEX = /^\s*$/;
var ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX = /([\w/-]+[_/-])([a-z\d]+$)/;
var ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX = /([\w/-]+)([A-Z][a-z\d]*$)/;
var ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX = /[A-Z][a-z\d]*$/;
function ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function ember$inflector$lib$lib$system$inflector$$loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
//pluralizing
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregular[pair[1].toLowerCase()] = pair[1];
//singularizing
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
rules.irregularInverse[pair[0].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow'); //=> 'kine'
inflector.singularize('kine'); //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice'); // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice'); // => 'advice'
inflector.pluralize('formula'); // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula'); // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function ember$inflector$lib$lib$system$inflector$$Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || ember$inflector$lib$lib$system$inflector$$makeDictionary();
ruleSet.irregularPairs = ruleSet.irregularPairs || ember$inflector$lib$lib$system$inflector$$makeDictionary();
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: ember$inflector$lib$lib$system$inflector$$makeDictionary(),
irregularInverse: ember$inflector$lib$lib$system$inflector$$makeDictionary(),
uncountable: ember$inflector$lib$lib$system$inflector$$makeDictionary()
};
ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, ruleSet.uncountable);
ember$inflector$lib$lib$system$inflector$$loadIrregular(rules, ruleSet.irregularPairs);
this.enableCache();
}
if (!Object.create && !Object.create(null).hasOwnProperty) {
throw new Error('This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg');
}
function ember$inflector$lib$lib$system$inflector$$makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
ember$inflector$lib$lib$system$inflector$$Inflector.prototype = {
/**
@public
As inflections can be costly, and commonly the same subset of words are repeatedly
inflected an optional cache is provided.
@method enableCache
*/
enableCache: function () {
this.purgeCache();
this.singularize = function (word) {
this._cacheUsed = true;
return this._sCache[word] || (this._sCache[word] = this._singularize(word));
};
this.pluralize = function (word) {
this._cacheUsed = true;
return this._pCache[word] || (this._pCache[word] = this._pluralize(word));
};
},
/**
@public
@method purgedCache
*/
purgeCache: function () {
this._cacheUsed = false;
this._sCache = ember$inflector$lib$lib$system$inflector$$makeDictionary();
this._pCache = ember$inflector$lib$lib$system$inflector$$makeDictionary();
},
/**
@public
disable caching
@method disableCache;
*/
disableCache: function () {
this._sCache = null;
this._pCache = null;
this.singularize = function (word) {
return this._singularize(word);
};
this.pluralize = function (word) {
return this._pluralize(word);
};
},
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function (regex, string) {
if (this._cacheUsed) {
this.purgeCache();
}
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function (regex, string) {
if (this._cacheUsed) {
this.purgeCache();
}
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function (string) {
if (this._cacheUsed) {
this.purgeCache();
}
ember$inflector$lib$lib$system$inflector$$loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
if (this._cacheUsed) {
this.purgeCache();
}
ember$inflector$lib$lib$system$inflector$$loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function (word) {
return this._pluralize(word);
},
_pluralize: function (word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function (word) {
return this._singularize(word);
},
_singularize: function (word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function (word, typeRules, irregular) {
var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, isUncountable, isIrregular, rule;
isBlank = !word || ember$inflector$lib$lib$system$inflector$$BLANK_REGEX.test(word);
isCamelized = ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX.test(word);
firstPhrase = '';
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
wordSplit = ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX.exec(word) || ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX.exec(word);
if (wordSplit) {
firstPhrase = wordSplit[1];
lastWord = wordSplit[2].toLowerCase();
}
isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord];
if (isUncountable) {
return word;
}
isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]);
if (isIrregular) {
if (irregular[lowercase]) {
return isIrregular;
} else {
isIrregular = isCamelized ? ember$inflector$lib$lib$system$inflector$$capitalize(isIrregular) : isIrregular;
return firstPhrase + isIrregular;
}
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i - 1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
var ember$inflector$lib$lib$system$inflector$$default = ember$inflector$lib$lib$system$inflector$$Inflector;
function ember$inflector$lib$lib$system$string$$pluralize(word) {
return ember$inflector$lib$lib$system$inflector$$default.inflector.pluralize(word);
}
function ember$inflector$lib$lib$system$string$$singularize(word) {
return ember$inflector$lib$lib$system$inflector$$default.inflector.singularize(word);
}
var ember$inflector$lib$lib$system$inflections$$default = {
plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']],
singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']],
irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']],
uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police']
};
ember$inflector$lib$lib$system$inflector$$default.inflector = new ember$inflector$lib$lib$system$inflector$$default(ember$inflector$lib$lib$system$inflections$$default);
var ember$inflector$lib$lib$utils$register$helper$$default = ember$inflector$lib$lib$utils$register$helper$$registerHelper;
function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, helperFunction) {
//earlier versions of ember with htmlbars used this
ember$lib$main$$default.HTMLBars.helpers[name] = helperFunction;
}
function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, helperFunction) {
//registerHelper has been made private as _registerHelper
//this is kept here if anyone is using it
ember$lib$main$$default.HTMLBars.registerHelper(name, helperFunction);
}
function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, helperFunction) {
//latest versin of ember uses this
ember$lib$main$$default.HTMLBars._registerHelper(name, helperFunction);
}
function ember$inflector$lib$lib$utils$register$helper$$registerHelper(name, helperFunction) {
if (ember$lib$main$$default.HTMLBars) {
var fn = ember$lib$main$$default.HTMLBars.makeBoundHelper(helperFunction);
if (ember$lib$main$$default.HTMLBars._registerHelper) {
if (ember$lib$main$$default.HTMLBars.helpers) {
ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, fn);
} else {
ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, fn);
}
} else if (ember$lib$main$$default.HTMLBars.registerHelper) {
ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, fn);
}
} else if (ember$lib$main$$default.Handlebars) {
ember$lib$main$$default.Handlebars.helper(name, helperFunction);
}
}
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* singularize a word. For example, turn "oxen" into "ox".
*
* Example:
*
* {{singularize myProperty}}
* {{singularize "oxen"}}
*
* @for Ember.HTMLBars.helpers
* @method singularize
* @param {String|Property} word word to singularize
*/
ember$inflector$lib$lib$utils$register$helper$$default('singularize', function (params) {
return ember$inflector$lib$lib$system$string$$singularize(params[0]);
});
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* pluralize a word. For example, turn "ox" into "oxen".
*
* Example:
*
* {{pluralize count myProperty}}
* {{pluralize 1 "oxen"}}
* {{pluralize myProperty}}
* {{pluralize "ox"}}
*
* @for Ember.HTMLBars.helpers
* @method pluralize
* @param {Number|Property} [count] count of objects
* @param {String|Property} word word to pluralize
*/
ember$inflector$lib$lib$utils$register$helper$$default('pluralize', function (params) {
var count, word;
if (params.length === 1) {
word = params[0];
return ember$inflector$lib$lib$system$string$$pluralize(word);
} else {
count = params[0];
word = params[1];
if (count !== 1) {
word = ember$inflector$lib$lib$system$string$$pluralize(word);
}
return count + ' ' + word;
}
});
if (ember$lib$main$$default.EXTEND_PROTOTYPES === true || ember$lib$main$$default.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function () {
return ember$inflector$lib$lib$system$string$$pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function () {
return ember$inflector$lib$lib$system$string$$singularize(this);
};
}
ember$inflector$lib$lib$system$inflector$$default.defaultRules = ember$inflector$lib$lib$system$inflections$$default;
ember$lib$main$$default.Inflector = ember$inflector$lib$lib$system$inflector$$default;
ember$lib$main$$default.String.pluralize = ember$inflector$lib$lib$system$string$$pluralize;
ember$lib$main$$default.String.singularize = ember$inflector$lib$lib$system$string$$singularize;
var ember$inflector$lib$main$$default = ember$inflector$lib$lib$system$inflector$$default;
if (typeof define !== "undefined" && define.amd) {
define("ember-inflector", ["exports"], function (__exports__) {
__exports__["default"] = ember$inflector$lib$lib$system$inflector$$default;
return ember$inflector$lib$lib$system$inflector$$default;
});
} else if (typeof module !== "undefined" && module["exports"]) {
module["exports"] = ember$inflector$lib$lib$system$inflector$$default;
}
/**
@module ember-data
*/
var activemodel$adapter$lib$system$active$model$adapter$$decamelize = Ember.String.decamelize;
var activemodel$adapter$lib$system$active$model$adapter$$underscore = Ember.String.underscore;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
Unlike the DS.RESTAdapter, async relationship keys must be the singular form
of the relationship name, followed by "_id" for DS.belongsTo relationships,
or "_ids" for DS.hasMany relationships.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.RESTAdapter
**/
var activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter = ember$data$lib$adapters$rest$adapter$$default.extend({
defaultSerializer: "-active-model",
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} modelName
@return String
*/
pathForType: function (modelName) {
var decamelized = activemodel$adapter$lib$system$active$model$adapter$$decamelize(modelName);
var underscored = activemodel$adapter$lib$system$active$model$adapter$$underscore(decamelized);
return ember$inflector$lib$lib$system$string$$pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param {Object} jqXHR
@return error
*/
ajaxError: function (jqXHR) {
var error = this._super.apply(this, arguments);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText);
return new ember$data$lib$system$model$errors$invalid$$default(response);
} else {
return error;
}
}
});
var activemodel$adapter$lib$system$active$model$adapter$$default = activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter;
var ember$data$lib$system$serializer$$Serializer = Ember.Object.extend({
/**
The `store` property is the application's `store` that contains all records.
It's injected as a service.
It can be used to push records from a non flat data structure server
response.
@property store
@type {DS.Store}
@public
*/
/**
The `extract` method is used to deserialize the payload received from your
data source into the form that Ember Data expects.
@method extract
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object}
*/
extract: null,
/**
The `serialize` method is used when a record is saved in order to convert
the record into the form that your external data source expects.
`serialize` takes an optional `options` hash with a single option:
- `includeId`: If this is `true`, `serialize` should include the ID
in the serialized object it builds.
@method serialize
@param {DS.Model} record
@param {Object} [options]
@return {Object}
*/
serialize: null,
/**
The `normalize` method is used to convert a payload received from your
external data source into the normalized form `store.push()` expects. You
should override this method, munge the hash and return the normalized
payload.
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@return {Object}
*/
normalize: function (typeClass, hash) {
return hash;
}
});
var ember$data$lib$system$serializer$$default = ember$data$lib$system$serializer$$Serializer;
var ember$data$lib$serializers$json$serializer$$get = Ember.get;
var ember$data$lib$serializers$json$serializer$$isNone = Ember.isNone;
var ember$data$lib$serializers$json$serializer$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$serializers$json$serializer$$merge = Ember.merge;
var ember$data$lib$serializers$json$serializer$$default = ember$data$lib$system$serializer$$default.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `DS.Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
```
```app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: {key: 'career'}
}
});
```
You can also remove attributes by setting the `serialize` key to
false in your mapping object.
Example
```app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: {serialize: false},
occupation: {key: 'career'}
}
});
```
When serialized:
```javascript
{
"firstName": "Harry",
"lastName": "Houdini",
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
@property attrs
@type {Object}
*/
mergedProperties: ['attrs'],
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {DS.Model} typeClass
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function (typeClass, data) {
typeClass.eachTransformedAttribute(function applyTransform(key, typeClass) {
if (!data.hasOwnProperty(key)) {
return;
}
var transform = this.transformFor(typeClass);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@return {Object}
*/
normalize: function (typeClass, hash) {
if (!hash) {
return hash;
}
this.normalizeId(hash);
this.normalizeAttributes(typeClass, hash);
this.normalizeRelationships(typeClass, hash);
this.normalizeUsingDeclaredMapping(typeClass, hash);
this.applyTransforms(typeClass, hash);
return hash;
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalizePayload: function(payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {Object} payload
@return {Object} the normalized payload
*/
normalizePayload: function (payload) {
return payload;
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function (typeClass, hash) {
var payloadKey;
if (this.keyForAttribute) {
typeClass.eachAttribute(function (key) {
payloadKey = this.keyForAttribute(key, 'deserialize');
if (key === payloadKey) {
return;
}
if (!hash.hasOwnProperty(payloadKey)) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function (typeClass, hash) {
var payloadKey;
if (this.keyForRelationship) {
typeClass.eachRelationship(function (key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize');
if (key === payloadKey) {
return;
}
if (!hash.hasOwnProperty(payloadKey)) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function (typeClass, hash) {
var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs');
var payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = this._getMappedKey(key);
if (!hash.hasOwnProperty(payloadKey)) {
continue;
}
if (payloadKey !== key) {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeId
@private
*/
normalizeId: function (hash) {
var primaryKey = ember$data$lib$serializers$json$serializer$$get(this, 'primaryKey');
if (primaryKey === 'id') {
return;
}
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
@method normalizeErrors
@private
*/
normalizeErrors: function (typeClass, hash) {
this.normalizeId(hash);
this.normalizeAttributes(typeClass, hash);
this.normalizeRelationships(typeClass, hash);
this.normalizeUsingDeclaredMapping(typeClass, hash);
},
/**
Looks up the property key that was set by the custom `attr` mapping
passed to the serializer.
@method _getMappedKey
@private
@param {String} key
@return {String} key
*/
_getMappedKey: function (key) {
var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs');
var mappedKey;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the {title: 'post_title'} and
//{title: {key: 'post_title'}} forms
if (mappedKey.key) {
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string') {
key = mappedKey;
}
}
return key;
},
/**
Check attrs.key.serialize property to inform if the `key`
can be serialized
@method _canSerialize
@private
@param {String} key
@return {boolean} true if the key can be serialized
*/
_canSerialize: function (key) {
var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs');
return !attrs || !attrs[key] || attrs[key].serialize !== false;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
}
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = {};
snapshot.eachAttribute(function(name) {
json[serverAttributeName(name)] = snapshot.attr(name);
})
snapshot.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
}
});
if (options.includeId) {
json.ID_ = snapshot.id;
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function (snapshot, options) {
var json = {};
if (options && options.includeId) {
var id = snapshot.id;
if (id) {
json[ember$data$lib$serializers$json$serializer$$get(this, 'primaryKey')] = id;
}
}
snapshot.eachAttribute(function (key, attribute) {
this.serializeAttribute(snapshot, json, key, attribute);
}, this);
snapshot.eachRelationship(function (key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(snapshot, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(snapshot, json, relationship);
}
}, this);
return json;
},
/**
You can use this method to customize how a serialized record is added to the complete
JSON hash to be sent to the server. By default the JSON Serializer does not namespace
the payload and just sends the raw serialized JSON object.
If your server expects namespaced keys, you should consider using the RESTSerializer.
Otherwise you can override this method to customize how the record is added to the hash.
For example, your server may expect underscored root objects.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, snapshot, options) {
var root = Ember.String.decamelize(type.modelName);
data[root] = this.serialize(snapshot, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function (hash, typeClass, snapshot, options) {
ember$data$lib$serializers$json$serializer$$merge(hash, this.serialize(snapshot, options));
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all your attributes were always
serialized as properties on an `attributes` object you could
write:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializeAttribute: function(snapshot, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(snapshot, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Snapshot} snapshot
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function (snapshot, json, key, attribute) {
var type = attribute.type;
if (this._canSerialize(key)) {
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForAttribute) {
payloadKey = this.keyForAttribute(key, 'serialize');
}
json[payloadKey] = value;
}
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializeBelongsTo: function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function (snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var belongsToId = snapshot.belongsTo(key, { id: true });
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize');
}
//Need to check whether the id is there for new&async records
if (ember$data$lib$serializers$json$serializer$$isNone(belongsToId)) {
json[payloadKey] = null;
} else {
json[payloadKey] = belongsToId;
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(snapshot, json, relationship);
}
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializeHasMany: function(snapshot, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var payloadKey;
// if provided, use the mapping provided by `attrs` in
// the serializer
payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize');
}
var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[payloadKey] = snapshot.hasMany(key, { ids: true });
// TODO support for polymorphic manyToNone and manyToMany relationships
}
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```app/serializers/comment.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializePolymorphicType: function(snapshot, json, relationship) {
var key = relationship.key,
belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key;
if (Ember.isNone(belongsTo)) {
json[key + "_type"] = null;
} else {
json[key + "_type"] = belongsTo.modelName;
}
}
});
```
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
To override this method with a custom one, make sure to call
`return this._super(store, type, payload, id, requestType)` with your
pre-processed data.
Here's an example of using `extract` manually:
```javascript
socket.on('message', function(message) {
var data = message.data;
var typeClass = store.modelFor(message.modelName);
var serializer = store.serializerFor(typeClass.modelName);
var record = serializer.extract(store, typeClass, data, data.id, 'single');
store.push(message.modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function (store, typeClass, payload, id, requestType) {
this.extractMeta(store, typeClass.modelName, payload);
var specificExtract = 'extract' + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, typeClass, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindAll: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindMany: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Model#save` and the record is new. By default
this method is alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractCreateRecord: function (store, typeClass, payload, id, requestType) {
return this.extractSave(store, typeClass, payload, id, requestType);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Model#save` and the record has been updated.
By default this method is alias for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function (store, typeClass, payload, id, requestType) {
return this.extractSave(store, typeClass, payload, id, requestType);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Model#save` and the record has been deleted.
By default this method is alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function (store, typeClass, payload, id, requestType) {
return this.extractSave(store, typeClass, payload, id, requestType);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFind: function (store, typeClass, payload, id, requestType) {
return this.extractSingle(store, typeClass, payload, id, requestType);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function (store, typeClass, payload, id, requestType) {
return this.extractSingle(store, typeClass, payload, id, requestType);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSave: function (store, typeClass, payload, id, requestType) {
return this.extractSingle(store, typeClass, payload, id, requestType);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractSingle: function(store, typeClass, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, typeClass, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSingle: function (store, typeClass, payload, id, requestType) {
var normalizedPayload = this.normalizePayload(payload);
return this.normalize(typeClass, normalizedPayload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractArray: function(store, typeClass, payload) {
return payload.map(function(json) {
return this.extractSingle(store, typeClass, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} arrayPayload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractArray: function (store, typeClass, arrayPayload, id, requestType) {
var normalizedPayload = this.normalizePayload(arrayPayload);
var serializer = this;
return ember$data$lib$serializers$json$serializer$$map.call(normalizedPayload, function (singlePayload) {
return serializer.normalize(typeClass, singlePayload);
});
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractMeta: function(store, typeClass, payload) {
if (payload && payload._pagination) {
store.setMetadataFor(typeClass, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
*/
extractMeta: function (store, typeClass, payload) {
if (payload && payload.meta) {
store.setMetadataFor(typeClass, payload.meta);
delete payload.meta;
}
},
/**
`extractErrors` is used to extract model errors when a call is made
to `DS.Model#save` which fails with an `InvalidError`. By default
Ember Data expects error information to be located on the `errors`
property of the payload object.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractErrors: function(store, typeClass, payload, id) {
if (payload && typeof payload === 'object' && payload._problems) {
payload = payload._problems;
this.normalizeErrors(typeClass, payload);
}
return payload;
}
});
```
@method extractErrors
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@return {Object} json The deserialized errors
*/
extractErrors: function (store, typeClass, payload, id) {
if (payload && typeof payload === 'object' && payload.errors) {
payload = payload.errors;
this.normalizeErrors(typeClass, payload);
}
return payload;
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
keyForAttribute: function(attr, method) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@param {String} method
@return {String} normalized key
*/
keyForAttribute: function (key, method) {
return key;
},
/**
`keyForRelationship` can be used to define a custom key when
serializing and deserializing relationship properties. By default
`JSONSerializer` does not provide an implementation of this method.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship, method) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} typeClass
@param {String} method
@return {String} normalized key
*/
keyForRelationship: function (key, typeClass, method) {
return key;
},
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function (attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
return transform;
}
});
var ember$data$lib$system$normalize$model$name$$default = ember$data$lib$system$normalize$model$name$$normalizeModelName;
/**
All modelNames are dasherized internally. Changing this function may
require changes to other normalization hooks (such as typeForRoot).
@method normalizeModelName
@public
@param {String} modelName
@return {String} if the adapter can generate one, an ID
@for DS
*/
function ember$data$lib$system$normalize$model$name$$normalizeModelName(modelName) {
return Ember.String.dasherize(modelName);
}
var ember$data$lib$system$coerce$id$$default = ember$data$lib$system$coerce$id$$coerceId;
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function ember$data$lib$system$coerce$id$$coerceId(id) {
return id == null ? null : id + '';
}
var ember$data$lib$serializers$rest$serializer$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$serializers$rest$serializer$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$serializers$rest$serializer$$camelize = Ember.String.camelize;
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to define
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
keyForAttribute: function(attr, method) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter, and
the method (`serialize` or `deserialize`) as the third parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
var ember$data$lib$serializers$rest$serializer$$RESTSerializer = ember$data$lib$serializers$json$serializer$$default.extend({
/**
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, given the following json where the the `IDs` under
`"comments"` are provided as `_id` instead of `id`.
```javascript
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"_id": 1,
"body": "FIRST"
}, {
"_id": 2,
"body": "Rails is unagi"
}]
}
```
You use `normalizeHash` to normalize just the comments:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is usually just the original key
that was in the original payload. However, key names will be
impacted by any modifications done in the `normalizePayload`
method. The `DS.RESTSerializer`'s default implementation makes no
changes to the payload keys.
@property normalizeHash
@type {Object}
@default undefined
*/
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@param {String} prop
@return {Object}
*/
normalize: function (typeClass, hash, prop) {
this.normalizeId(hash);
this.normalizeAttributes(typeClass, hash);
this.normalizeRelationships(typeClass, hash);
this.normalizeUsingDeclaredMapping(typeClass, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
this.applyTransforms(typeClass, hash);
return hash;
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, typeClass, payload, id) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, typeClass, payload, id);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {DS.Model} primaryTypeClass
@param {Object} rawPayload
@param {String} recordId
@return {Object} the primary response to the original request
*/
extractSingle: function (store, primaryTypeClass, rawPayload, recordId) {
var payload = this.normalizePayload(rawPayload);
var primaryRecord;
for (var prop in payload) {
var modelName = this.modelNameFromPayloadKey(prop);
if (!store.modelFactoryFor(modelName)) {
continue;
}
var isPrimary = this.isPrimaryType(store, modelName, primaryTypeClass);
var value = payload[prop];
if (value === null) {
continue;
}
// legacy support for singular resources
if (isPrimary && Ember.typeOf(value) !== "array") {
primaryRecord = this.normalize(primaryTypeClass, value, prop);
continue;
}
var normalizedArray = this.normalizeArray(store, modelName, value, prop);
/*jshint loopfunc:true*/
ember$data$lib$serializers$rest$serializer$$forEach.call(normalizedArray, function (hash) {
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord;
var isUpdatedRecord = isPrimary && ember$data$lib$system$coerce$id$$default(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(modelName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi",
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
});
payload = { comments: comments, posts: posts };
return this._super(store, type, payload);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {DS.Model} primaryTypeClass
@param {Object} rawPayload
@return {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function (store, primaryTypeClass, rawPayload) {
var payload = this.normalizePayload(rawPayload);
var primaryArray;
for (var prop in payload) {
var modelName = prop;
var forcedSecondary = false;
if (prop.charAt(0) === "_") {
forcedSecondary = true;
modelName = prop.substr(1);
}
var typeName = this.modelNameFromPayloadKey(modelName);
if (!store.modelFactoryFor(typeName)) {
continue;
}
var normalizedArray = this.normalizeArray(store, typeName, payload[prop], prop);
var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryTypeClass);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
normalizeArray: function (store, typeName, arrayHash, prop) {
var typeClass = store.modelFor(typeName);
var typeSerializer = store.serializerFor(typeName);
/*jshint loopfunc:true*/
return ember$data$lib$serializers$rest$serializer$$map.call(arrayHash, function (hash) {
return typeSerializer.normalize(typeClass, hash, prop);
}, this);
},
isPrimaryType: function (store, typeName, primaryTypeClass) {
var typeClass = store.modelFor(typeName);
return typeClass.modelName === primaryTypeClass.modelName;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} rawPayload
*/
pushPayload: function (store, rawPayload) {
var payload = this.normalizePayload(rawPayload);
for (var prop in payload) {
var modelName = this.modelNameFromPayloadKey(prop);
if (!store.modelFactoryFor(modelName)) {
continue;
}
var typeClass = store.modelFor(modelName);
var typeSerializer = store.serializerFor(modelName);
/*jshint loopfunc:true*/
var normalizedArray = ember$data$lib$serializers$rest$serializer$$map.call(Ember.makeArray(payload[prop]), function (hash) {
return typeSerializer.normalize(typeClass, hash, prop);
}, this);
store.pushMany(modelName, normalizedArray);
}
},
/**
This method is used to convert each JSON root key in the payload
into a modelName that it can use to look up the appropriate model for
that part of the payload.
For example, your server may send a model name that does not correspond with
the name of the model in your app. Let's take a look at an example model,
and an example payload:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
});
```
```javascript
{
"blog/post": {
"id": "1
}
}
```
Ember Data is going to normalize the payload's root key for the modelName. As a result,
it will try to look up the "blog/post" model. Since we don't have a model called "blog/post"
(or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error
because it cannot find the "blog/post" model.
Since we want to remove this namespace, we can define a serializer for the application that will
remove "blog/" from the payload key whenver it's encountered by Ember Data:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
modelNameFromPayloadKey: function(payloadKey) {
if (payloadKey === 'blog/post') {
return this._super(payloadKey.replace('blog/', ''));
} else {
return this._super(payloadKey);
}
}
});
```
After refreshing, Ember Data will appropriately look up the "post" model.
By default the modelName for a model is its
name in dasherized form. This means that a payload key like "blogPost" would be
normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data
can use the correct inflection to do this for you. Most of the time, you won't
need to override `modelNameFromPayloadKey` for this purpose.
@method modelNameFromPayloadKey
@param {String} key
@return {String} the model's modelName
*/
modelNameFromPayloadKey: function (key) {
return ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(key));
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
}
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = {};
snapshot.eachAttribute(function(name) {
json[serverAttributeName(name)] = snapshot.attr(name);
})
snapshot.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
}
});
if (options.includeId) {
json.ID_ = snapshot.id;
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = this._super(snapshot, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function (snapshot, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends the modelName of a model, which is a camelized
version of the name.
For example, your server may expect underscored root objects.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.modelName);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function (hash, typeClass, snapshot, options) {
var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName);
hash[normalizedRootKey] = this.serialize(snapshot, options);
},
/**
You can use `payloadKeyFromModelName` to override the root key for an outgoing
request. By default, the RESTSerializer returns a camelized version of the
model's name.
For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer
will send it to the server with `tacoParty` as the root key in the JSON payload:
```js
{
"tacoParty": {
"id": "1",
"location": "Matthew Beale's House"
}
}
```
For example, your server may expect dasherized root objects:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.dasherize(modelName);
}
});
```
Given a `TacoParty' model, calling `save` on a tacoModel would produce an outgoing
request like:
```js
{
"taco-party": {
"id": "1",
"location": "Matthew Beale's House"
}
}
```
@method payloadKeyFromModelName
@param {String} modelName
@return {String}
*/
payloadKeyFromModelName: function (modelName) {
return ember$data$lib$serializers$rest$serializer$$camelize(modelName);
},
/**
Deprecated. Use modelNameFromPayloadKey instead
@method typeForRoot
@param {String} modelName
@return {String}
@deprecated
*/
typeForRoot: function (modelName) {
return this.modelNameFromPayloadKey(modelName);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function (snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key;
if (Ember.isNone(belongsTo)) {
json[key + "Type"] = null;
} else {
json[key + "Type"] = Ember.String.camelize(belongsTo.modelName);
}
}
});
var ember$data$lib$serializers$rest$serializer$$default = ember$data$lib$serializers$rest$serializer$$RESTSerializer;
/**
@module ember-data
*/
var activemodel$adapter$lib$system$active$model$serializer$$forEach = Ember.EnumerableUtils.forEach;
var activemodel$adapter$lib$system$active$model$serializer$$camelize = Ember.String.camelize;
var activemodel$adapter$lib$system$active$model$serializer$$classify = Ember.String.classify;
var activemodel$adapter$lib$system$active$model$serializer$$decamelize = Ember.String.decamelize;
var activemodel$adapter$lib$system$active$model$serializer$$underscore = Ember.String.underscore;
/**
The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This serializer extends the DS.RESTSerializer by making consistent
use of the camelization, decamelization and pluralization methods to
normalize the serialized JSON into a format that is compatible with
a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelSerializer expects the JSON returned from your server
to follow the REST adapter conventions substituting underscored keys
for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelSerializer
@namespace DS
@extends DS.RESTSerializer
*/
var activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer = ember$data$lib$serializers$rest$serializer$$default.extend({
// SERIALIZE
/**
Converts camelCased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@return String
*/
keyForAttribute: function (attr) {
return activemodel$adapter$lib$system$active$model$serializer$$decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} relationshipModelName
@param {String} kind
@return String
*/
keyForRelationship: function (relationshipModelName, kind) {
var key = activemodel$adapter$lib$system$active$model$serializer$$decamelize(relationshipModelName);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return ember$inflector$lib$lib$system$string$$singularize(key) + "_ids";
} else {
return key;
}
},
/*
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method payloadKeyFromModelName
@param {String} modelName
@return {String}
*/
payloadKeyFromModelName: function (modelName) {
return activemodel$adapter$lib$system$active$model$serializer$$underscore(activemodel$adapter$lib$system$active$model$serializer$$decamelize(modelName));
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function (snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
var jsonKey = activemodel$adapter$lib$system$active$model$serializer$$underscore(key + "_type");
if (Ember.isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = activemodel$adapter$lib$system$active$model$serializer$$classify(belongsTo.modelName).replace(/(\/)([a-z])/g, function (match, separator, chr) {
return match.toUpperCase();
}).replace("/", "::");
}
},
// EXTRACT
/**
Add extra step to `DS.RESTSerializer.normalize` so links are normalized.
If your payload looks like:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} typeClass
@param {Object} hash
@param {String} prop
@return Object
*/
normalize: function (typeClass, hash, prop) {
this.normalizeLinks(hash);
return this._super(typeClass, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} data
*/
normalizeLinks: function (data) {
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = activemodel$adapter$lib$system$active$model$serializer$$camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@param {Subclass of DS.Model} typeClass
@method normalizeRelationships
@private
*/
normalizeRelationships: function (typeClass, hash) {
if (this.keyForRelationship) {
typeClass.eachRelationship(function (key, relationship) {
var payloadKey, payload;
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key, "deserialize");
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.modelNameFromPayloadKey(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
activemodel$adapter$lib$system$active$model$serializer$$forEach(payload, function (single) {
single.type = self.modelNameFromPayloadKey(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind, "deserialize");
if (!hash.hasOwnProperty(payloadKey)) {
return;
}
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
},
modelNameFromPayloadKey: function (key) {
var convertedFromRubyModule = activemodel$adapter$lib$system$active$model$serializer$$camelize(ember$inflector$lib$lib$system$string$$singularize(key)).replace(/(^|\:)([A-Z])/g, function (match, separator, chr) {
return match.toLowerCase();
}).replace("::", "/");
return ember$data$lib$system$normalize$model$name$$default(convertedFromRubyModule);
}
});
var activemodel$adapter$lib$system$active$model$serializer$$default = activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer;
function ember$data$lib$system$container$proxy$$ContainerProxy(container) {
this.container = container;
}
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.aliasedFactory = function (path, preLookup) {
var _this = this;
return {
create: function () {
if (preLookup) {
preLookup();
}
return _this.container.lookup(path);
}
};
};
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerAlias = function (source, dest, preLookup) {
var factory = this.aliasedFactory(dest, preLookup);
return this.container.register(source, factory);
};
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecation = function (deprecated, valid) {
var preLookupCallback = function () {
};
return this.registerAlias(deprecated, valid, preLookupCallback);
};
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecations = function (proxyPairs) {
var i, proxyPair, deprecated, valid;
for (i = proxyPairs.length; i > 0; i--) {
proxyPair = proxyPairs[i - 1];
deprecated = proxyPair["deprecated"];
valid = proxyPair["valid"];
this.registerDeprecation(deprecated, valid);
}
};
var ember$data$lib$system$container$proxy$$default = ember$data$lib$system$container$proxy$$ContainerProxy;
var activemodel$adapter$lib$setup$container$$default = activemodel$adapter$lib$setup$container$$setupActiveModelAdapter;
function activemodel$adapter$lib$setup$container$$setupActiveModelAdapter(registry, application) {
var proxy = new ember$data$lib$system$container$proxy$$default(registry);
proxy.registerDeprecations([{ deprecated: "serializer:_ams", valid: "serializer:-active-model" }, { deprecated: "adapter:_ams", valid: "adapter:-active-model" }]);
registry.register("serializer:-active-model", activemodel$adapter$lib$system$active$model$serializer$$default);
registry.register("adapter:-active-model", activemodel$adapter$lib$system$active$model$adapter$$default);
}
var ember$data$lib$core$$DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.19.2'
});
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', ember$data$lib$core$$DS.VERSION);
}
//jshint ignore: line
var ember$data$lib$core$$EMBER_DATA_FEATURES = {};
Ember.merge(Ember.FEATURES, ember$data$lib$core$$EMBER_DATA_FEATURES);
var ember$data$lib$core$$default = ember$data$lib$core$$DS;
var ember$data$lib$initializers$store$$default = ember$data$lib$initializers$store$$initializeStore;
/**
Configures a registry for use with an Ember-Data
store. Accepts an optional namespace argument.
@method initializeStore
@param {Ember.Registry} registry
@param {Object} [application] an application namespace
*/
function ember$data$lib$initializers$store$$initializeStore(registry, application) {
registry.optionsForType("serializer", { singleton: false });
registry.optionsForType("adapter", { singleton: false });
if (application && application.Store) {
registry.register("store:application", application.Store);
}
// allow older names to be looked up
var proxy = new ember$data$lib$system$container$proxy$$default(registry);
proxy.registerDeprecations([{ deprecated: "serializer:_default", valid: "serializer:-default" }, { deprecated: "serializer:_rest", valid: "serializer:-rest" }, { deprecated: "adapter:_rest", valid: "adapter:-rest" }]);
// new go forward paths
registry.register("serializer:-default", ember$data$lib$serializers$json$serializer$$default);
registry.register("serializer:-rest", ember$data$lib$serializers$rest$serializer$$default);
registry.register("adapter:-rest", ember$data$lib$adapters$rest$adapter$$default);
}
var ember$data$lib$transforms$base$$default = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@return The serialized value
*/
serialize: null,
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
@return The deserialized value
*/
deserialize: null
});
var ember$data$lib$transforms$number$$empty = Ember.isEmpty;
function ember$data$lib$transforms$number$$isNumber(value) {
return value === value && value !== Infinity && value !== -Infinity;
}
var ember$data$lib$transforms$number$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
var transformed;
if (ember$data$lib$transforms$number$$empty(serialized)) {
return null;
} else {
transformed = Number(serialized);
return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null;
}
},
serialize: function (deserialized) {
var transformed;
if (ember$data$lib$transforms$number$$empty(deserialized)) {
return null;
} else {
transformed = Number(deserialized);
return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null;
}
}
});
// Date.prototype.toISOString shim
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
var ember$data$lib$transforms$date$$toISOString = Date.prototype.toISOString || function () {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';
};
if (Ember.SHIM_ES5) {
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = ember$data$lib$transforms$date$$toISOString;
}
}
var ember$data$lib$transforms$date$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
var type = typeof serialized;
if (type === 'string') {
return new Date(Ember.Date.parse(serialized));
} else if (type === 'number') {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is null return null
// if the value is not present in the data return undefined
return serialized;
} else {
return null;
}
},
serialize: function (date) {
if (date instanceof Date) {
return ember$data$lib$transforms$date$$toISOString.call(date);
} else {
return null;
}
}
});
var ember$data$lib$transforms$string$$none = Ember.isNone;
var ember$data$lib$transforms$string$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
return ember$data$lib$transforms$string$$none(serialized) ? null : String(serialized);
},
serialize: function (deserialized) {
return ember$data$lib$transforms$string$$none(deserialized) ? null : String(deserialized);
}
});
var ember$data$lib$transforms$boolean$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function (deserialized) {
return Boolean(deserialized);
}
});
var ember$data$lib$initializers$transforms$$default = ember$data$lib$initializers$transforms$$initializeTransforms;
/**
Configures a registry for use with Ember-Data
transforms.
@method initializeTransforms
@param {Ember.Registry} registry
*/
function ember$data$lib$initializers$transforms$$initializeTransforms(registry) {
registry.register('transform:boolean', ember$data$lib$transforms$boolean$$default);
registry.register('transform:date', ember$data$lib$transforms$date$$default);
registry.register('transform:number', ember$data$lib$transforms$number$$default);
registry.register('transform:string', ember$data$lib$transforms$string$$default);
}
var ember$data$lib$initializers$store$injections$$default = ember$data$lib$initializers$store$injections$$initializeStoreInjections;
/**
Configures a registry with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Registry} registry
*/
function ember$data$lib$initializers$store$injections$$initializeStoreInjections(registry) {
registry.injection('controller', 'store', 'store:main');
registry.injection('route', 'store', 'store:main');
registry.injection('data-adapter', 'store', 'store:main');
}var ember$data$lib$system$promise$proxies$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$promise$proxies$$get = Ember.get;
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
var ember$data$lib$system$promise$proxies$$PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved, then the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
var ember$data$lib$system$promise$proxies$$PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
var ember$data$lib$system$promise$proxies$$promiseObject = function (promise, label) {
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label)
});
};
var ember$data$lib$system$promise$proxies$$promiseArray = function (promise, label) {
return ember$data$lib$system$promise$proxies$$PromiseArray.create({
promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label)
});
};
/**
A PromiseManyArray is a PromiseArray that also proxies certain method calls
to the underlying manyArray.
Right now we proxy:
* `reload()`
* `createRecord()`
* `on()`
* `one()`
* `trigger()`
* `off()`
* `has()`
@class PromiseManyArray
@namespace DS
@extends Ember.ArrayProxy
*/
function ember$data$lib$system$promise$proxies$$proxyToContent(method) {
return function () {
var content = ember$data$lib$system$promise$proxies$$get(this, 'content');
return content[method].apply(content, arguments);
};
}
var ember$data$lib$system$promise$proxies$$PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseArray.extend({
reload: function () {
//I don't think this should ever happen right now, but worth guarding if we refactor the async relationships
return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({
promise: ember$data$lib$system$promise$proxies$$get(this, 'content').reload()
});
},
createRecord: ember$data$lib$system$promise$proxies$$proxyToContent('createRecord'),
on: ember$data$lib$system$promise$proxies$$proxyToContent('on'),
one: ember$data$lib$system$promise$proxies$$proxyToContent('one'),
trigger: ember$data$lib$system$promise$proxies$$proxyToContent('trigger'),
off: ember$data$lib$system$promise$proxies$$proxyToContent('off'),
has: ember$data$lib$system$promise$proxies$$proxyToContent('has')
});
var ember$data$lib$system$promise$proxies$$promiseManyArray = function (promise, label) {
return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({
promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label)
});
};
/**
@module ember-data
*/
var ember$data$lib$system$model$model$$get = Ember.get;
var ember$data$lib$system$model$model$$intersection = Ember.EnumerableUtils.intersection;
var ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS = ['currentState', 'data', 'store'];
var ember$data$lib$system$model$model$$retrieveFromCurrentState = Ember.computed('currentState', function (key) {
return ember$data$lib$system$model$model$$get(this._internalModel.currentState, key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
This is the public API of Ember Data models. If you are using Ember Data
in your application, this is the class you should use.
If you are working on Ember Data internals, you most likely want to be dealing
with `InternalModel`
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var ember$data$lib$system$model$model$$Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
_internalModel: null,
store: null,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord('model');
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.get('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('isDirty'); // true
record.get('isSaving'); // false
// Persisting the deletion
var promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('isDirty'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord('model');
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
contains keys corresponding to the invalid property names
and values which are arrays of Javascript objects with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
record.get('errors').get('foo');
// [{message: 'foo should be a number.', attribute: 'foo'}]
});
```
The `errors` property us useful for displaying error messages to
the user.
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property errors
@type {DS.Errors}
*/
errors: Ember.computed(function () {
return this._internalModel.getErrors();
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function (options) {
return this.store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON: function (options) {
// container is for lazy transform lookups
var serializer = this.store.serializerFor('-default');
var snapshot = this._internalModel.createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: Ember.K,
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when a new record is commited to the server.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
Fired when the record is rolled back.
@event rolledBack
*/
rolledBack: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed.readOnly('_internalModel._data'),
//TODO Do we want to deprecate these?
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function (name, context) {
return this._internalModel.send(name, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function (name) {
return this._internalModel.transitionTo(name);
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function () {
this._internalModel.deleteRecord();
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function () {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function () {
if (this.isDestroyed) {
return;
}
this._internalModel.unloadRecord();
},
/**
@method _notifyProperties
@private
*/
_notifyProperties: function (keys) {
Ember.beginPropertyChanges();
var key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
Ember.endPropertyChanges();
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```app/models/mascot.js
import DS from 'ember-data';
export default DS.Model.extend({
name: attr('string')
});
```
```javascript
var mascot = store.createRecord('mascot');
mascot.changedAttributes(); // {}
mascot.set('name', 'Tomster');
mascot.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function () {
var oldData = ember$data$lib$system$model$model$$get(this._internalModel, '_data');
var newData = ember$data$lib$system$model$model$$get(this._internalModel, '_attributes');
var diffData = Ember.create(null);
var prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
//TODO discuss with tomhuda about events/hooks
//Bring back as hooks?
/**
@method adapterWillCommit
@private
adapterWillCommit: function() {
this.send('willCommit');
},
/**
@method adapterDidDirty
@private
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
*/
/**
If the model `isDirty` this function will discard any unsaved
changes. If the model `isNew` it will be removed from the store.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function () {
this._internalModel.rollback();
},
/*
@method _createSnapshot
@private
*/
_createSnapshot: function () {
return this._internalModel.createSnapshot();
},
toStringExtension: function () {
return ember$data$lib$system$model$model$$get(this, 'id');
},
/**
Save the record and persist any changes to the record to an
external source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function () {
var model = this;
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: this._internalModel.save().then(function () {
return model;
})
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```app/routes/model/view.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function () {
var model = this;
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: this._internalModel.reload().then(function () {
return model;
})
});
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param {String} name
*/
trigger: function (name) {
var length = arguments.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
Ember.tryInvoke(this, name, args);
this._super.apply(this, arguments);
},
willDestroy: function () {
//TODO Move!
this._internalModel.clearRelationships();
this._internalModel.recordObjectWillDestroy();
this._super.apply(this, arguments);
//TODO should we set internalModel to null here?
},
// This is a temporary solution until we refactor DS.Model to not
// rely on the data property.
willMergeMixin: function (props) {
var constructor = this.constructor;
},
attr: function () {
},
belongsTo: function () {
},
hasMany: function () {
}
});
ember$data$lib$system$model$model$$Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: ember$data$lib$system$model$model$$Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function () {
throw new Ember.Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
},
/**
Represents the model's class name as a string. This can be used to look up the model through
DS.Store's modelFor method.
`modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
```javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'
```
The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
keys to underscore (instead of dasherized), you might use the following code:
```javascript
export default var PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
```
@property
@type String
@readonly
*/
modelName: null
});
var ember$data$lib$system$model$model$$default = ember$data$lib$system$model$model$$Model;
var ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter;
try {
Ember.computed({
get: function () {},
set: function () {}
});
ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter = true;
} catch (e) {
ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter = false;
}
var ember$data$lib$utils$supports$computed$getter$setter$$default = ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter;
var ember$data$lib$utils$computed$polyfill$$computed = Ember.computed;
var ember$data$lib$utils$computed$polyfill$$default = function () {
var polyfillArguments = [];
var config = arguments[arguments.length - 1];
if (typeof config === 'function' || ember$data$lib$utils$supports$computed$getter$setter$$default) {
return ember$data$lib$utils$computed$polyfill$$computed.apply(null, arguments);
}
for (var i = 0, l = arguments.length - 1; i < l; i++) {
polyfillArguments.push(arguments[i]);
}
var func;
if (config.set) {
func = function (key, value) {
if (arguments.length > 1) {
return config.set.call(this, key, value);
} else {
return config.get.call(this, key);
}
};
} else {
func = function (key) {
return config.get.call(this, key);
};
}
polyfillArguments.push(func);
return ember$data$lib$utils$computed$polyfill$$computed.apply(null, polyfillArguments);
};
var ember$data$lib$system$model$attributes$$default = ember$data$lib$system$model$attributes$$attr;
/**
@module ember-data
*/
var ember$data$lib$system$model$attributes$$get = Ember.get;
/**
@class Model
@namespace DS
*/
ember$data$lib$system$model$model$$default.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
var attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function () {
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isAttribute) {
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
var transformedAttributes = Ember.get(Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function () {
var map = ember$data$lib$system$map$$Map.create();
this.eachAttribute(function (key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
var Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachAttribute: function (callback, binding) {
ember$data$lib$system$model$attributes$$get(this, "attributes").forEach(function (meta, name) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
var Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachTransformedAttribute: function (callback, binding) {
ember$data$lib$system$model$attributes$$get(this, "transformedAttributes").forEach(function (type, name) {
callback.call(binding, name, type);
});
}
});
ember$data$lib$system$model$model$$default.reopen({
eachAttribute: function (callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function ember$data$lib$system$model$attributes$$getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
return options.defaultValue;
}
}
function ember$data$lib$system$model$attributes$$hasValue(record, key) {
return key in record._attributes || key in record._inFlightAttributes || key in record._data;
}
function ember$data$lib$system$model$attributes$$getValue(record, key) {
if (key in record._attributes) {
return record._attributes[key];
} else if (key in record._inFlightAttributes) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
Note that you cannot use `attr` to define an attribute of `id`.
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
verified: DS.attr('boolean', {defaultValue: false})
});
```
Default value can also be a function. This is useful it you want to return
a new object for each attribute.
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: attr('string'),
email: attr('string'),
settings: attr({defaultValue: function() {
return {};
}})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
function ember$data$lib$system$model$attributes$$attr(type, options) {
if (typeof type === "object") {
options = type;
type = undefined;
} else {
options = options || {};
}
var meta = {
type: type,
isAttribute: true,
options: options
};
return ember$data$lib$utils$computed$polyfill$$default({
get: function (key) {
var internalModel = this._internalModel;
if (ember$data$lib$system$model$attributes$$hasValue(internalModel, key)) {
return ember$data$lib$system$model$attributes$$getValue(internalModel, key);
} else {
return ember$data$lib$system$model$attributes$$getDefaultValue(this, options, key);
}
},
set: function (key, value) {
var internalModel = this._internalModel;
var oldValue = ember$data$lib$system$model$attributes$$getValue(internalModel, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
internalModel._attributes[key] = value;
this._internalModel.send("didSetProperty", {
name: key,
oldValue: oldValue,
originalValue: internalModel._data[key],
value: value
});
}
return value;
}
}).meta(meta);
}
var ember$data$lib$system$model$states$$get = Ember.get;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (This state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What that means is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function ember$data$lib$system$model$states$$didSetProperty(internalModel, context) {
if (context.value === context.originalValue) {
delete internalModel._attributes[context.name];
internalModel.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
internalModel.send('becomeDirty');
}
internalModel.updateRecordArraysLater();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: The adapter did not report any server-side validation
// failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var ember$data$lib$system$model$states$$DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
//TODO(Igor) reloading now triggers a
//loadingData event, though it seems fine?
loadingData: Ember.K,
propertyWasReset: function (internalModel, name) {
var length = Ember.keys(internalModel._attributes).length;
var stillDirty = length > 0;
if (!stillDirty) {
internalModel.send('rolledBack');
}
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function (internalModel) {
internalModel.transitionTo('inFlight');
},
reloadRecord: function (internalModel, resolve) {
resolve(internalModel.store.reloadRecord(internalModel));
},
rolledBack: function (internalModel) {
internalModel.transitionTo('loaded.saved');
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
},
rollback: function (internalModel) {
internalModel.rollback();
internalModel.triggerLater('ready');
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function (internalModel) {
var dirtyType = ember$data$lib$system$model$states$$get(this, 'dirtyType');
internalModel.transitionTo('saved');
internalModel.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
internalModel.send('invokeLifecycleCallbacks');
},
becameError: function (internalModel) {
internalModel.transitionTo('uncommitted');
internalModel.triggerLater('becameError', internalModel);
}
},
// A record is in the `invalid` if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
internalModel.disconnectRelationships();
},
didSetProperty: function (internalModel, context) {
internalModel.getErrors().remove(context.name);
ember$data$lib$system$model$states$$didSetProperty(internalModel, context);
},
becomeDirty: Ember.K,
pushedData: Ember.K,
willCommit: function (internalModel) {
internalModel.getErrors().clear();
internalModel.transitionTo('inFlight');
},
rolledBack: function (internalModel) {
internalModel.getErrors().clear();
internalModel.triggerLater('ready');
},
becameValid: function (internalModel) {
internalModel.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function (internalModel) {
internalModel.triggerLater('becameInvalid', internalModel);
},
exit: function (internalModel) {
internalModel._inFlightAttributes = Ember.create(null);
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function ember$data$lib$system$model$states$$deepClone(object) {
var clone = {};
var value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = ember$data$lib$system$model$states$$deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function ember$data$lib$system$model$states$$mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function ember$data$lib$system$model$states$$dirtyState(options) {
var newState = ember$data$lib$system$model$states$$deepClone(ember$data$lib$system$model$states$$DirtyState);
return ember$data$lib$system$model$states$$mixin(newState, options);
}
var ember$data$lib$system$model$states$$createdState = ember$data$lib$system$model$states$$dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
ember$data$lib$system$model$states$$createdState.invalid.rolledBack = function (internalModel) {
internalModel.transitionTo('deleted.saved');
};
ember$data$lib$system$model$states$$createdState.uncommitted.rolledBack = function (internalModel) {
internalModel.transitionTo('deleted.saved');
};
var ember$data$lib$system$model$states$$updatedState = ember$data$lib$system$model$states$$dirtyState({
dirtyType: 'updated'
});
ember$data$lib$system$model$states$$createdState.uncommitted.deleteRecord = function (internalModel) {
internalModel.disconnectRelationships();
internalModel.transitionTo('deleted.saved');
internalModel.send('invokeLifecycleCallbacks');
};
ember$data$lib$system$model$states$$createdState.uncommitted.rollback = function (internalModel) {
ember$data$lib$system$model$states$$DirtyState.uncommitted.rollback.apply(this, arguments);
internalModel.transitionTo('deleted.saved');
};
ember$data$lib$system$model$states$$createdState.uncommitted.pushedData = function (internalModel) {
internalModel.transitionTo('loaded.updated.uncommitted');
internalModel.triggerLater('didLoad');
};
ember$data$lib$system$model$states$$createdState.uncommitted.propertyWasReset = Ember.K;
function ember$data$lib$system$model$states$$assertAgainstUnloadRecord(internalModel) {
}
ember$data$lib$system$model$states$$updatedState.inFlight.unloadRecord = ember$data$lib$system$model$states$$assertAgainstUnloadRecord;
ember$data$lib$system$model$states$$updatedState.uncommitted.deleteRecord = function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
internalModel.disconnectRelationships();
};
var ember$data$lib$system$model$states$$RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
unloadRecord: function (internalModel) {
// clear relationships before moving to deleted state
// otherwise it fails
internalModel.clearRelationships();
internalModel.transitionTo('deleted.saved');
},
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function (internalModel, promise) {
internalModel._loadingPromise = promise;
internalModel.transitionTo('loading');
},
loadedData: function (internalModel) {
internalModel.transitionTo('loaded.created.uncommitted');
internalModel.triggerLater('ready');
},
pushedData: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('didLoad');
internalModel.triggerLater('ready');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function (internalModel) {
internalModel._loadingPromise = null;
},
// EVENTS
pushedData: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('didLoad');
internalModel.triggerLater('ready');
//TODO this seems out of place here
internalModel.didCleanError();
},
becameError: function (internalModel) {
internalModel.triggerLater('becameError', internalModel);
},
notFound: function (internalModel) {
internalModel.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
//TODO(Igor) Reloading now triggers a loadingData event,
//but it should be ok?
loadingData: Ember.K,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function (internalModel) {
var attrs = internalModel._attributes;
var isDirty = Ember.keys(attrs).length > 0;
if (isDirty) {
internalModel.adapterDidDirty();
}
},
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
pushedData: Ember.K,
becomeDirty: function (internalModel) {
internalModel.transitionTo('updated.uncommitted');
},
willCommit: function (internalModel) {
internalModel.transitionTo('updated.inFlight');
},
reloadRecord: function (internalModel, resolve) {
resolve(internalModel.store.reloadRecord(internalModel));
},
deleteRecord: function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
internalModel.disconnectRelationships();
},
unloadRecord: function (internalModel) {
// clear relationships before moving to deleted state
// otherwise it fails
internalModel.clearRelationships();
internalModel.transitionTo('deleted.saved');
},
didCommit: function (internalModel) {
internalModel.send('invokeLifecycleCallbacks', ember$data$lib$system$model$states$$get(internalModel, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: ember$data$lib$system$model$states$$createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: ember$data$lib$system$model$states$$updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function (internalModel) {
internalModel.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function (internalModel) {
internalModel.transitionTo('inFlight');
},
rollback: function (internalModel) {
internalModel.rollback();
internalModel.triggerLater('ready');
},
pushedData: Ember.K,
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function (internalModel) {
internalModel.transitionTo('saved');
internalModel.send('invokeLifecycleCallbacks');
},
becameError: function (internalModel) {
internalModel.transitionTo('uncommitted');
internalModel.triggerLater('becameError', internalModel);
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
internalModel.triggerLater('becameInvalid', internalModel);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function (internalModel) {
var store = internalModel.store;
store._dematerializeRecord(internalModel);
},
invokeLifecycleCallbacks: function (internalModel) {
internalModel.triggerLater('didDelete', internalModel);
internalModel.triggerLater('didCommit', internalModel);
},
willCommit: Ember.K,
didCommit: Ember.K
},
invalid: {
isValid: false,
didSetProperty: function (internalModel, context) {
internalModel.getErrors().remove(context.name);
ember$data$lib$system$model$states$$didSetProperty(internalModel, context);
},
deleteRecord: Ember.K,
becomeDirty: Ember.K,
willCommit: Ember.K,
rolledBack: function (internalModel) {
internalModel.getErrors().clear();
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
},
becameValid: function (internalModel) {
internalModel.transitionTo('uncommitted');
}
}
},
invokeLifecycleCallbacks: function (internalModel, dirtyType) {
if (dirtyType === 'created') {
internalModel.triggerLater('didCreate', internalModel);
} else {
internalModel.triggerLater('didUpdate', internalModel);
}
internalModel.triggerLater('didCommit', internalModel);
}
};
function ember$data$lib$system$model$states$$wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = ember$data$lib$system$model$states$$mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') {
continue;
}
if (typeof object[prop] === 'object') {
object[prop] = ember$data$lib$system$model$states$$wireState(object[prop], object, name + '.' + prop);
}
}
return object;
}
ember$data$lib$system$model$states$$RootState = ember$data$lib$system$model$states$$wireState(ember$data$lib$system$model$states$$RootState, null, 'root');
var ember$data$lib$system$model$states$$default = ember$data$lib$system$model$states$$RootState;
var ember$data$lib$system$model$errors$$get = Ember.get;
var ember$data$lib$system$model$errors$$isEmpty = Ember.isEmpty;
var ember$data$lib$system$model$errors$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$model$errors$$default = Ember.Object.extend(Ember.Enumerable, Ember.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
*/
registerHandlers: function (target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: Ember.reduceComputed('content', {
initialValue: function () {
return ember$data$lib$system$map$$MapWithDefault.create({
defaultValue: function () {
return Ember.A();
}
});
},
addedItem: function (errors, error) {
errors.get(error.attribute).pushObject(error);
return errors;
},
removedItem: function (errors, error) {
errors.get(error.attribute).removeObject(error);
return errors;
}
}),
/**
Returns errors for a given attribute
```javascript
var user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save().catch(function(){
user.get('errors').errorsFor('email'); // returns:
// [{attribute: "email", message: "Doesn't look like a valid email."}]
});
```
@method errorsFor
@param {String} attribute
@return {Array}
*/
errorsFor: function (attribute) {
return ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName').get(attribute);
},
/**
An array containing all of the error messages for this
record. This is useful for displaying all errors to the user.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property messages
@type {Array}
*/
messages: Ember.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: Ember.computed(function () {
return Ember.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function (attribute) {
var errors = this.errorsFor(attribute);
if (ember$data$lib$system$model$errors$$isEmpty(errors)) {
return null;
}
return errors;
},
/**
@method nextObject
@private
*/
nextObject: function (index, previousObject, context) {
return ember$data$lib$system$model$errors$$get(this, 'content').objectAt(index);
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
length: Ember.computed.oneWay('content.length').readOnly(),
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: Ember.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
Example:
```javascript
if (!user.get('username') {
user.get('errors').add('username', 'This field is required');
}
```
@method add
@param {String} attribute
@param {(Array|String)} messages
*/
add: function (attribute, messages) {
var wasEmpty = ember$data$lib$system$model$errors$$get(this, 'isEmpty');
messages = this._findOrCreateMessages(attribute, messages);
ember$data$lib$system$model$errors$$get(this, 'content').addObjects(messages);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (wasEmpty && !ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function (attribute, messages) {
var errors = this.errorsFor(attribute);
return ember$data$lib$system$model$errors$$map(Ember.makeArray(messages), function (message) {
return errors.findBy('message', message) || {
attribute: attribute,
message: message
};
});
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
Example:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
email: DS.attr('string'),
twoFactorAuth: DS.attr('boolean'),
phone: DS.attr('string')
});
```
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
save: function(user) {
if (!user.get('twoFactorAuth')) {
user.get('errors').remove('phone');
}
user.save();
}
}
});
```
@method remove
@param {String} attribute
*/
remove: function (attribute) {
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
return;
}
var content = ember$data$lib$system$model$errors$$get(this, 'content').rejectBy('attribute', attribute);
ember$data$lib$system$model$errors$$get(this, 'content').setObjects(content);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages and sends `becameValid` event
to the record.
Example:
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
retrySave: function(user) {
user.get('errors').clear();
user.save();
}
}
});
```
@method clear
*/
clear: function () {
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
return;
}
ember$data$lib$system$model$errors$$get(this, 'content').clear();
this.enumerableContentDidChange();
this.trigger('becameValid');
},
/**
Checks if there is error messages for the given attribute.
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
save: function(user) {
if (user.get('errors').has('email')) {
return alert('Please update your email before attempting to save.');
}
user.save();
}
}
});
```
@method has
@param {String} attribute
@return {Boolean} true if there some errors on given attribute
*/
has: function (attribute) {
return !ember$data$lib$system$model$errors$$isEmpty(this.errorsFor(attribute));
}
});
var ember$data$lib$system$model$$default = ember$data$lib$system$model$model$$default;
var ember$data$lib$system$debug$debug$adapter$$get = Ember.get;
var ember$data$lib$system$debug$debug$adapter$$capitalize = Ember.String.capitalize;
var ember$data$lib$system$debug$debug$adapter$$underscore = Ember.String.underscore;
var ember$data$lib$system$debug$debug$adapter$$_Ember = Ember;
var ember$data$lib$system$debug$debug$adapter$$assert = ember$data$lib$system$debug$debug$adapter$$_Ember.assert;
var ember$data$lib$system$debug$debug$adapter$$default = Ember.DataAdapter.extend({
getFilters: function () {
return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }];
},
detect: function (typeClass) {
return typeClass !== ember$data$lib$system$model$$default && ember$data$lib$system$model$$default.detect(typeClass);
},
columnsForType: function (typeClass) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
ember$data$lib$system$debug$debug$adapter$$get(typeClass, 'attributes').forEach(function (meta, name) {
if (count++ > self.attributeLimit) {
return false;
}
var desc = ember$data$lib$system$debug$debug$adapter$$capitalize(ember$data$lib$system$debug$debug$adapter$$underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function (modelClass, modelName) {
if (arguments.length < 2) {
// Legacy Ember.js < 1.13 support
var containerKey = modelClass._debugContainerKey;
if (containerKey) {
var match = containerKey.match(/model:(.*)/);
if (match) {
modelName = match[1];
}
}
}
ember$data$lib$system$debug$debug$adapter$$assert('Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support', !!modelName);
return this.get('store').all(modelName);
},
getRecordColumnValues: function (record) {
var self = this;
var count = 0;
var columnValues = { id: ember$data$lib$system$debug$debug$adapter$$get(record, 'id') };
record.eachAttribute(function (key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = ember$data$lib$system$debug$debug$adapter$$get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function (record) {
var keywords = [];
var keys = Ember.A(['id']);
record.eachAttribute(function (key) {
keys.push(key);
});
keys.forEach(function (key) {
keywords.push(ember$data$lib$system$debug$debug$adapter$$get(record, key));
});
return keywords;
},
getRecordFilterValues: function (record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function (record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function (record, recordUpdated) {
var releaseMethods = Ember.A();
var self = this;
var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function (key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function (key) {
var handler = function () {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function () {
Ember.removeObserver(record, key, handler);
});
});
var release = function () {
releaseMethods.forEach(function (fn) {
fn();
});
};
return release;
}
});
var ember$data$lib$initializers$data$adapter$$default = ember$data$lib$initializers$data$adapter$$initializeDebugAdapter;
/**
Configures a registry with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Registry} registry
*/
function ember$data$lib$initializers$data$adapter$$initializeDebugAdapter(registry) {
registry.register("data-adapter:main", ember$data$lib$system$debug$debug$adapter$$default);
}
var ember$data$lib$system$store$common$$get = Ember.get;
function ember$data$lib$system$store$common$$_bind(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return fn.apply(undefined, args);
};
}
function ember$data$lib$system$store$common$$_guard(promise, test) {
var guarded = promise["finally"](function () {
if (!test()) {
guarded._subscribers.length = 0;
}
});
return guarded;
}
function ember$data$lib$system$store$common$$_objectIsAlive(object) {
return !(ember$data$lib$system$store$common$$get(object, "isDestroyed") || ember$data$lib$system$store$common$$get(object, "isDestroying"));
}
function ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type) {
var serializer = adapter.serializer;
if (serializer === undefined) {
serializer = store.serializerFor(type);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function (store, type, payload) {
return payload;
}
};
}
return serializer;
}
var ember$data$lib$system$store$finders$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$store$finders$$map = Ember.EnumerableUtils.map;
function ember$data$lib$system$store$finders$$_find(adapter, store, typeClass, id, internalModel) {
var snapshot = internalModel.createSnapshot();
var promise = adapter.find(store, typeClass, id, snapshot);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, internalModel.type.modelName);
var label = "DS: Handle Adapter#find of " + typeClass + " with id: " + id;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, id, "find");
//TODO Optimize
var record = store.push(typeClass.modelName, payload);
return record._internalModel;
});
}, function (error) {
internalModel.notFound();
if (internalModel.isEmpty()) {
internalModel.unloadRecord();
}
throw error;
}, "DS: Extract payload of '" + typeClass + "'");
}
function ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, internalModels) {
var snapshots = Ember.A(internalModels).invoke("createSnapshot");
var promise = adapter.findMany(store, typeClass, ids, snapshots);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass.modelName);
var label = "DS: Handle Adapter#findMany of " + typeClass;
if (promise === undefined) {
throw new Error("adapter.findMany returned undefined, this was very likely a mistake");
}
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findMany");
//TODO Optimize, no need to materialize here
var records = store.pushMany(typeClass.modelName, payload);
return ember$data$lib$system$store$finders$$map(records, function (record) {
return record._internalModel;
});
});
}, null, "DS: Extract payload of " + typeClass);
}
function ember$data$lib$system$store$finders$$_findHasMany(adapter, store, internalModel, link, relationship) {
var snapshot = internalModel.createSnapshot();
var typeClass = store.modelFor(relationship.type);
var promise = adapter.findHasMany(store, snapshot, link, relationship);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type);
var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findHasMany");
//TODO Use a non record creating push
var records = store.pushMany(relationship.type, payload);
return ember$data$lib$system$store$finders$$map(records, function (record) {
return record._internalModel;
});
});
}, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type);
}
function ember$data$lib$system$store$finders$$_findBelongsTo(adapter, store, internalModel, link, relationship) {
var snapshot = internalModel.createSnapshot();
var typeClass = store.modelFor(relationship.type);
var promise = adapter.findBelongsTo(store, snapshot, link, relationship);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type);
var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findBelongsTo");
if (!payload) {
return null;
}
var record = store.push(relationship.type, payload);
//TODO Optimize
return record._internalModel;
});
}, null, "DS: Extract payload of " + internalModel + " : " + relationship.type);
}
function ember$data$lib$system$store$finders$$_findAll(adapter, store, typeClass, sinceToken) {
var promise = adapter.findAll(store, typeClass, sinceToken);
var modelName = typeClass.modelName;
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName);
var label = "DS: Handle Adapter#findAll of " + typeClass;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findAll");
store.pushMany(modelName, payload);
});
store.didUpdateAll(typeClass);
return store.all(modelName);
}, null, "DS: Extract payload of findAll " + typeClass);
}
function ember$data$lib$system$store$finders$$_findQuery(adapter, store, typeClass, query, recordArray) {
var modelName = typeClass.modelName;
var promise = adapter.findQuery(store, typeClass, query, recordArray);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName);
var label = "DS: Handle Adapter#findQuery of " + typeClass;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
var payload;
store._adapterRun(function () {
payload = serializer.extract(store, typeClass, adapterPayload, null, "findQuery");
});
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + typeClass);
}
var ember$data$lib$system$record$arrays$record$array$$get = Ember.get;
var ember$data$lib$system$record$arrays$record$array$$set = Ember.set;
var ember$data$lib$system$record$arrays$record$array$$default = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
content: null,
/**
The flag to signal a `RecordArray` is finished loading data.
Example
```javascript
var people = store.all('person');
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
isLoaded: false,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
isUpdating: false,
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
store: null,
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function (index) {
var content = ember$data$lib$system$record$arrays$record$array$$get(this, 'content');
var internalModel = content.objectAt(index);
return internalModel && internalModel.getRecord();
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@method update
*/
update: function () {
if (ember$data$lib$system$record$arrays$record$array$$get(this, 'isUpdating')) {
return;
}
var store = ember$data$lib$system$record$arrays$record$array$$get(this, 'store');
var modelName = ember$data$lib$system$record$arrays$record$array$$get(this, 'type.modelName');
return store.fetchAll(modelName, this);
},
/**
Adds an internal model to the `RecordArray` without duplicates
@method addInternalModel
@private
@param {InternalModel} internalModel
@param {number} an optional index to insert at
*/
addInternalModel: function (internalModel, idx) {
var content = ember$data$lib$system$record$arrays$record$array$$get(this, 'content');
if (idx === undefined) {
content.addObject(internalModel);
} else if (!content.contains(internalModel)) {
content.insertAt(idx, internalModel);
}
},
/**
Removes an internalModel to the `RecordArray`.
@method removeInternalModel
@private
@param {InternalModel} internalModel
*/
removeInternalModel: function (internalModel) {
ember$data$lib$system$record$arrays$record$array$$get(this, 'content').removeObject(internalModel);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.all('message');
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function () {
var recordArray = this;
var promiseLabel = 'DS: RecordArray#save ' + ember$data$lib$system$record$arrays$record$array$$get(this, 'type');
var promise = Ember.RSVP.all(this.invoke('save'), promiseLabel).then(function (array) {
return recordArray;
}, null, 'DS: RecordArray#save return RecordArray');
return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function () {
var array = this;
this.get('content').forEach(function (record) {
var recordArrays = record._recordArrays;
if (recordArrays) {
recordArrays["delete"](array);
}
});
},
/**
@method _unregisterFromManager
@private
*/
_unregisterFromManager: function () {
var manager = ember$data$lib$system$record$arrays$record$array$$get(this, 'manager');
manager.unregisterFilteredRecordArray(this);
},
willDestroy: function () {
this._unregisterFromManager();
this._dissociateFromOwnRecords();
ember$data$lib$system$record$arrays$record$array$$set(this, 'content', undefined);
this._super.apply(this, arguments);
}
});
/**
@module ember-data
*/
var ember$data$lib$system$record$arrays$filtered$record$array$$get = Ember.get;
var ember$data$lib$system$record$arrays$filtered$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.all('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
isLoaded: true,
replace: function () {
var type = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "type").toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
_updateFilter: function () {
var manager = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "manager");
manager.updateFilter(this, ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "type"), ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "filterFunction"));
},
updateFilter: Ember.observer(function () {
Ember.run.once(this, this._updateFilter);
}, "filterFunction")
});
/**
@module ember-data
*/
var ember$data$lib$system$record$arrays$adapter$populated$record$array$$get = Ember.get;
function ember$data$lib$system$record$arrays$adapter$populated$record$array$$cloneNull(source) {
var clone = Ember.create(null);
for (var key in source) {
clone[key] = source[key];
}
return clone;
}
var ember$data$lib$system$record$arrays$adapter$populated$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({
query: null,
replace: function () {
var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type").toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
/**
@method load
@private
@param {Array} data
*/
load: function (data) {
var store = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "store");
var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type");
var modelName = type.modelName;
var records = store.pushMany(modelName, data);
var meta = store.metadataFor(modelName);
//TODO Optimize
var internalModels = Ember.A(records).mapBy("_internalModel");
this.setProperties({
content: Ember.A(internalModels),
isLoaded: true,
meta: ember$data$lib$system$record$arrays$adapter$populated$record$array$$cloneNull(meta)
});
internalModels.forEach(function (record) {
this.manager.recordArraysForRecord(record).add(this);
}, this);
// TODO: should triggering didLoad event be the last action of the runLoop?
Ember.run.once(this, "trigger", "didLoad");
}
});
var ember$data$lib$system$ordered$set$$EmberOrderedSet = Ember.OrderedSet;
var ember$data$lib$system$ordered$set$$guidFor = Ember.guidFor;
var ember$data$lib$system$ordered$set$$OrderedSet = function () {
this._super$constructor();
};
ember$data$lib$system$ordered$set$$OrderedSet.create = function () {
var Constructor = this;
return new Constructor();
};
ember$data$lib$system$ordered$set$$OrderedSet.prototype = Ember.create(ember$data$lib$system$ordered$set$$EmberOrderedSet.prototype);
ember$data$lib$system$ordered$set$$OrderedSet.prototype.constructor = ember$data$lib$system$ordered$set$$OrderedSet;
ember$data$lib$system$ordered$set$$OrderedSet.prototype._super$constructor = ember$data$lib$system$ordered$set$$EmberOrderedSet;
ember$data$lib$system$ordered$set$$OrderedSet.prototype.addWithIndex = function (obj, idx) {
var guid = ember$data$lib$system$ordered$set$$guidFor(obj);
var presenceSet = this.presenceSet;
var list = this.list;
if (presenceSet[guid] === true) {
return;
}
presenceSet[guid] = true;
if (idx === undefined || idx == null) {
list.push(obj);
} else {
list.splice(idx, 0, obj);
}
this.size += 1;
return this;
};
var ember$data$lib$system$ordered$set$$default = ember$data$lib$system$ordered$set$$OrderedSet;
var ember$data$lib$system$record$array$manager$$get = Ember.get;
var ember$data$lib$system$record$array$manager$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$record$array$manager$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$system$record$array$manager$$default = Ember.Object.extend({
init: function () {
this.filteredRecordArrays = ember$data$lib$system$map$$MapWithDefault.create({
defaultValue: function () {
return [];
}
});
this.changedRecords = [];
this._adapterPopulatedRecordArrays = [];
},
recordDidChange: function (record) {
if (this.changedRecords.push(record) !== 1) {
return;
}
Ember.run.schedule("actions", this, this.updateRecordArrays);
},
recordArraysForRecord: function (record) {
record._recordArrays = record._recordArrays || ember$data$lib$system$ordered$set$$default.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
*/
updateRecordArrays: function () {
ember$data$lib$system$record$array$manager$$forEach(this.changedRecords, function (record) {
if (record.isDeleted()) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) {
return;
}
recordArrays.forEach(function (array) {
array.removeInternalModel(record);
});
record._recordArrays = null;
},
//Don't need to update non filtered arrays on simple changes
_recordWasChanged: function (record) {
var typeClass = record.type;
var recordArrays = this.filteredRecordArrays.get(typeClass);
var filter;
ember$data$lib$system$record$array$manager$$forEach(recordArrays, function (array) {
filter = ember$data$lib$system$record$array$manager$$get(array, "filterFunction");
if (filter) {
this.updateRecordArray(array, filter, typeClass, record);
}
}, this);
},
//Need to update live arrays on loading
recordWasLoaded: function (record) {
var typeClass = record.type;
var recordArrays = this.filteredRecordArrays.get(typeClass);
var filter;
ember$data$lib$system$record$array$manager$$forEach(recordArrays, function (array) {
filter = ember$data$lib$system$record$array$manager$$get(array, "filterFunction");
this.updateRecordArray(array, filter, typeClass, record);
}, this);
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {DS.Model} typeClass
@param {InternalModel} record
*/
updateRecordArray: function (array, filter, typeClass, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record.getRecord());
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
if (!recordArrays.has(array)) {
array.addInternalModel(record);
recordArrays.add(array);
}
} else if (!shouldBeInArray) {
recordArrays["delete"](array);
array.removeInternalModel(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param {Array} array
@param {String} modelName
@param {Function} filter
*/
updateFilter: function (array, modelName, filter) {
var typeMap = this.store.typeMapFor(modelName);
var records = typeMap.records;
var record;
for (var i = 0, l = records.length; i < l; i++) {
record = records[i];
if (!record.isDeleted() && !record.isEmpty()) {
this.updateRecordArray(array, filter, modelName, record);
}
}
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} typeClass
@return {DS.RecordArray}
*/
createRecordArray: function (typeClass) {
var array = ember$data$lib$system$record$arrays$record$array$$default.create({
type: typeClass,
content: Ember.A(),
store: this.store,
isLoaded: true,
manager: this
});
this.registerFilteredRecordArray(array, typeClass);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {DS.Model} typeClass
@param {Function} filter
@param {Object} query (optional
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function (typeClass, filter, query) {
var array = ember$data$lib$system$record$arrays$filtered$record$array$$default.create({
query: query,
type: typeClass,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, typeClass, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {DS.Model} typeClass
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function (typeClass, query) {
var array = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default.create({
type: typeClass,
query: query,
content: Ember.A(),
store: this.store,
manager: this
});
this._adapterPopulatedRecordArrays.push(array);
return array;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {DS.Model} typeClass
@param {Function} filter
*/
registerFilteredRecordArray: function (array, typeClass, filter) {
var recordArrays = this.filteredRecordArrays.get(typeClass);
recordArrays.push(array);
this.updateFilter(array, typeClass, filter);
},
/**
Unregister a FilteredRecordArray.
So manager will not update this array.
@method unregisterFilteredRecordArray
@param {DS.RecordArray} array
*/
unregisterFilteredRecordArray: function (array) {
var recordArrays = this.filteredRecordArrays.get(array.type);
var index = ember$data$lib$system$record$array$manager$$indexOf(recordArrays, array);
recordArrays.splice(index, 1);
},
willDestroy: function () {
this._super.apply(this, arguments);
this.filteredRecordArrays.forEach(function (value) {
ember$data$lib$system$record$array$manager$$forEach(ember$data$lib$system$record$array$manager$$flatten(value), ember$data$lib$system$record$array$manager$$destroy);
});
ember$data$lib$system$record$array$manager$$forEach(this._adapterPopulatedRecordArrays, ember$data$lib$system$record$array$manager$$destroy);
}
});
function ember$data$lib$system$record$array$manager$$destroy(entry) {
entry.destroy();
}
function ember$data$lib$system$record$array$manager$$flatten(list) {
var length = list.length;
var result = Ember.A();
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
/**
* The `ContainerInstanceCache` serves as a lazy cache for looking up
* instances of serializers and adapters. It has some additional logic for
* finding the 'fallback' adapter or serializer.
*
* The 'fallback' adapter or serializer is an adapter or serializer that is looked up
* when the preferred lookup fails. For example, say you try to look up `adapter:post`,
* but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry.
*
* The `fallbacks` array passed will then be used; the first entry in the fallbacks array
* that exists in the container will then be cached for `adapter:post`. So, the next time you
* look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback
* was if `adapter:application` doesn't exist).
*
* @private
* @class ContainerInstanceCache
*
*/
function ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache(container) {
this._container = container;
this._cache = ember$lib$main$$default.create(null);
}
ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache.prototype = ember$lib$main$$default.create(null);
ember$lib$main$$default.merge(ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache.prototype, {
get: function (type, preferredKey, fallbacks) {
var cache = this._cache;
var preferredLookupKey = '' + type + ':' + preferredKey;
if (!(preferredLookupKey in cache)) {
var instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks);
if (instance) {
cache[preferredLookupKey] = instance;
}
}
return cache[preferredLookupKey];
},
_findInstance: function (type, fallbacks) {
for (var i = 0, _length = fallbacks.length; i < _length; i++) {
var fallback = fallbacks[i];
var lookupKey = '' + type + ':' + fallback;
var instance = this.instanceFor(lookupKey);
if (instance) {
return instance;
}
}
},
instanceFor: function (key) {
var cache = this._cache;
if (!cache[key]) {
var instance = this._container.lookup(key);
if (instance) {
cache[key] = instance;
}
}
return cache[key];
},
destroy: function () {
var cache = this._cache;
var cacheEntries = ember$lib$main$$default.keys(cache);
for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) {
var cacheKey = cacheEntries[i];
var cacheEntry = cache[cacheKey];
if (cacheEntry) {
cacheEntry.destroy();
}
}
this._container = null;
},
constructor: ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache,
toString: function () {
return 'ContainerInstanceCache';
}
});
var ember$data$lib$system$store$container$instance$cache$$default = ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache;
function ember$data$lib$system$merge$$merge(original, updates) {
if (!updates || typeof updates !== 'object') {
return original;
}
var props = Ember.keys(updates);
var prop;
var length = props.length;
for (var i = 0; i < length; i++) {
prop = props[i];
original[prop] = updates[prop];
}
return original;
}
var ember$data$lib$system$merge$$default = ember$data$lib$system$merge$$merge;
var ember$data$lib$system$relationships$state$relationship$$forEach = Ember.EnumerableUtils.forEach;
function ember$data$lib$system$relationships$state$relationship$$Relationship(store, record, inverseKey, relationshipMeta) {
this.members = new ember$data$lib$system$ordered$set$$default();
this.canonicalMembers = new ember$data$lib$system$ordered$set$$default();
this.store = store;
this.key = relationshipMeta.key;
this.inverseKey = inverseKey;
this.record = record;
this.isAsync = relationshipMeta.options.async;
this.relationshipMeta = relationshipMeta;
//This probably breaks for polymorphic relationship in complex scenarios, due to
//multiple possible modelNames
this.inverseKeyForImplicit = this.record.constructor.modelName + this.key;
this.linkPromise = null;
this.hasData = false;
}
ember$data$lib$system$relationships$state$relationship$$Relationship.prototype = {
constructor: ember$data$lib$system$relationships$state$relationship$$Relationship,
destroy: Ember.K,
clear: function () {
var members = this.members.list;
var member;
while (members.length > 0) {
member = members[0];
this.removeRecord(member);
}
},
disconnect: function () {
this.members.forEach(function (member) {
this.removeRecordFromInverse(member);
}, this);
},
reconnect: function () {
this.members.forEach(function (member) {
this.addRecordToInverse(member);
}, this);
},
removeRecords: function (records) {
var self = this;
ember$data$lib$system$relationships$state$relationship$$forEach(records, function (record) {
self.removeRecord(record);
});
},
addRecords: function (records, idx) {
var self = this;
ember$data$lib$system$relationships$state$relationship$$forEach(records, function (record) {
self.addRecord(record, idx);
if (idx !== undefined) {
idx++;
}
});
},
addCanonicalRecords: function (records, idx) {
for (var i = 0; i < records.length; i++) {
if (idx !== undefined) {
this.addCanonicalRecord(records[i], i + idx);
} else {
this.addCanonicalRecord(records[i]);
}
}
},
addCanonicalRecord: function (record, idx) {
if (!this.canonicalMembers.has(record)) {
this.canonicalMembers.add(record);
if (this.inverseKey) {
record._relationships.get(this.inverseKey).addCanonicalRecord(this.record);
} else {
if (!record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} });
}
record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record);
}
}
this.flushCanonicalLater();
this.setHasData(true);
},
removeCanonicalRecords: function (records, idx) {
for (var i = 0; i < records.length; i++) {
if (idx !== undefined) {
this.removeCanonicalRecord(records[i], i + idx);
} else {
this.removeCanonicalRecord(records[i]);
}
}
},
removeCanonicalRecord: function (record, idx) {
if (this.canonicalMembers.has(record)) {
this.removeCanonicalRecordFromOwn(record);
if (this.inverseKey) {
this.removeCanonicalRecordFromInverse(record);
} else {
if (record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record);
}
}
}
this.flushCanonicalLater();
},
addRecord: function (record, idx) {
if (!this.members.has(record)) {
this.members.addWithIndex(record, idx);
this.notifyRecordRelationshipAdded(record, idx);
if (this.inverseKey) {
record._relationships.get(this.inverseKey).addRecord(this.record);
} else {
if (!record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} });
}
record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record);
}
this.record.updateRecordArraysLater();
}
this.setHasData(true);
},
removeRecord: function (record) {
if (this.members.has(record)) {
this.removeRecordFromOwn(record);
if (this.inverseKey) {
this.removeRecordFromInverse(record);
} else {
if (record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record);
}
}
}
},
addRecordToInverse: function (record) {
if (this.inverseKey) {
record._relationships.get(this.inverseKey).addRecord(this.record);
}
},
removeRecordFromInverse: function (record) {
var inverseRelationship = record._relationships.get(this.inverseKey);
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeRecordFromOwn(this.record);
}
},
removeRecordFromOwn: function (record) {
this.members["delete"](record);
this.notifyRecordRelationshipRemoved(record);
this.record.updateRecordArrays();
},
removeCanonicalRecordFromInverse: function (record) {
var inverseRelationship = record._relationships.get(this.inverseKey);
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeCanonicalRecordFromOwn(this.record);
}
},
removeCanonicalRecordFromOwn: function (record) {
this.canonicalMembers["delete"](record);
this.flushCanonicalLater();
},
flushCanonical: function () {
this.willSync = false;
//a hack for not removing new records
//TODO remove once we have proper diffing
var newRecords = [];
for (var i = 0; i < this.members.list.length; i++) {
if (this.members.list[i].isNew()) {
newRecords.push(this.members.list[i]);
}
}
//TODO(Igor) make this less abysmally slow
this.members = this.canonicalMembers.copy();
for (i = 0; i < newRecords.length; i++) {
this.members.add(newRecords[i]);
}
},
flushCanonicalLater: function () {
if (this.willSync) {
return;
}
this.willSync = true;
var self = this;
this.store._backburner.join(function () {
self.store._backburner.schedule("syncRelationships", self, self.flushCanonical);
});
},
updateLink: function (link) {
if (link !== this.link) {
this.link = link;
this.linkPromise = null;
this.record.notifyPropertyChange(this.key);
}
},
findLink: function () {
if (this.linkPromise) {
return this.linkPromise;
} else {
var promise = this.fetchLink();
this.linkPromise = promise;
return promise.then(function (result) {
return result;
});
}
},
updateRecordsFromAdapter: function (records) {
//TODO(Igor) move this to a proper place
var self = this;
//TODO Once we have adapter support, we need to handle updated and canonical changes
self.computeChanges(records);
self.setHasData(true);
},
notifyRecordRelationshipAdded: Ember.K,
notifyRecordRelationshipRemoved: Ember.K,
setHasData: function (value) {
this.hasData = value;
}
};
var ember$data$lib$system$relationships$state$relationship$$default = ember$data$lib$system$relationships$state$relationship$$Relationship;
var ember$data$lib$system$many$array$$get = Ember.get;
var ember$data$lib$system$many$array$$set = Ember.set;
var ember$data$lib$system$many$array$$filter = Ember.ArrayPolyfills.filter;
var ember$data$lib$system$many$array$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$many$array$$default = Ember.Object.extend(Ember.MutableArray, Ember.Evented, {
init: function () {
this.currentState = Ember.A([]);
},
record: null,
canonicalState: null,
currentState: null,
length: 0,
objectAt: function (index) {
//Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses
if (!this.currentState[index]) {
return undefined;
}
return this.currentState[index].getRecord();
},
flushCanonical: function () {
//TODO make this smarter, currently its plenty stupid
var toSet = ember$data$lib$system$many$array$$filter.call(this.canonicalState, function (internalModel) {
return !internalModel.isDeleted();
});
//a hack for not removing new records
//TODO remove once we have proper diffing
var newRecords = this.currentState.filter(function (internalModel) {
return internalModel.isNew();
});
toSet = toSet.concat(newRecords);
var oldLength = this.length;
this.arrayContentWillChange(0, this.length, toSet.length);
this.set('length', toSet.length);
this.currentState = toSet;
this.arrayContentDidChange(0, oldLength, this.length);
//TODO Figure out to notify only on additions and maybe only if unloaded
this.relationship.notifyHasManyChanged();
this.record.updateRecordArrays();
},
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
isPolymorphic: false,
/**
The loading state of this array
@property {Boolean} isLoaded
*/
isLoaded: false,
/**
The relationship which manages this array.
@property {ManyRelationship} relationship
@private
*/
relationship: null,
internalReplace: function (idx, amt, objects) {
if (!objects) {
objects = [];
}
this.arrayContentWillChange(idx, amt, objects.length);
this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects));
this.set('length', this.currentState.length);
this.arrayContentDidChange(idx, amt, objects.length);
if (objects) {
//TODO(Igor) probably needed only for unloaded records
this.relationship.notifyHasManyChanged();
}
this.record.updateRecordArrays();
},
//TODO(Igor) optimize
internalRemoveRecords: function (records) {
var index;
for (var i = 0; i < records.length; i++) {
index = this.currentState.indexOf(records[i]);
this.internalReplace(index, 1);
}
},
//TODO(Igor) optimize
internalAddRecords: function (records, idx) {
if (idx === undefined) {
idx = this.currentState.length;
}
this.internalReplace(idx, 0, records);
},
replace: function (idx, amt, objects) {
var records;
if (amt > 0) {
records = this.currentState.slice(idx, idx + amt);
this.get('relationship').removeRecords(records);
}
if (objects) {
this.get('relationship').addRecords(ember$data$lib$system$many$array$$map(objects, function (obj) {
return obj._internalModel;
}), idx);
}
},
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
promise: null,
/**
@method loadingRecordsCount
@param {Number} count
@private
*/
loadingRecordsCount: function (count) {
this.loadingRecordsCount = count;
},
/**
@method loadedRecord
@private
*/
loadedRecord: function () {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
ember$data$lib$system$many$array$$set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
/**
@method reload
@public
*/
reload: function () {
return this.relationship.reload();
},
/**
Saves all of the records in the `ManyArray`.
Example
```javascript
store.find('inbox', 1).then(function(inbox) {
inbox.get('messages').then(function(messages) {
messages.forEach(function(message) {
message.set('isRead', true);
});
messages.save()
});
});
```
@method save
@return {DS.PromiseArray} promise
*/
save: function () {
var manyArray = this;
var promiseLabel = 'DS: ManyArray#save ' + ember$data$lib$system$many$array$$get(this, 'type');
var promise = Ember.RSVP.all(this.invoke('save'), promiseLabel).then(function (array) {
return manyArray;
}, null, 'DS: ManyArray#save return ManyArray');
return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise });
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function (hash) {
var store = ember$data$lib$system$many$array$$get(this, 'store');
var type = ember$data$lib$system$many$array$$get(this, 'type');
var record;
record = store.createRecord(type.modelName, hash);
this.pushObject(record);
return record;
},
/**
@method addRecord
@param {DS.Model} record
@deprecated Use `addObject()` instead
*/
addRecord: function (record) {
this.addObject(record);
},
/**
@method removeRecord
@param {DS.Model} record
@deprecated Use `removeObject()` instead
*/
removeRecord: function (record) {
this.removeObject(record);
}
});
var ember$data$lib$system$relationships$state$has$many$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$relationships$state$has$many$$ManyRelationship = function (store, record, inverseKey, relationshipMeta) {
this._super$constructor(store, record, inverseKey, relationshipMeta);
this.belongsToType = relationshipMeta.type;
this.canonicalState = [];
this.manyArray = ember$data$lib$system$many$array$$default.create({
canonicalState: this.canonicalState,
store: this.store,
relationship: this,
type: this.store.modelFor(this.belongsToType),
record: record
});
this.isPolymorphic = relationshipMeta.options.polymorphic;
this.manyArray.isPolymorphic = this.isPolymorphic;
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype);
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.constructor = ember$data$lib$system$relationships$state$has$many$$ManyRelationship;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.destroy = function () {
this.manyArray.destroy();
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addCanonicalRecord = function (record, idx) {
if (this.canonicalMembers.has(record)) {
return;
}
if (idx !== undefined) {
this.canonicalState.splice(idx, 0, record);
} else {
this.canonicalState.push(record);
}
this._super$addCanonicalRecord(record, idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addRecord = function (record, idx) {
if (this.members.has(record)) {
return;
}
this._super$addRecord(record, idx);
this.manyArray.internalAddRecords([record], idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) {
var i = idx;
if (!this.canonicalMembers.has(record)) {
return;
}
if (i === undefined) {
i = this.canonicalState.indexOf(record);
}
if (i > -1) {
this.canonicalState.splice(i, 1);
}
this._super$removeCanonicalRecordFromOwn(record, idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.flushCanonical = function () {
this.manyArray.flushCanonical();
this._super$flushCanonical();
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) {
if (!this.members.has(record)) {
return;
}
this._super$removeRecordFromOwn(record, idx);
if (idx !== undefined) {
//TODO(Igor) not used currently, fix
this.manyArray.currentState.removeAt(idx);
} else {
this.manyArray.internalRemoveRecords([record]);
}
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) {
var typeClass = this.store.modelFor(this.relationshipMeta.type);
this.record.notifyHasManyAdded(this.key, record, idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.reload = function () {
var self = this;
if (this.link) {
return this.fetchLink();
} else {
return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function () {
//Goes away after the manyArray refactor
self.manyArray.set("isLoaded", true);
return self.manyArray;
});
}
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.computeChanges = function (records) {
var members = this.canonicalMembers;
var recordsToRemove = [];
var length;
var record;
var i;
records = ember$data$lib$system$relationships$state$has$many$$setForArray(records);
members.forEach(function (member) {
if (records.has(member)) {
return;
}
recordsToRemove.push(member);
});
this.removeCanonicalRecords(recordsToRemove);
// Using records.toArray() since currently using
// removeRecord can modify length, messing stuff up
// forEach since it directly looks at "length" each
// iteration
records = records.toArray();
length = records.length;
for (i = 0; i < length; i++) {
record = records[i];
this.removeCanonicalRecord(record);
this.addCanonicalRecord(record, i);
}
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.fetchLink = function () {
var self = this;
return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) {
self.store._backburner.join(function () {
self.updateRecordsFromAdapter(records);
});
return self.manyArray;
});
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.findRecords = function () {
var manyArray = this.manyArray;
//TODO CLEANUP
return this.store.findMany(ember$data$lib$system$relationships$state$has$many$$map(manyArray.toArray(), function (rec) {
return rec._internalModel;
})).then(function () {
//Goes away after the manyArray refactor
manyArray.set("isLoaded", true);
return manyArray;
});
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyHasManyChanged = function () {
this.record.notifyHasManyAdded(this.key);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.getRecords = function () {
//TODO(Igor) sync server here, once our syncing is not stupid
if (this.isAsync) {
var self = this;
var promise;
if (this.link) {
promise = this.findLink().then(function () {
return self.findRecords();
});
} else {
promise = this.findRecords();
}
return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({
content: this.manyArray,
promise: promise
});
} else {
//TODO(Igor) WTF DO I DO HERE?
if (!this.manyArray.get("isDestroyed")) {
this.manyArray.set("isLoaded", true);
}
return this.manyArray;
}
};
function ember$data$lib$system$relationships$state$has$many$$setForArray(array) {
var set = new ember$data$lib$system$ordered$set$$default();
if (array) {
for (var i = 0, l = array.length; i < l; i++) {
set.add(array[i]);
}
}
return set;
}
var ember$data$lib$system$relationships$state$has$many$$default = ember$data$lib$system$relationships$state$has$many$$ManyRelationship;
var ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship = function (store, record, inverseKey, relationshipMeta) {
this._super$constructor(store, record, inverseKey, relationshipMeta);
this.record = record;
this.key = relationshipMeta.key;
this.inverseRecord = null;
this.canonicalState = null;
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype);
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.constructor = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecord = function (newRecord) {
if (newRecord) {
this.addRecord(newRecord);
} else if (this.inverseRecord) {
this.removeRecord(this.inverseRecord);
}
this.setHasData(true);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) {
if (newRecord) {
this.addCanonicalRecord(newRecord);
} else if (this.inverseRecord) {
this.removeCanonicalRecord(this.inverseRecord);
}
this.setHasData(true);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) {
if (this.canonicalMembers.has(newRecord)) {
return;
}
if (this.canonicalState) {
this.removeCanonicalRecord(this.canonicalState);
}
this.canonicalState = newRecord;
this._super$addCanonicalRecord(newRecord);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.flushCanonical = function () {
//temporary fix to not remove newly created records if server returned null.
//TODO remove once we have proper diffing
if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) {
return;
}
this.inverseRecord = this.canonicalState;
this.record.notifyBelongsToChanged(this.key);
this._super$flushCanonical();
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addRecord = function (newRecord) {
if (this.members.has(newRecord)) {
return;
}
var typeClass = this.store.modelFor(this.relationshipMeta.type);
if (this.inverseRecord) {
this.removeRecord(this.inverseRecord);
}
this.inverseRecord = newRecord;
this._super$addRecord(newRecord);
this.record.notifyBelongsToChanged(this.key);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecordPromise = function (newPromise) {
var content = newPromise.get && newPromise.get("content");
this.setRecord(content ? content._internalModel : content);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeRecordFromOwn = function (record) {
if (!this.members.has(record)) {
return;
}
this.inverseRecord = null;
this._super$removeRecordFromOwn(record);
this.record.notifyBelongsToChanged(this.key);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) {
if (!this.canonicalMembers.has(record)) {
return;
}
this.canonicalState = null;
this._super$removeCanonicalRecordFromOwn(record);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.findRecord = function () {
if (this.inverseRecord) {
return this.store._findByInternalModel(this.inverseRecord);
} else {
return Ember.RSVP.Promise.resolve(null);
}
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.fetchLink = function () {
var self = this;
return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) {
if (record) {
self.addRecord(record);
}
return record;
});
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.getRecord = function () {
//TODO(Igor) flushCanonical here once our syncing is not stupid
if (this.isAsync) {
var promise;
if (this.link) {
var self = this;
promise = this.findLink().then(function () {
return self.findRecord();
});
} else {
promise = this.findRecord();
}
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: promise,
content: this.inverseRecord ? this.inverseRecord.getRecord() : null
});
} else {
if (this.inverseRecord === null) {
return null;
}
var toReturn = this.inverseRecord.getRecord();
return toReturn;
}
};
var ember$data$lib$system$relationships$state$belongs$to$$default = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship;
var ember$data$lib$system$relationships$state$create$$get = Ember.get;
var ember$data$lib$system$relationships$state$create$$createRelationshipFor = function (record, relationshipMeta, store) {
var inverseKey;
var inverse = record.type.inverseFor(relationshipMeta.key, store);
if (inverse) {
inverseKey = inverse.name;
}
if (relationshipMeta.kind === "hasMany") {
return new ember$data$lib$system$relationships$state$has$many$$default(store, record, inverseKey, relationshipMeta);
} else {
return new ember$data$lib$system$relationships$state$belongs$to$$default(store, record, inverseKey, relationshipMeta);
}
};
var ember$data$lib$system$relationships$state$create$$Relationships = function (record) {
this.record = record;
this.initializedRelationships = Ember.create(null);
};
ember$data$lib$system$relationships$state$create$$Relationships.prototype.has = function (key) {
return !!this.initializedRelationships[key];
};
ember$data$lib$system$relationships$state$create$$Relationships.prototype.get = function (key) {
var relationships = this.initializedRelationships;
var relationshipsByName = ember$data$lib$system$relationships$state$create$$get(this.record.type, "relationshipsByName");
if (!relationships[key] && relationshipsByName.get(key)) {
relationships[key] = ember$data$lib$system$relationships$state$create$$createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store);
}
return relationships[key];
};
var ember$data$lib$system$relationships$state$create$$default = ember$data$lib$system$relationships$state$create$$Relationships;
var ember$data$lib$system$snapshot$$get = Ember.get;
/**
@class Snapshot
@namespace DS
@private
@constructor
@param {DS.Model} internalModel The model to create a snapshot from
*/
function ember$data$lib$system$snapshot$$Snapshot(internalModel) {
this._attributes = Ember.create(null);
this._belongsToRelationships = Ember.create(null);
this._belongsToIds = Ember.create(null);
this._hasManyRelationships = Ember.create(null);
this._hasManyIds = Ember.create(null);
var record = internalModel.getRecord();
this.record = record;
record.eachAttribute(function (keyName) {
this._attributes[keyName] = ember$data$lib$system$snapshot$$get(record, keyName);
}, this);
this.id = internalModel.id;
this._internalModel = internalModel;
this.type = internalModel.type;
this.modelName = internalModel.type.modelName;
this._changedAttributes = record.changedAttributes();
// The following code is here to keep backwards compatibility when accessing
// `constructor` directly.
//
// With snapshots you should use `type` instead of `constructor`.
//
// Remove for Ember Data 1.0.
if (Ember.platform.hasPropertyAccessors) {
var callDeprecate = true;
Ember.defineProperty(this, 'constructor', {
get: function () {
// Ugly hack since accessing error.stack (done in `Ember.deprecate()`)
// causes the internals of Chrome to access the constructor, which then
// causes an infinite loop if accessed and calls `Ember.deprecate()`
// again.
if (callDeprecate) {
callDeprecate = false;
callDeprecate = true;
}
return this.type;
}
});
} else {
this.constructor = this.type;
}
}
ember$data$lib$system$snapshot$$Snapshot.prototype = {
constructor: ember$data$lib$system$snapshot$$Snapshot,
/**
The id of the snapshot's underlying record
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.id; // => '1'
```
@property id
@type {String}
*/
id: null,
/**
The underlying record for this snapshot. Can be used to access methods and
properties defined on the record.
Example
```javascript
var json = snapshot.record.toJSON();
```
@property record
@type {DS.Model}
*/
record: null,
/**
The type of the underlying record for this snapshot, as a DS.Model.
@property type
@type {DS.Model}
*/
type: null,
/**
The name of the type of the underlying record for this snapshot, as a string.
@property modelName
@type {String}
*/
modelName: null,
/**
Returns the value of an attribute.
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.attr('author'); // => 'Tomster'
postSnapshot.attr('title'); // => 'Ember.js rocks'
```
Note: Values are loaded eagerly and cached when the snapshot is created.
@method attr
@param {String} keyName
@return {Object} The attribute value or undefined
*/
attr: function (keyName) {
if (keyName in this._attributes) {
return this._attributes[keyName];
}
throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no attribute named \'' + keyName + '\' defined.');
},
/**
Returns all attributes and their corresponding values.
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' }
```
@method attributes
@return {Object} All attributes of the current snapshot
*/
attributes: function () {
return Ember.copy(this._attributes);
},
/**
Returns all changed attributes and their old and new values.
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postModel.set('title', 'Ember.js rocks!');
postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] }
```
@method changedAttributes
@return {Object} All changed attributes of the current snapshot
*/
changedAttributes: function () {
var prop;
var changedAttributes = Ember.create(null);
for (prop in this._changedAttributes) {
changedAttributes[prop] = Ember.copy(this._changedAttributes[prop]);
}
return changedAttributes;
},
/**
Returns the current value of a belongsTo relationship.
`belongsTo` takes an optional hash of options as a second parameter,
currently supported options are:
- `id`: set to `true` if you only want the ID of the related record to be
returned.
Example
```javascript
// store.push('post', { id: 1, title: 'Hello World' });
// store.createRecord('comment', { body: 'Lorem ipsum', post: post });
commentSnapshot.belongsTo('post'); // => DS.Snapshot
commentSnapshot.belongsTo('post', { id: true }); // => '1'
// store.push('comment', { id: 1, body: 'Lorem ipsum' });
commentSnapshot.belongsTo('post'); // => undefined
```
Calling `belongsTo` will return a new Snapshot as long as there's any known
data for the relationship available, such as an ID. If the relationship is
known but unset, `belongsTo` will return `null`. If the contents of the
relationship is unknown `belongsTo` will return `undefined`.
Note: Relationships are loaded lazily and cached upon first access.
@method belongsTo
@param {String} keyName
@param {Object} [options]
@return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known
relationship or null if the relationship is known but unset. undefined
will be returned if the contents of the relationship is unknown.
*/
belongsTo: function (keyName, options) {
var id = options && options.id;
var relationship, inverseRecord, hasData;
var result;
if (id && keyName in this._belongsToIds) {
return this._belongsToIds[keyName];
}
if (!id && keyName in this._belongsToRelationships) {
return this._belongsToRelationships[keyName];
}
relationship = this._internalModel._relationships.get(keyName);
if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) {
throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no belongsTo relationship named \'' + keyName + '\' defined.');
}
hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData');
inverseRecord = ember$data$lib$system$snapshot$$get(relationship, 'inverseRecord');
if (hasData) {
if (inverseRecord && !inverseRecord.isDeleted()) {
if (id) {
result = ember$data$lib$system$snapshot$$get(inverseRecord, 'id');
} else {
result = inverseRecord.createSnapshot();
}
} else {
result = null;
}
}
if (id) {
this._belongsToIds[keyName] = result;
} else {
this._belongsToRelationships[keyName] = result;
}
return result;
},
/**
Returns the current value of a hasMany relationship.
`hasMany` takes an optional hash of options as a second parameter,
currently supported options are:
- `ids`: set to `true` if you only want the IDs of the related records to be
returned.
Example
```javascript
// store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] });
postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot]
postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3']
// store.push('post', { id: 1, title: 'Hello World' });
postSnapshot.hasMany('comments'); // => undefined
```
Note: Relationships are loaded lazily and cached upon first access.
@method hasMany
@param {String} keyName
@param {Object} [options]
@return {(Array|undefined)} An array of snapshots or IDs of a known
relationship or an empty array if the relationship is known but unset.
undefined will be returned if the contents of the relationship is unknown.
*/
hasMany: function (keyName, options) {
var ids = options && options.ids;
var relationship, members, hasData;
var results;
if (ids && keyName in this._hasManyIds) {
return this._hasManyIds[keyName];
}
if (!ids && keyName in this._hasManyRelationships) {
return this._hasManyRelationships[keyName];
}
relationship = this._internalModel._relationships.get(keyName);
if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) {
throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no hasMany relationship named \'' + keyName + '\' defined.');
}
hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData');
members = ember$data$lib$system$snapshot$$get(relationship, 'members');
if (hasData) {
results = [];
members.forEach(function (member) {
if (!member.isDeleted()) {
if (ids) {
results.push(member.id);
} else {
results.push(member.createSnapshot());
}
}
});
}
if (ids) {
this._hasManyIds[keyName] = results;
} else {
this._hasManyRelationships[keyName] = results;
}
return results;
},
/**
Iterates through all the attributes of the model, calling the passed
function on each attribute.
Example
```javascript
snapshot.eachAttribute(function(name, meta) {
// ...
});
```
@method eachAttribute
@param {Function} callback the callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
*/
eachAttribute: function (callback, binding) {
this.record.eachAttribute(callback, binding);
},
/**
Iterates through all the relationships of the model, calling the passed
function on each relationship.
Example
```javascript
snapshot.eachRelationship(function(name, relationship) {
// ...
});
```
@method eachRelationship
@param {Function} callback the callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
*/
eachRelationship: function (callback, binding) {
this.record.eachRelationship(callback, binding);
},
/**
@method get
@param {String} keyName
@return {Object} The property value
@deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead
*/
get: function (keyName) {
if (keyName === 'id') {
return this.id;
}
if (keyName in this._attributes) {
return this.attr(keyName);
}
var relationship = this._internalModel._relationships.get(keyName);
if (relationship && relationship.relationshipMeta.kind === 'belongsTo') {
return this.belongsTo(keyName);
}
if (relationship && relationship.relationshipMeta.kind === 'hasMany') {
return this.hasMany(keyName);
}
return ember$data$lib$system$snapshot$$get(this.record, keyName);
},
/**
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function (options) {
return this.record.store.serializerFor(this.modelName).serialize(this, options);
},
/**
@method unknownProperty
@param {String} keyName
@return {Object} The property value
@deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead
*/
unknownProperty: function (keyName) {
return this.get(keyName);
},
/**
@method _createSnapshot
@private
*/
_createSnapshot: function () {
return this;
}
};
Ember.defineProperty(ember$data$lib$system$snapshot$$Snapshot.prototype, 'typeKey', {
enumerable: false,
get: function () {
return this.modelName;
},
set: function () {
}
});
var ember$data$lib$system$snapshot$$default = ember$data$lib$system$snapshot$$Snapshot;
var ember$data$lib$system$model$internal$model$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$model$internal$model$$get = Ember.get;
var ember$data$lib$system$model$internal$model$$set = Ember.set;
var ember$data$lib$system$model$internal$model$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$system$model$internal$model$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$system$model$internal$model$$_extractPivotNameCache = Ember.create(null);
var ember$data$lib$system$model$internal$model$$_splitOnDotCache = Ember.create(null);
function ember$data$lib$system$model$internal$model$$splitOnDot(name) {
return ember$data$lib$system$model$internal$model$$_splitOnDotCache[name] || (ember$data$lib$system$model$internal$model$$_splitOnDotCache[name] = name.split("."));
}
function ember$data$lib$system$model$internal$model$$extractPivotName(name) {
return ember$data$lib$system$model$internal$model$$_extractPivotNameCache[name] || (ember$data$lib$system$model$internal$model$$_extractPivotNameCache[name] = ember$data$lib$system$model$internal$model$$splitOnDot(name)[0]);
}
function ember$data$lib$system$model$internal$model$$retrieveFromCurrentState(key) {
return function () {
return ember$data$lib$system$model$internal$model$$get(this.currentState, key);
};
}
/**
`InternalModel` is the Model class that we use internally inside Ember Data to represent models.
Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class.
We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as
a performance optimization.
`InternalModel` should never be exposed to application code. At the boundaries of the system, in places
like `find`, `push`, etc. we convert between Models and InternalModels.
We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model`
if they are needed.
@class InternalModel
*/
var ember$data$lib$system$model$internal$model$$InternalModel = function InternalModel(type, id, store, container, data) {
this.type = type;
this.id = id;
this.store = store;
this.container = container;
this._data = data || Ember.create(null);
this.modelName = type.modelName;
this.errors = null;
this.dataHasInitialized = false;
//Look into making this lazy
this._deferredTriggers = [];
this._attributes = Ember.create(null);
this._inFlightAttributes = Ember.create(null);
this._relationships = new ember$data$lib$system$relationships$state$create$$default(this);
this.currentState = ember$data$lib$system$model$states$$default.empty;
this.isReloading = false;
/*
implicit relationships are relationship which have not been declared but the inverse side exists on
another record somewhere
For example if there was
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr()
})
```
but there is also
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
comments: DS.hasMany('comment')
})
```
would have a implicit post relationship in order to be do things like remove ourselves from the post
when we are deleted
*/
this._implicitRelationships = Ember.create(null);
};
ember$data$lib$system$model$internal$model$$InternalModel.prototype = {
isEmpty: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isEmpty"),
isLoading: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isLoading"),
isLoaded: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isLoaded"),
isDirty: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isDirty"),
isSaving: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isSaving"),
isDeleted: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isDeleted"),
isNew: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isNew"),
isValid: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isValid"),
dirtyType: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("dirtyType"),
constructor: ember$data$lib$system$model$internal$model$$InternalModel,
materializeRecord: function () {
// lookupFactory should really return an object that creates
// instances with the injections applied
this.record = this.type._create({
id: this.id,
store: this.store,
container: this.container,
_internalModel: this,
currentState: ember$data$lib$system$model$internal$model$$get(this, "currentState")
});
this._triggerDeferredTriggers();
},
recordObjectWillDestroy: function () {
this.record = null;
},
deleteRecord: function () {
this.send("deleteRecord");
},
save: function () {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.store.scheduleSave(this, resolver);
return resolver.promise;
},
startedReloading: function () {
this.isReloading = true;
if (this.record) {
ember$data$lib$system$model$internal$model$$set(this.record, "isReloading", true);
}
},
finishedReloading: function () {
this.isReloading = false;
if (this.record) {
ember$data$lib$system$model$internal$model$$set(this.record, "isReloading", false);
}
},
reload: function () {
this.startedReloading();
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
return new ember$data$lib$system$model$internal$model$$Promise(function (resolve) {
record.send("reloadRecord", resolve);
}, promiseLabel).then(function () {
record.didCleanError();
return record;
}, function (reason) {
record.didError();
throw reason;
}, "DS: Model#reload complete, update flags")["finally"](function () {
record.finishedReloading();
record.updateRecordArrays();
});
},
getRecord: function () {
if (!this.record) {
this.materializeRecord();
}
return this.record;
},
unloadRecord: function () {
this.send("unloadRecord");
},
eachRelationship: function (callback, binding) {
return this.type.eachRelationship(callback, binding);
},
eachAttribute: function (callback, binding) {
return this.type.eachAttribute(callback, binding);
},
inverseFor: function (key) {
return this.type.inverseFor(key);
},
setupData: function (data) {
var changedKeys = ember$data$lib$system$model$internal$model$$mergeAndReturnChangedKeys(this._data, data);
this.pushedData();
if (this.record) {
this.record._notifyProperties(changedKeys);
}
this.didInitalizeData();
},
becameReady: function () {
Ember.run.schedule("actions", this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this);
},
didInitalizeData: function () {
if (!this.dataHasInitialized) {
this.becameReady();
this.dataHasInitialized = true;
}
},
destroy: function () {
if (this.record) {
return this.record.destroy();
}
},
/**
@method createSnapshot
@private
*/
createSnapshot: function () {
return new ember$data$lib$system$snapshot$$default(this);
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function (promise) {
this.send("loadingData", promise);
},
/**
@method loadedData
@private
*/
loadedData: function () {
this.send("loadedData");
this.didInitalizeData();
},
/**
@method notFound
@private
*/
notFound: function () {
this.send("notFound");
},
/**
@method pushedData
@private
*/
pushedData: function () {
this.send("pushedData");
},
flushChangedAttributes: function () {
this._inFlightAttributes = this._attributes;
this._attributes = Ember.create(null);
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function () {
this.send("willCommit");
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function () {
this.send("becomeDirty");
this.updateRecordArraysLater();
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function (name, context) {
var currentState = ember$data$lib$system$model$internal$model$$get(this, "currentState");
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
notifyHasManyAdded: function (key, record, idx) {
if (this.record) {
this.record.notifyHasManyAdded(key, record, idx);
}
},
notifyHasManyRemoved: function (key, record, idx) {
if (this.record) {
this.record.notifyHasManyRemoved(key, record, idx);
}
},
notifyBelongsToChanged: function (key, record) {
if (this.record) {
this.record.notifyBelongsToChanged(key, record);
}
},
notifyPropertyChange: function (key) {
if (this.record) {
this.record.notifyPropertyChange(key);
}
},
rollback: function () {
var dirtyKeys = Ember.keys(this._attributes);
this._attributes = Ember.create(null);
if (ember$data$lib$system$model$internal$model$$get(this, "isError")) {
this._inFlightAttributes = Ember.create(null);
this.didCleanError();
}
//Eventually rollback will always work for relationships
//For now we support it only out of deleted state, because we
//have an explicit way of knowing when the server acked the relationship change
if (this.isDeleted()) {
//TODO: Should probably move this to the state machine somehow
this.becameReady();
this.reconnectRelationships();
}
if (this.isNew()) {
this.clearRelationships();
}
if (this.isValid()) {
this._inFlightAttributes = Ember.create(null);
}
this.send("rolledBack");
this.record._notifyProperties(dirtyKeys);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function (name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct reference to state objects
var pivotName = ember$data$lib$system$model$internal$model$$extractPivotName(name);
var currentState = ember$data$lib$system$model$internal$model$$get(this, "currentState");
var state = currentState;
do {
if (state.exit) {
state.exit(this);
}
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = ember$data$lib$system$model$internal$model$$splitOnDot(name);
var setups = [];
var enters = [];
var i, l;
for (i = 0, l = path.length; i < l; i++) {
state = state[path[i]];
if (state.enter) {
enters.push(state);
}
if (state.setup) {
setups.push(state);
}
}
for (i = 0, l = enters.length; i < l; i++) {
enters[i].enter(this);
}
ember$data$lib$system$model$internal$model$$set(this, "currentState", state);
//TODO Consider whether this is the best approach for keeping these two in sync
if (this.record) {
ember$data$lib$system$model$internal$model$$set(this.record, "currentState", state);
}
for (i = 0, l = setups.length; i < l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function (state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
triggerLater: function () {
var length = arguments.length;
var args = new Array(length);
for (var i = 0; i < length; i++) {
args[i] = arguments[i];
}
if (this._deferredTriggers.push(args) !== 1) {
return;
}
Ember.run.scheduleOnce("actions", this, "_triggerDeferredTriggers");
},
_triggerDeferredTriggers: function () {
//TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record,
//but for now, we queue up all the events triggered before the record was materialized, and flush
//them once we have the record
if (!this.record) {
return;
}
for (var i = 0, l = this._deferredTriggers.length; i < l; i++) {
this.record.trigger.apply(this.record, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
/**
@method clearRelationships
@private
*/
clearRelationships: function () {
this.eachRelationship(function (name, relationship) {
if (this._relationships.has(name)) {
var rel = this._relationships.get(name);
//TODO(Igor) figure out whether we want to clear or disconnect
rel.clear();
rel.destroy();
}
}, this);
var model = this;
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(this._implicitRelationships), function (key) {
model._implicitRelationships[key].clear();
model._implicitRelationships[key].destroy();
});
},
disconnectRelationships: function () {
this.eachRelationship(function (name, relationship) {
this._relationships.get(name).disconnect();
}, this);
var model = this;
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(this._implicitRelationships), function (key) {
model._implicitRelationships[key].disconnect();
});
},
reconnectRelationships: function () {
this.eachRelationship(function (name, relationship) {
this._relationships.get(name).reconnect();
}, this);
var model = this;
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(this._implicitRelationships), function (key) {
model._implicitRelationships[key].reconnect();
});
},
/**
When a find request is triggered on the store, the user can optionally pass in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, except the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.find('comment', 2, {post:1})` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method _preloadData
@private
@param {Object} preload
*/
_preloadData: function (preload) {
var record = this;
//TODO(Igor) consider the polymorphic case
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(preload), function (key) {
var preloadValue = ember$data$lib$system$model$internal$model$$get(preload, key);
var relationshipMeta = record.type.metaForProperty(key);
if (relationshipMeta.isRelationship) {
record._preloadRelationship(key, preloadValue);
} else {
record._data[key] = preloadValue;
}
});
},
_preloadRelationship: function (key, preloadValue) {
var relationshipMeta = this.type.metaForProperty(key);
var type = relationshipMeta.type;
if (relationshipMeta.kind === "hasMany") {
this._preloadHasMany(key, preloadValue, type);
} else {
this._preloadBelongsTo(key, preloadValue, type);
}
},
_preloadHasMany: function (key, preloadValue, type) {
var internalModel = this;
var recordsToSet = ember$data$lib$system$model$internal$model$$map.call(preloadValue, function (recordToPush) {
return internalModel._convertStringOrNumberIntoInternalModel(recordToPush, type);
});
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).updateRecordsFromAdapter(recordsToSet);
},
_preloadBelongsTo: function (key, preloadValue, type) {
var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).setRecord(recordToSet);
},
_convertStringOrNumberIntoInternalModel: function (value, type) {
if (typeof value === "string" || typeof value === "number") {
return this.store._internalModelForId(type, value);
}
if (value._internalModel) {
return value._internalModel;
}
return value;
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function () {
this._updatingRecordArraysLater = false;
this.store.dataWasUpdated(this.type, this);
},
setId: function (id) {
this.id = id;
//TODO figure out whether maybe we should proxy
ember$data$lib$system$model$internal$model$$set(this.record, "id", id);
},
didError: function () {
this.isError = true;
if (this.record) {
this.record.set("isError", true);
}
},
didCleanError: function () {
this.isError = false;
if (this.record) {
this.record.set("isError", false);
}
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function (data) {
var changedKeys;
this.didCleanError();
if (data) {
changedKeys = ember$data$lib$system$model$internal$model$$mergeAndReturnChangedKeys(this._data, data);
} else {
ember$data$lib$system$merge$$default(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = Ember.create(null);
this.send("didCommit");
this.updateRecordArraysLater();
if (!data) {
return;
}
this.record._notifyProperties(changedKeys);
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function () {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) {
return;
}
this._updatingRecordArraysLater = true;
Ember.run.schedule("actions", this, this.updateRecordArrays);
},
getErrors: function () {
if (this.errors) {
return this.errors;
}
var errors = ember$data$lib$system$model$errors$$default.create();
errors.registerHandlers(this, function () {
this.send("becameInvalid");
}, function () {
this.send("becameValid");
});
this.errors = errors;
return errors;
},
// FOR USE DURING COMMIT PROCESS
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function (errors) {
var recordErrors = this.getErrors();
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(errors), function (key) {
recordErrors.add(key, errors[key]);
});
this._saveWasRejected();
},
/**
@method adapterDidError
@private
*/
adapterDidError: function () {
this.send("becameError");
this.didError();
this._saveWasRejected();
},
_saveWasRejected: function () {
var keys = Ember.keys(this._inFlightAttributes);
for (var i = 0; i < keys.length; i++) {
if (this._attributes[keys[i]] === undefined) {
this._attributes[keys[i]] = this._inFlightAttributes[keys[i]];
}
}
this._inFlightAttributes = Ember.create(null);
},
toString: function () {
if (this.record) {
return this.record.toString();
} else {
return "<" + this.modelName + ":" + this.id + ">";
}
}
};
// Like Ember.merge, but instead returns a list of keys
// for values that fail a strict equality check
// instead of the original object.
function ember$data$lib$system$model$internal$model$$mergeAndReturnChangedKeys(original, updates) {
var changedKeys = [];
if (!updates || typeof updates !== "object") {
return changedKeys;
}
var keys = Ember.keys(updates);
var length = keys.length;
var i, val, key;
for (i = 0; i < length; i++) {
key = keys[i];
val = updates[key];
if (original[key] !== val) {
changedKeys.push(key);
}
original[key] = val;
}
return changedKeys;
}
var ember$data$lib$system$model$internal$model$$default = ember$data$lib$system$model$internal$model$$InternalModel;
var ember$data$lib$system$store$$Backburner = Ember.Backburner || Ember.__loader.require("backburner")["default"] || Ember.__loader.require("backburner")["Backburner"];
//Shim Backburner.join
if (!ember$data$lib$system$store$$Backburner.prototype.join) {
var ember$data$lib$system$store$$isString = function (suspect) {
return typeof suspect === "string";
};
ember$data$lib$system$store$$Backburner.prototype.join = function () {
var method, target;
if (this.currentInstance) {
var length = arguments.length;
if (length === 1) {
method = arguments[0];
target = null;
} else {
target = arguments[0];
method = arguments[1];
}
if (ember$data$lib$system$store$$isString(method)) {
method = target[method];
}
if (length === 1) {
return method();
} else if (length === 2) {
return method.call(target);
} else {
var args = new Array(length - 2);
for (var i = 0, l = length - 2; i < l; i++) {
args[i] = arguments[i + 2];
}
return method.apply(target, args);
}
} else {
return this.run.apply(this, arguments);
}
};
}
//Get the materialized model from the internalModel/promise that returns
//an internal model and return it in a promiseObject. Useful for returning
//from find methods
function ember$data$lib$system$store$$promiseRecord(internalModel, label) {
//TODO cleanup
var toReturn = internalModel;
if (!internalModel.then) {
toReturn = internalModel.getRecord();
} else {
toReturn = internalModel.then(function (model) {
return model.getRecord();
});
}
return ember$data$lib$system$promise$proxies$$promiseObject(toReturn, label);
}
var ember$data$lib$system$store$$get = Ember.get;
var ember$data$lib$system$store$$set = Ember.set;
var ember$data$lib$system$store$$once = Ember.run.once;
var ember$data$lib$system$store$$isNone = Ember.isNone;
var ember$data$lib$system$store$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$store$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$system$store$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$store$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$store$$copy = Ember.copy;
var ember$data$lib$system$store$$Store;
var ember$data$lib$system$store$$Service = Ember.Service;
if (!ember$data$lib$system$store$$Service) {
ember$data$lib$system$store$$Service = Ember.Object;
}
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +internalModel+ means a record internalModel object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a DS.Model.
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```app/stores/application.js
import DS from 'ember-data';
export default DS.Store.extend({
});
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `find()` method:
```javascript
store.find('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](#method_createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend you will need to call `record.save()`.
[push](#method_push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates (full or partial) that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](#method_pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
Note: When creating a new record using any of the above methods
Ember Data will update `DS.RecordArray`s such as those returned by
`store#all()`, `store#findAll()` or `store#filter()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@class Store
@namespace DS
@extends Ember.Service
*/
ember$data$lib$system$store$$Store = ember$data$lib$system$store$$Service.extend({
/**
@method init
@private
*/
init: function () {
this._backburner = new ember$data$lib$system$store$$Backburner(["normalizeRelationships", "syncRelationships", "finished"]);
// internal bookkeeping; not observable
this.typeMaps = {};
this.recordArrayManager = ember$data$lib$system$record$array$manager$$default.create({
store: this
});
this._pendingSave = [];
this._instanceCache = new ember$data$lib$system$store$container$instance$cache$$default(this.container);
//Used to keep track of all the find requests that need to be coalesced
this._pendingFetch = ember$data$lib$system$map$$Map.create();
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `app/adapters/custom.js` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {(DS.Adapter|String)}
*/
adapter: "-rest",
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function (record, options) {
var snapshot = record._internalModel.createSnapshot();
return snapshot.serialize(options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@return DS.Adapter
*/
defaultAdapter: Ember.computed("adapter", function () {
var adapter = ember$data$lib$system$store$$get(this, "adapter");
adapter = this.retrieveManagedInstance("adapter", adapter);
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} modelName
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {DS.Model} record
*/
createRecord: function (modelName, inputProperties) {
var typeClass = this.modelFor(modelName);
var properties = ember$data$lib$system$store$$copy(inputProperties) || Ember.create(null);
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (ember$data$lib$system$store$$isNone(properties.id)) {
properties.id = this._generateId(modelName, properties);
}
// Coerce ID to a string
properties.id = ember$data$lib$system$coerce$id$$default(properties.id);
var internalModel = this.buildInternalModel(typeClass, properties.id);
var record = internalModel.getRecord();
// Move the record out of its initial `empty` state into
// the `loaded` state.
internalModel.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
internalModel.eachRelationship(function (key, descriptor) {
internalModel._relationships.get(key).setHasData(true);
});
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} modelName
@param {Object} properties from the new record
@return {String} if the adapter can generate one, an ID
*/
_generateId: function (modelName, properties) {
var adapter = this.adapterFor(modelName);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this, modelName, properties);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
var post = store.createRecord('post', {
title: "Rails is omakase"
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function (record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store. Only
non-dirty records can be unloaded.
Example
```javascript
store.find('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function (record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
You can optionally `preload` specific attributes and relationships that you know of
by passing them as the third argument to find.
For example, if your Ember route looks like `/posts/1/comments/2` and your API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without fetching the post you can pass in the post to the `find` call:
```javascript
store.find('comment', 2, {post: 1});
```
If you have access to the post model you can also pass the model itself:
```javascript
store.find('post', 1).then(function (myPostModel) {
store.find('comment', 2, {post: myPostModel});
});
```
This way, your adapter's `find` or `buildURL` method will be able to look up the
relationship on the record and construct the nested URL without having to first
fetch the post.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values. The promise will resolve into all records of this type
present in the store, even if the server only returns a subset of them.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find('person', { page: 1 });
```
By passing an object `{page: 1}` as an argument to the find method, it
delegates to the adapter's findQuery method. The adapter then makes
a call to the server, transforming the object `{page: 1}` as parameters
that are sent along, and will return a RecordArray when the promise
resolves.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
The call made to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?page=1"
Processing by Api::V1::PersonsController#index as HTML
Parameters: {"page"=>"1"}
```
If you do something like this:
```javascript
store.find('person', {ids: [1, 2, 3]});
```
The call to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
Processing by Api::V1::PersonsController#index as HTML
Parameters: {"ids"=>["1", "2", "3"]}
```
@method find
@param {String} modelName
@param {(Object|String|Integer|null)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
find: function (modelName, id, preload) {
if (arguments.length === 1) {
return this.findAll(modelName);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === "object") {
return this.findQuery(modelName, id);
}
return this.findById(modelName, ember$data$lib$system$coerce$id$$default(id), preload);
},
/**
This method returns a fresh record for a given type and id combination.
If a record is available for the given type/id combination, then
it will fetch this record from the store and call `reload()` on it.
That will fire a request to server and return a promise that will
resolve once the record has been reloaded.
If there's no record corresponding in the store it will simply call
`store.find`.
Example
```app/routes/post.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
return this.store.fetchById('post', params.post_id);
}
});
```
@method fetchById
@param {String} modelName
@param {(String|Integer)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
fetchById: function (modelName, id, preload) {
if (this.hasRecordForId(modelName, id)) {
return this.getById(modelName, id).reload();
} else {
return this.find(modelName, id, preload);
}
},
/**
This method returns a fresh collection from the server, regardless of if there is already records
in the store or not.
@method fetchAll
@param {String} modelName
@return {Promise} promise
*/
fetchAll: function (modelName) {
var typeClass = this.modelFor(modelName);
return this._fetchAll(typeClass, this.all(modelName));
},
/**
@method fetch
@param {String} modelName
@param {(String|Integer)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
@deprecated Use [fetchById](#method_fetchById) instead
*/
fetch: function (modelName, id, preload) {
return this.fetchById(modelName, id, preload);
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param {String} modelName
@param {(String|Integer)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
findById: function (modelName, id, preload) {
var internalModel = this._internalModelForId(modelName, id);
return this._findByInternalModel(internalModel, preload);
},
_findByInternalModel: function (internalModel, preload) {
var fetchedInternalModel;
if (preload) {
internalModel._preloadData(preload);
}
if (internalModel.isEmpty()) {
fetchedInternalModel = this.scheduleFetch(internalModel);
//TODO double check about reloading
} else if (internalModel.isLoading()) {
fetchedInternalModel = internalModel._loadingPromise;
}
return ember$data$lib$system$store$$promiseRecord(fetchedInternalModel || internalModel, "DS: Store#findByRecord " + internalModel.typeKey + " with id: " + ember$data$lib$system$store$$get(internalModel, "id"));
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} modelName
@param {Array} ids
@return {Promise} promise
*/
findByIds: function (modelName, ids) {
var store = this;
return ember$data$lib$system$promise$proxies$$promiseArray(Ember.RSVP.all(ember$data$lib$system$store$$map(ids, function (id) {
return store.findById(modelName, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + modelName + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {InternalModel} internalModel model
@return {Promise} promise
*/
fetchRecord: function (internalModel) {
var typeClass = internalModel.type;
var id = internalModel.id;
var adapter = this.adapterFor(typeClass.modelName);
var promise = ember$data$lib$system$store$finders$$_find(adapter, this, typeClass, id, internalModel);
return promise;
},
scheduleFetchMany: function (records) {
var internalModels = ember$data$lib$system$store$$map(records, function (record) {
return record._internalModel;
});
return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(internalModels, this.scheduleFetch, this));
},
scheduleFetch: function (internalModel) {
var typeClass = internalModel.type;
if (internalModel._loadingPromise) {
return internalModel._loadingPromise;
}
var resolver = Ember.RSVP.defer("Fetching " + typeClass + "with id: " + internalModel.id);
var recordResolverPair = {
record: internalModel,
resolver: resolver
};
var promise = resolver.promise;
internalModel.loadingData(promise);
if (!this._pendingFetch.get(typeClass)) {
this._pendingFetch.set(typeClass, [recordResolverPair]);
} else {
this._pendingFetch.get(typeClass).push(recordResolverPair);
}
Ember.run.scheduleOnce("afterRender", this, this.flushAllPendingFetches);
return promise;
},
flushAllPendingFetches: function () {
if (this.isDestroyed || this.isDestroying) {
return;
}
this._pendingFetch.forEach(this._flushPendingFetchForType, this);
this._pendingFetch = ember$data$lib$system$map$$Map.create();
},
_flushPendingFetchForType: function (recordResolverPairs, typeClass) {
var store = this;
var adapter = store.adapterFor(typeClass.modelName);
var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
var records = Ember.A(recordResolverPairs).mapBy("record");
function _fetchRecord(recordResolverPair) {
recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record));
}
function resolveFoundRecords(records) {
ember$data$lib$system$store$$forEach(records, function (record) {
var pair = Ember.A(recordResolverPairs).findBy("record", record);
if (pair) {
var resolver = pair.resolver;
resolver.resolve(record);
}
});
return records;
}
function makeMissingRecordsRejector(requestedRecords) {
return function rejectMissingRecords(resolvedRecords) {
resolvedRecords = Ember.A(resolvedRecords);
var missingRecords = requestedRecords.reject(function (record) {
return resolvedRecords.contains(record);
});
if (missingRecords.length) {
}
rejectRecords(missingRecords);
};
}
function makeRecordsRejector(records) {
return function (error) {
rejectRecords(records, error);
};
}
function rejectRecords(records, error) {
ember$data$lib$system$store$$forEach(records, function (record) {
var pair = Ember.A(recordResolverPairs).findBy("record", record);
if (pair) {
var resolver = pair.resolver;
resolver.reject(error);
}
});
}
if (recordResolverPairs.length === 1) {
_fetchRecord(recordResolverPairs[0]);
} else if (shouldCoalesce) {
// TODO: Improve records => snapshots => records => snapshots
//
// We want to provide records to all store methods and snapshots to all
// adapter methods. To make sure we're doing that we're providing an array
// of snapshots to adapter.groupRecordsForFindMany(), which in turn will
// return grouped snapshots instead of grouped records.
//
// But since the _findMany() finder is a store method we need to get the
// records from the grouped snapshots even though the _findMany() finder
// will once again convert the records to snapshots for adapter.findMany()
var snapshots = Ember.A(records).invoke("createSnapshot");
var groups = adapter.groupRecordsForFindMany(this, snapshots);
ember$data$lib$system$store$$forEach(groups, function (groupOfSnapshots) {
var groupOfRecords = Ember.A(groupOfSnapshots).mapBy("_internalModel");
var requestedRecords = Ember.A(groupOfRecords);
var ids = requestedRecords.mapBy("id");
if (ids.length > 1) {
ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords));
} else if (ids.length === 1) {
var pair = Ember.A(recordResolverPairs).findBy("record", groupOfRecords[0]);
_fetchRecord(pair);
} else {
}
});
} else {
ember$data$lib$system$store$$forEach(recordResolverPairs, _fetchRecord);
}
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store,
otherwise it will return `null`. A record is available if it has been fetched earlier, or
pushed manually into the store.
_Note: This is an synchronous method and does not return a promise._
```js
var post = store.getById('post', 1);
post.get('id'); // 1
```
@method getById
@param {String} modelName
@param {String|Integer} id
@return {DS.Model|null} record
*/
getById: function (modelName, id) {
if (this.hasRecordForId(modelName, id)) {
return this._internalModelForId(modelName, id).getRecord();
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} internalModel
@return {Promise} promise
*/
reloadRecord: function (internalModel) {
var modelName = internalModel.type.modelName;
var adapter = this.adapterFor(modelName);
var id = internalModel.id;
return this.scheduleFetch(internalModel);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {(String|DS.Model)} modelName
@param {(String|Integer)} inputId
@return {Boolean}
*/
hasRecordForId: function (modelName, inputId) {
var typeClass = this.modelFor(modelName);
var id = ember$data$lib$system$coerce$id$$default(inputId);
var internalModel = this.typeMapFor(typeClass).idToRecord[id];
return !!internalModel && internalModel.isLoaded();
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String} modelName
@param {(String|Integer)} id
@return {DS.Model} record
*/
recordForId: function (modelName, id) {
return this._internalModelForId(modelName, id).getRecord();
},
_internalModelForId: function (typeName, inputId) {
var typeClass = this.modelFor(typeName);
var id = ember$data$lib$system$coerce$id$$default(inputId);
var idToRecord = this.typeMapFor(typeClass).idToRecord;
var record = idToRecord[id];
if (!record || !idToRecord[id]) {
record = this.buildInternalModel(typeClass, id);
}
return record;
},
/**
@method findMany
@private
@param {Array} internalModels
@return {Promise} promise
*/
findMany: function (internalModels) {
var store = this;
return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(internalModels, function (internalModel) {
return store._findByInternalModel(internalModel);
}));
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {(Relationship)} relationship
@return {Promise} promise
*/
findHasMany: function (owner, link, relationship) {
var adapter = this.adapterFor(owner.type.modelName);
return ember$data$lib$system$store$finders$$_findHasMany(adapter, this, owner, link, relationship);
},
/**
@method findBelongsTo
@private
@param {DS.Model} owner
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function (owner, link, relationship) {
var adapter = this.adapterFor(owner.type.modelName);
return ember$data$lib$system$store$finders$$_findBelongsTo(adapter, this, owner, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String} modelName
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
findQuery: function (modelName, query) {
var typeClass = this.modelFor(modelName);
var array = this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query);
var adapter = this.adapterFor(modelName);
return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findQuery(adapter, this, typeClass, query, array));
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {String} modelName
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function (modelName) {
return this.fetchAll(modelName);
},
/**
@method _fetchAll
@private
@param {DS.Model} typeClass
@param {DS.RecordArray} array
@return {Promise} promise
*/
_fetchAll: function (typeClass, array) {
var adapter = this.adapterFor(typeClass.modelName);
var sinceToken = this.typeMapFor(typeClass).metadata.since;
ember$data$lib$system$store$$set(array, "isUpdating", true);
return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, typeClass, sinceToken));
},
/**
@method didUpdateAll
@param {DS.Model} typeClass
@private
*/
didUpdateAll: function (typeClass) {
var findAllCache = this.typeMapFor(typeClass).findAllCache;
ember$data$lib$system$store$$set(findAllCache, "isUpdating", false);
},
/**
This method returns a filtered array that contains all of the
known records for a given type in the store.
Note that because it's just a filter, the result will contain any
locally created records of the type, however, it will not make a
request to the backend to retrieve additional records. If you
would like to request all the records from the backend please use
[store.find](#method_find).
Also note that multiple calls to `all` for a given type will always
return the same `RecordArray`.
Example
```javascript
var localPosts = store.all('post');
```
@method all
@param {String} modelName
@return {DS.RecordArray}
*/
all: function (modelName) {
var typeClass = this.modelFor(modelName);
var typeMap = this.typeMapFor(typeClass);
var findAllCache = typeMap.findAllCache;
if (findAllCache) {
this.recordArrayManager.updateFilter(findAllCache, typeClass);
return findAllCache;
}
var array = this.recordArrayManager.createRecordArray(typeClass);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all records in the store.
Optionally you can pass a type which unload all records for a given type.
```javascript
store.unloadAll();
store.unloadAll('post');
```
@method unloadAll
@param {String=} modelName
*/
unloadAll: function (modelName) {
if (arguments.length === 0) {
var typeMaps = this.typeMaps;
var keys = Ember.keys(typeMaps);
var types = ember$data$lib$system$store$$map(keys, byType);
ember$data$lib$system$store$$forEach(types, this.unloadAll, this);
} else {
var typeClass = this.modelFor(modelName);
var typeMap = this.typeMapFor(typeClass);
var records = typeMap.records.slice();
var record;
for (var i = 0; i < records.length; i++) {
record = records[i];
record.unloadRecord();
record.destroy(); // maybe within unloadRecord
}
typeMap.findAllCache = null;
typeMap.metadata = Ember.create(null);
}
function byType(entry) {
return typeMaps[entry]["type"].modelName;
}
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The filter function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
Example
```javascript
store.filter('post', function(post) {
return post.get('unread');
});
```
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query, which is the equivalent of calling
[find](#method_find) with that same query, to fetch additional records
from the server. The results returned by the server could then appear
in the filter if they match the filter function.
The query itself is not used to filter records, it's only sent to your
server for you to be able to do server-side filtering. The filter
function will be applied on the returned results regardless.
Example
```javascript
store.filter('post', { unread: true }, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
var unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@param {String} modelName
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
*/
filter: function (modelName, query, filter) {
var promise;
var length = arguments.length;
var array;
var hasQuery = length === 3;
// allow an optional server query
if (hasQuery) {
promise = this.findQuery(modelName, query);
} else if (arguments.length === 2) {
filter = query;
}
modelName = this.modelFor(modelName);
if (hasQuery) {
array = this.recordArrayManager.createFilteredRecordArray(modelName, filter, query);
} else {
array = this.recordArrayManager.createFilteredRecordArray(modelName, filter);
}
promise = promise || ember$data$lib$system$store$$Promise.cast(array);
return ember$data$lib$system$promise$proxies$$promiseArray(promise.then(function () {
return array;
}, null, "DS: Store#filter of " + modelName));
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
Example
```javascript
store.recordIsLoaded('post', 1); // false
store.find('post', 1).then(function() {
store.recordIsLoaded('post', 1); // true
});
```
@method recordIsLoaded
@param {String} modelName
@param {string} id
@return {boolean}
*/
recordIsLoaded: function (modelName, id) {
return this.hasRecordForId(modelName, id);
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {String} modelName
@return {object}
*/
metadataFor: function (modelName) {
var typeClass = this.modelFor(modelName);
return this.typeMapFor(typeClass).metadata;
},
/**
This method sets the metadata for a specific type.
@method setMetadataFor
@param {String} modelName
@param {Object} metadata metadata to set
@return {object}
*/
setMetadataFor: function (modelName, metadata) {
var typeClass = this.modelFor(modelName);
Ember.merge(this.typeMapFor(typeClass).metadata, metadata);
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes the record will notify
the store to update its membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {InternalModel} internalModel
*/
dataWasUpdated: function (type, internalModel) {
this.recordArrayManager.recordDidChange(internalModel);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {InternalModel} internalModel
@param {Resolver} resolver
*/
scheduleSave: function (internalModel, resolver) {
var snapshot = internalModel.createSnapshot();
internalModel.flushChangedAttributes();
internalModel.adapterWillCommit();
this._pendingSave.push([snapshot, resolver]);
ember$data$lib$system$store$$once(this, "flushPendingSave");
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function () {
var pending = this._pendingSave.slice();
this._pendingSave = [];
ember$data$lib$system$store$$forEach(pending, function (tuple) {
var snapshot = tuple[0];
var resolver = tuple[1];
var record = snapshot._internalModel;
var adapter = this.adapterFor(record.type.modelName);
var operation;
if (ember$data$lib$system$store$$get(record, "currentState.stateName") === "root.deleted.saved") {
return resolver.resolve();
} else if (record.isNew()) {
operation = "createRecord";
} else if (record.isDeleted()) {
operation = "deleteRecord";
} else {
operation = "updateRecord";
}
resolver.resolve(ember$data$lib$system$store$$_commit(adapter, this, operation, snapshot));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {InternalModel} internalModel the in-flight internal model
@param {Object} data optional data (see above)
*/
didSaveRecord: function (internalModel, data) {
if (data) {
// normalize relationship IDs into records
this._backburner.schedule("normalizeRelationships", this, "_setupRelationships", internalModel, internalModel.type, data);
this.updateId(internalModel, data);
}
//We first make sure the primary data has been updated
//TODO try to move notification to the user to the end of the runloop
internalModel.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {InternalModel} internalModel
@param {Object} errors
*/
recordWasInvalid: function (internalModel, errors) {
internalModel.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {InternalModel} internalModel
*/
recordWasError: function (internalModel) {
internalModel.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {InternalModel} internalModel
@param {Object} data
*/
updateId: function (internalModel, data) {
var oldId = internalModel.id;
var id = ember$data$lib$system$coerce$id$$default(data.id);
this.typeMapFor(internalModel.type).idToRecord[id] = internalModel;
internalModel.setId(id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param {DS.Model} typeClass
@return {Object} typeMap
*/
typeMapFor: function (typeClass) {
var typeMaps = ember$data$lib$system$store$$get(this, "typeMaps");
var guid = Ember.guidFor(typeClass);
var typeMap = typeMaps[guid];
if (typeMap) {
return typeMap;
}
typeMap = {
idToRecord: Ember.create(null),
records: [],
metadata: Ember.create(null),
type: typeClass
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {(String|DS.Model)} type
@param {Object} data
*/
_load: function (type, data) {
var id = ember$data$lib$system$coerce$id$$default(data.id);
var internalModel = this._internalModelForId(type, id);
internalModel.setupData(data);
this.recordArrayManager.recordDidChange(internalModel);
return internalModel;
},
/*
In case someone defined a relationship to a mixin, for example:
```
var Comment = DS.Model.extend({
owner: belongsTo('commentable'. { polymorphic: true})
});
var Commentable = Ember.Mixin.create({
comments: hasMany('comment')
});
```
we want to look up a Commentable class which has all the necessary
relationship metadata. Thus, we look up the mixin and create a mock
DS.Model, so we can access the relationship CPs of the mixin (`comments`)
in this case
*/
_modelForMixin: function (modelName) {
var normalizedModelName = ember$data$lib$system$normalize$model$name$$default(modelName);
var registry = this.container._registry ? this.container._registry : this.container;
var mixin = registry.resolve("mixin:" + normalizedModelName);
if (mixin) {
//Cache the class as a model
registry.register("model:" + normalizedModelName, DS.Model.extend(mixin));
}
var factory = this.modelFactoryFor(normalizedModelName);
if (factory) {
factory.__isMixin = true;
factory.__mixin = mixin;
}
return factory;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String} modelName
@return {DS.Model}
*/
modelFor: function (modelName) {
var factory = this.modelFactoryFor(modelName);
if (!factory) {
//Support looking up mixins as base types for polymorphic relationships
factory = this._modelForMixin(modelName);
}
if (!factory) {
throw new Ember.Error("No model was found for '" + modelName + "'");
}
factory.modelName = factory.modelName || ember$data$lib$system$normalize$model$name$$default(modelName);
// deprecate typeKey
if (!("typeKey" in factory)) {
Ember.defineProperty(factory, "typeKey", {
enumerable: true,
configurable: false,
get: function () {
var typeKey = this.modelName;
if (typeKey) {
typeKey = Ember.String.camelize(this.modelName);
}
return typeKey;
},
set: function () {
}
});
}
return factory;
},
modelFactoryFor: function (modelName) {
var normalizedKey = ember$data$lib$system$normalize$model$name$$default(modelName);
return this.container.lookupFactory("model:" + normalizedKey);
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter, make sure
that you have converted the incoming data into this form. The
store's [normalize](#method_normalize) method is a convenience
helper for converting a json payload into the form Ember Data
expects.
```js
store.push('person', store.normalize('person', data));
```
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String} modelName
@param {Object} data
@return {DS.Model} the record that was created or
updated.
*/
push: function (modelName, data) {
var internalModel = this._pushInternalModel(modelName, data);
return internalModel.getRecord();
},
_pushInternalModel: function (modelName, data) {
var type = this.modelFor(modelName);
var filter = Ember.EnumerableUtils.filter;
// If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload
// contains unknown keys, log a warning.
if (Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS) {
}
// Actually load the record into the store.
var internalModel = this._load(modelName, data);
var store = this;
this._backburner.join(function () {
store._backburner.schedule("normalizeRelationships", store, "_setupRelationships", internalModel, type, data);
});
return internalModel;
},
_setupRelationships: function (record, type, data) {
// If the payload contains relationships that are specified as
// IDs, normalizeRelationships will convert them into DS.Model instances
// (possibly unloaded) before we push the payload into the
// store.
data = ember$data$lib$system$store$$normalizeRelationships(this, type, data);
// Now that the pushed record as well as any related records
// are in the store, create the data structures used to track
// relationships.
ember$data$lib$system$store$$setupRelationships(this, record, data);
},
/**
Push some raw data into the store.
This method can be used both to push in brand new
records, as well as to update existing records. You
can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer;
```
```js
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload(pushData);
```
By default, the data will be deserialized using a default
serializer (the application serializer if it exists).
Alternatively, `pushPayload` will accept a model type which
will determine which serializer will process the payload.
However, the serializer itself (processing this data via
`normalizePayload`) will not know which model it is
deserializing.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer;
```
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer;
```
```js
store.pushPayload('comment', pushData); // Will use the application serializer
store.pushPayload('post', pushData); // Will use the post serializer
```
@method pushPayload
@param {String} modelName Optionally, a model type used to determine which serializer will be used
@param {Object} inputPayload
*/
pushPayload: function (modelName, inputPayload) {
var serializer;
var payload;
if (!inputPayload) {
payload = modelName;
serializer = ember$data$lib$system$store$$defaultSerializer(this.container);
} else {
payload = inputPayload;
serializer = this.serializerFor(modelName);
}
var store = this;
this._adapterRun(function () {
serializer.pushPayload(store, payload);
});
},
/**
`normalize` converts a json payload into the normalized form that
[push](#method_push) expects.
Example
```js
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
store.push(modelName, store.normalize(modelName, data));
});
```
@method normalize
@param {String} modelName The name of the model type for this payload
@param {Object} payload
@return {Object} The normalized payload
*/
normalize: function (modelName, payload) {
var serializer = this.serializerFor(modelName);
var model = this.modelFor(modelName);
return serializer.normalize(model, payload);
},
/**
@method update
@param {String} modelName
@param {Object} data
@return {DS.Model} the record that was updated.
@deprecated Use [push](#method_push) instead
*/
update: function (modelName, data) {
return this.push(modelName, data);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String} modelName
@param {Array} datas
@return {Array}
*/
pushMany: function (modelName, datas) {
var length = datas.length;
var result = new Array(length);
for (var i = 0; i < length; i++) {
result[i] = this.push(modelName, datas[i]);
}
return result;
},
/**
@method metaForType
@param {String} modelName
@param {Object} metadata
@deprecated Use [setMetadataFor](#method_setMetadataFor) instead
*/
metaForType: function (modelName, metadata) {
this.setMetadataFor(modelName, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {DS.Model} type
@param {String} id
@param {Object} data
@return {InternalModel} internal model
*/
buildInternalModel: function (type, id, data) {
var typeMap = this.typeMapFor(type);
var idToRecord = typeMap.idToRecord;
// lookupFactory should really return an object that creates
// instances with the injections applied
var internalModel = new ember$data$lib$system$model$internal$model$$default(type, id, this, this.container, data);
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = internalModel;
}
typeMap.records.push(internalModel);
return internalModel;
},
//Called by the state machine to notify the store that the record is ready to be interacted with
recordWasLoaded: function (record) {
this.recordArrayManager.recordWasLoaded(record);
},
// ...............
// . DESTRUCTION .
// ...............
/**
@method dematerializeRecord
@private
@param {DS.Model} record
@deprecated Use [unloadRecord](#method_unloadRecord) instead
*/
dematerializeRecord: function (record) {
this._dematerializeRecord(record);
},
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method _dematerializeRecord
@private
@param {InternalModel} internalModel
*/
_dematerializeRecord: function (internalModel) {
var type = internalModel.type;
var typeMap = this.typeMapFor(type);
var id = internalModel.id;
internalModel.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = ember$data$lib$system$store$$indexOf(typeMap.records, internalModel);
typeMap.records.splice(loc, 1);
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns an instance of the adapter for a given type. For
example, `adapterFor('person')` will return an instance of
`App.PersonAdapter`.
If no `App.PersonAdapter` is found, this method will look
for an `App.ApplicationAdapter` (the default adapter for
your entire application).
If no `App.ApplicationAdapter` is found, it will return
the value of the `defaultAdapter`.
@method adapterFor
@private
@param {String} modelName
@return DS.Adapter
*/
adapterFor: function (modelOrClass) {
var modelName;
if (typeof modelOrClass !== "string") {
modelName = modelOrClass.modelName;
} else {
modelName = modelOrClass;
}
return this.lookupAdapter(modelName);
},
_adapterRun: function (fn) {
return this._backburner.run(fn);
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
if no `App.ApplicationSerializer` is found, it will attempt
to get the `defaultSerializer` from the `PersonAdapter`
(`adapterFor('person')`).
If a serializer cannot be found on the adapter, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} modelName the record to serialize
@return {DS.Serializer}
*/
serializerFor: function (modelOrClass) {
var modelName;
if (typeof modelOrClass !== "string") {
modelName = modelOrClass.modelName;
} else {
modelName = modelOrClass;
}
var fallbacks = ["application", this.adapterFor(modelName).get("defaultSerializer"), "-default"];
var serializer = this.lookupSerializer(modelName, fallbacks);
return serializer;
},
/**
Retrieve a particular instance from the
container cache. If not found, creates it and
placing it in the cache.
Enabled a store to manage local instances of
adapters and serializers.
@method retrieveManagedInstance
@private
@param {String} modelName the object modelName
@param {String} name the object name
@param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails
@return {Ember.Object}
*/
retrieveManagedInstance: function (type, modelName, fallbacks) {
var normalizedModelName = ember$data$lib$system$normalize$model$name$$default(modelName);
var instance = this._instanceCache.get(type, normalizedModelName, fallbacks);
ember$data$lib$system$store$$set(instance, "store", this);
return instance;
},
lookupAdapter: function (name) {
return this.retrieveManagedInstance("adapter", name, this.get("_adapterFallbacks"));
},
_adapterFallbacks: Ember.computed("adapter", function () {
var adapter = this.get("adapter");
return ["application", adapter, "-rest"];
}),
lookupSerializer: function (name, fallbacks) {
return this.retrieveManagedInstance("serializer", name, fallbacks);
},
willDestroy: function () {
this.recordArrayManager.destroy();
this.unloadAll();
for (var cacheKey in this._containerCache) {
this._containerCache[cacheKey].destroy();
delete this._containerCache[cacheKey];
}
delete this._containerCache;
}
});
function ember$data$lib$system$store$$normalizeRelationships(store, type, data, record) {
type.eachRelationship(function (key, relationship) {
var kind = relationship.kind;
var value = data[key];
if (kind === "belongsTo") {
ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, value);
} else if (kind === "hasMany") {
ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, value);
}
});
return data;
}
function ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, id) {
if (ember$data$lib$system$store$$isNone(id)) {
return;
}
//If record objects were given to push directly, uncommon, not sure whether we should actually support
if (id instanceof ember$data$lib$system$model$$default) {
data[key] = id._internalModel;
return;
}
var type;
if (typeof id === "number" || typeof id === "string") {
type = ember$data$lib$system$store$$typeFor(relationship, key, data);
data[key] = store._internalModelForId(type, id);
} else if (typeof id === "object") {
// hasMany polymorphic
data[key] = store._internalModelForId(id.type, id.id);
}
}
function ember$data$lib$system$store$$typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, ids) {
if (ember$data$lib$system$store$$isNone(ids)) {
return;
}
for (var i = 0, l = ids.length; i < l; i++) {
ember$data$lib$system$store$$deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// Delegation to the adapter and promise management
function ember$data$lib$system$store$$defaultSerializer(container) {
return container.lookup("serializer:application") || container.lookup("serializer:-default");
}
function ember$data$lib$system$store$$_commit(adapter, store, operation, snapshot) {
var record = snapshot._internalModel;
var modelName = snapshot.modelName;
var type = store.modelFor(modelName);
var promise = adapter[operation](store, type, snapshot);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName);
var label = "DS: Extract and notify about " + operation + " completion of " + record;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, record));
return promise.then(function (adapterPayload) {
var payload;
store._adapterRun(function () {
if (adapterPayload) {
payload = serializer.extract(store, type, adapterPayload, snapshot.id, operation);
}
store.didSaveRecord(record, payload);
});
return record;
}, function (reason) {
if (reason instanceof ember$data$lib$system$model$errors$invalid$$default) {
var errors = serializer.extractErrors(store, type, reason.errors, snapshot.id);
store.recordWasInvalid(record, errors);
reason = new ember$data$lib$system$model$errors$invalid$$default(errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, label);
}
function ember$data$lib$system$store$$setupRelationships(store, record, data) {
var typeClass = record.type;
typeClass.eachRelationship(function (key, descriptor) {
var kind = descriptor.kind;
var value = data[key];
var relationship;
if (data.links && data.links[key]) {
relationship = record._relationships.get(key);
relationship.updateLink(data.links[key]);
}
if (value !== undefined) {
if (kind === "belongsTo") {
relationship = record._relationships.get(key);
relationship.setCanonicalRecord(value);
} else if (kind === "hasMany") {
relationship = record._relationships.get(key);
relationship.updateRecordsFromAdapter(value);
}
}
});
}
var ember$data$lib$system$store$$default = ember$data$lib$system$store$$Store;
var ember$data$lib$instance$initializers$initialize$store$service$$default = ember$data$lib$instance$initializers$initialize$store$service$$initializeStoreService;
/**
Configures a registry for use with an Ember-Data
store.
@method initializeStore
@param {Ember.ApplicationInstance} applicationOrRegistry
*/
function ember$data$lib$instance$initializers$initialize$store$service$$initializeStoreService(applicationOrRegistry) {
var registry, container;
if (applicationOrRegistry.registry && applicationOrRegistry.container) {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
registry = applicationOrRegistry.registry;
container = applicationOrRegistry.container;
} else {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registy. This
// case allows ED to support Ember pre 1.12
registry = applicationOrRegistry;
if (registry.container) {
// Support Ember 1.10 - 1.11
container = registry.container();
} else {
// Support Ember 1.9
container = registry;
}
}
if (registry.has('store:application')) {
var customStoreFactory = container.lookupFactory('store:application');
registry.register('store:main', customStoreFactory);
} else {
registry.register('store:main', ember$data$lib$system$store$$default);
}
// Eagerly generate the store so defaultStore is populated.
var store = container.lookup('store:main');
registry.register('service:store', store, { instantiate: false });
}
var ember$data$lib$setup$container$$default = ember$data$lib$setup$container$$setupContainer;
function ember$data$lib$setup$container$$setupContainer(registry, application) {
// application is not a required argument. This ensures
// testing setups can setup a container without booting an
// entire ember application.
ember$data$lib$setup$container$$initializeInjects(registry, application);
ember$data$lib$instance$initializers$initialize$store$service$$default(registry);
}
function ember$data$lib$setup$container$$initializeInjects(registry, application) {
ember$data$lib$initializers$data$adapter$$default(registry, application);
ember$data$lib$initializers$transforms$$default(registry, application);
ember$data$lib$initializers$store$injections$$default(registry, application);
activemodel$adapter$lib$setup$container$$default(registry, application);
ember$data$lib$initializers$store$$default(registry, application);
}
var ember$data$lib$ember$initializer$$K = Ember.K;
/**
@module ember-data
*/
/*
This code initializes Ember-Data onto an Ember application.
If an Ember.js developer defines a subclass of DS.Store on their application,
as `App.ApplicationStore` (or via a module system that resolves to `store:application`)
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.ApplicationStore = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.ApplicationStore` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function (Application) {
Application.initializer({
name: 'ember-data',
initialize: ember$data$lib$setup$container$$initializeInjects
});
if (Application.instanceInitializer) {
Application.instanceInitializer({
name: 'ember-data',
initialize: ember$data$lib$instance$initializers$initialize$store$service$$default
});
} else {
Application.initializer({
name: 'ember-data-store-service',
after: 'ember-data',
initialize: ember$data$lib$instance$initializers$initialize$store$service$$default
});
}
// Deprecated initializers to satisfy old code that depended on them
Application.initializer({
name: 'store',
after: 'ember-data',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'activeModelAdapter',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'transforms',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'data-adapter',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'injectStore',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
});
Ember.Date = Ember.Date || {};
var origParse = Date.parse;
var numericKeys = [1, 4, 5, 6, 7, 10, 11];
/**
@method parse
@param {Date} date
@return {Number} timestamp
*/
Ember.Date.parse = function (date) {
var timestamp, struct;
var minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date)) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; k = numericKeys[i]; ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
} else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
ember$data$lib$system$model$$default.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function () {
var attributes = ['id'];
var relationships = { belongsTo: [], hasMany: [] };
var expensiveProperties = [];
this.eachAttribute(function (name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function (name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [{
name: 'Attributes',
properties: attributes,
expand: true
}, {
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
}, {
name: 'Has Many',
properties: relationships.hasMany,
expand: true
}, {
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
var ember$data$lib$system$debug$debug$info$$default = ember$data$lib$system$model$$default;
var ember$data$lib$system$debug$$default = ember$data$lib$system$debug$debug$adapter$$default;
var ember$data$lib$serializers$embedded$records$mixin$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$serializers$embedded$records$mixin$$camelize = Ember.String.camelize;
/**
## Using Embedded Records
`DS.EmbeddedRecordsMixin` supports serializing embedded records.
To set up embedded records, include the mixin when extending a serializer
then define and configure embedded (model) relationships.
Below is an example of a per-type serializer ('post' type).
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: { embedded: 'always' },
comments: { serialize: 'ids' }
}
});
```
Note that this use of `{ embedded: 'always' }` is unrelated to
the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of
defining a model while working with the ActiveModelSerializer. Nevertheless,
using `{ embedded: 'always' }` as an option to DS.attr is not a valid way to setup
embedded records.
The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
```js
{
serialize: 'records',
deserialize: 'records'
}
```
### Configuring Attrs
A resource's `attrs` option may be set to use `ids`, `records` or false for the
`serialize` and `deserialize` settings.
The `attrs` property can be set on the ApplicationSerializer or a per-type
serializer.
In the case where embedded JSON is expected while extracting a payload (reading)
the setting is `deserialize: 'records'`, there is no need to use `ids` when
extracting as that is the default behavior without this mixin if you are using
the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while
serializing `serialize: 'records'` is the setting to use. There is an option of
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
do not want the relationship sent at all, you can use `serialize: false`.
### EmbeddedRecordsMixin defaults
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
will behave in the following way:
BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
HasMany: `{ serialize: false, deserialize: 'ids' }`
### Model Relationships
Embedded records must have a model defined to be extracted and serialized. Note that
when defining any relationships on your model such as `belongsTo` and `hasMany`, you
should not both specify `async:true` and also indicate through the serializer's
`attrs` attribute that the related model should be embedded for deserialization.
If a model is declared embedded for deserialization (`embedded: 'always'`,
`deserialize: 'record'` or `deserialize: 'records'`), then do not use `async:true`.
To successfully extract and serialize embedded records the model relationships
must be setup correcty See the
[defining relationships](/guides/models/defining-models/#toc_defining-relationships)
section of the **Defining Models** guide page.
Records without an `id` property are not considered embedded records, model
instances must have an `id` property to be used with Ember Data.
### Example JSON payloads, Models and Serializers
**When customizing a serializer it is important to grok what the customizations
are. Please read the docs for the methods this mixin provides, in case you need
to modify it to fit your specific needs.**
For example review the docs for each method of this mixin:
* [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize)
* [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo)
* [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany)
@class EmbeddedRecordsMixin
@namespace DS
*/
var ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Normalize the record and recursively normalize/extract all the embedded records
while pushing them into the store as they are encountered
A payload with an attr configured for embedded records needs to be extracted:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
@method normalize
@param {DS.Model} typeClass
@param {Object} hash to be normalized
@param {String} prop the hash has been referenced by
@return {Object} the normalized hash
**/
normalize: function (typeClass, hash, prop) {
var normalizedHash = this._super(typeClass, hash, prop);
return ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(this, this.store, typeClass, normalizedHash);
},
keyForRelationship: function (key, typeClass, method) {
if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) {
return this.keyForAttribute(key, method);
} else {
return this._super(key, typeClass, method) || key;
}
},
/**
Serialize `belongsTo` relationship when it is configured as an embedded object.
This example of an author model belongs to a post model:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
author: DS.belongsTo('author')
});
Author = DS.Model.extend({
name: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded author
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"author": {
"id": "2"
"name": "dhh"
}
}
}
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function (snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var embeddedSnapshot = snapshot.belongsTo(attr);
var key;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind, 'serialize');
if (!embeddedSnapshot) {
json[key] = null;
} else {
json[key] = embeddedSnapshot.id;
}
} else if (includeRecords) {
key = this.keyForAttribute(attr, 'serialize');
if (!embeddedSnapshot) {
json[key] = null;
} else {
json[key] = embeddedSnapshot.record.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[key]);
}
}
},
/**
Serialize `hasMany` relationship when it is configured as embedded objects.
This example of a post model has many comments:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment')
});
Comment = DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded comments
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
The attrs options object can use more specific instruction for extracting and
serializing. When serializing, an option to embed `ids` or `records` can be set.
When extracting the only option is `records`.
So `{embedded: 'always'}` is shorthand for:
`{serialize: 'records', deserialize: 'records'}`
To embed the `ids` for a related object (using a hasMany relationship):
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {serialize: 'ids', deserialize: 'records'}
}
})
```
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": ["1", "2"]
}
}
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var key, hasMany;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind, 'serialize');
json[key] = snapshot.hasMany(attr, { ids: true });
} else if (includeRecords) {
key = this.keyForAttribute(attr, 'serialize');
hasMany = snapshot.hasMany(attr);
json[key] = Ember.A(hasMany).map(function (embeddedSnapshot) {
var embeddedJson = embeddedSnapshot.record.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
return embeddedJson;
}, this);
}
},
/**
When serializing an embedded record, modify the property (in the json payload)
that refers to the parent record (foreign key for relationship).
Serializing a `belongsTo` relationship removes the property that refers to the
parent record
Serializing a `hasMany` relationship does not remove the property that refers to
the parent record.
@method removeEmbeddedForeignKey
@param {DS.Snapshot} snapshot
@param {DS.Snapshot} embeddedSnapshot
@param {Object} relationship
@param {Object} json
*/
removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) {
if (relationship.kind === 'hasMany') {
return;
} else if (relationship.kind === 'belongsTo') {
var parentRecord = snapshot.type.inverseFor(relationship.key, this.store);
if (parentRecord) {
var name = parentRecord.name;
var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName);
var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize');
if (parentKey) {
delete json[parentKey];
}
}
}
},
// checks config for attrs option to embedded (always) - serialize and deserialize
hasEmbeddedAlwaysOption: function (attr) {
var option = this.attrsOption(attr);
return option && option.embedded === 'always';
},
// checks config for attrs option to serialize ids
hasSerializeRecordsOption: function (attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || option && option.serialize === 'records';
},
// checks config for attrs option to serialize records
hasSerializeIdsOption: function (attr) {
var option = this.attrsOption(attr);
return option && (option.serialize === 'ids' || option.serialize === 'id');
},
// checks config for attrs option to serialize records
noSerializeOptionSpecified: function (attr) {
var option = this.attrsOption(attr);
return !(option && (option.serialize || option.embedded));
},
// checks config for attrs option to deserialize records
// a defined option object for a resource is treated the same as
// `deserialize: 'records'`
hasDeserializeRecordsOption: function (attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || option && option.deserialize === 'records';
},
attrsOption: function (attr) {
var attrs = this.get('attrs');
return attrs && (attrs[ember$data$lib$serializers$embedded$records$mixin$$camelize(attr)] || attrs[attr]);
}
});
// chooses a relationship kind to branch which function is used to update payload
// does not change payload if attr is not embedded
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(serializer, store, typeClass, partial) {
typeClass.eachRelationship(function (key, relationship) {
if (serializer.hasDeserializeRecordsOption(key)) {
var embeddedTypeClass = store.modelFor(relationship.type);
if (relationship.kind === 'hasMany') {
if (relationship.options.polymorphic) {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasManyPolymorphic(store, key, partial);
} else {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedTypeClass, partial);
}
}
if (relationship.kind === 'belongsTo') {
if (relationship.options.polymorphic) {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsToPolymorphic(store, key, partial);
} else {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedTypeClass, partial);
}
}
}
});
return partial;
}
// handles embedding for `hasMany` relationship
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedTypeClass, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
var embeddedSerializer = store.serializerFor(embeddedTypeClass.modelName);
ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function (data) {
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
ids.push(embeddedRecord.id);
});
hash[key] = ids;
return hash;
}
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasManyPolymorphic(store, key, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function (data) {
var modelName = data.type;
var embeddedSerializer = store.serializerFor(modelName);
var embeddedTypeClass = store.modelFor(modelName);
// var primaryKey = embeddedSerializer.get('primaryKey');
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
ids.push({ id: embeddedRecord.id, type: modelName });
});
hash[key] = ids;
return hash;
}
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedTypeClass, hash) {
if (!hash[key]) {
return hash;
}
var embeddedSerializer = store.serializerFor(embeddedTypeClass.modelName);
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, hash[key], null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
hash[key] = embeddedRecord.id;
//TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records
return hash;
}
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsToPolymorphic(store, key, hash) {
if (!hash[key]) {
return hash;
}
var data = hash[key];
var modelName = data.type;
var embeddedSerializer = store.serializerFor(modelName);
var embeddedTypeClass = store.modelFor(modelName);
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
hash[key] = embeddedRecord.id;
hash[key + 'Type'] = modelName;
return hash;
}
var ember$data$lib$serializers$embedded$records$mixin$$default = ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin;
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
profile: DS.belongsTo('profile')
});
```
```app/models/profile.js
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the key name.
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo()
});
```
will lookup for a Post type.
@namespace
@method belongsTo
@for DS
@param {String} modelName (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function ember$data$lib$system$relationships$belongs$to$$belongsTo(modelName, options) {
var opts, userEnteredModelName;
if (typeof modelName === "object") {
opts = modelName;
userEnteredModelName = undefined;
} else {
opts = options;
userEnteredModelName = modelName;
}
if (typeof userEnteredModelName === "string") {
userEnteredModelName = ember$data$lib$system$normalize$model$name$$default(userEnteredModelName);
}
opts = opts || {};
var meta = {
type: userEnteredModelName,
isRelationship: true,
options: opts,
kind: "belongsTo",
key: null
};
return ember$data$lib$utils$computed$polyfill$$default({
get: function (key) {
return this._internalModel._relationships.get(key).getRecord();
},
set: function (key, value) {
if (value === undefined) {
value = null;
}
if (value && value.then) {
this._internalModel._relationships.get(key).setRecordPromise(value);
} else if (value) {
this._internalModel._relationships.get(key).setRecord(value._internalModel);
} else {
this._internalModel._relationships.get(key).setRecord(value);
}
return this._internalModel._relationships.get(key).getRecord();
}
}).meta(meta);
}
/*
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
*/
ember$data$lib$system$model$$default.reopen({
notifyBelongsToChanged: function (key) {
this.notifyPropertyChange(key);
}
});
var ember$data$lib$system$relationships$belongs$to$$default = ember$data$lib$system$relationships$belongs$to$$belongsTo;
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
tags: DS.hasMany('tag')
});
```
```app/models/tag.js
import DS from 'ember-data';
export default DS.Model.extend({
posts: DS.hasMany('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the singularized key name.
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
tags: DS.hasMany()
});
```
will lookup for a Tag type.
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
onePost: DS.belongsTo('post'),
twoPost: DS.belongsTo('post'),
redPost: DS.belongsTo('post'),
bluePost: DS.belongsTo('post')
});
```
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String} type (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function ember$data$lib$system$relationships$has$many$$hasMany(type, options) {
if (typeof type === "object") {
options = type;
type = undefined;
}
options = options || {};
if (typeof type === "string") {
type = ember$data$lib$system$normalize$model$name$$default(type);
}
// Metadata about relationships is stored on the meta of
// the relationship. This is used for introspection and
// serialization. Note that `key` is populated lazily
// the first time the CP is called.
var meta = {
type: type,
isRelationship: true,
options: options,
kind: "hasMany",
key: null
};
return ember$data$lib$utils$computed$polyfill$$default({
get: function (key) {
var relationship = this._internalModel._relationships.get(key);
return relationship.getRecords();
},
set: function (key, records) {
var relationship = this._internalModel._relationships.get(key);
relationship.clear();
relationship.addRecords(Ember.A(records).mapBy("_internalModel"));
return relationship.getRecords();
}
}).meta(meta);
}
ember$data$lib$system$model$$default.reopen({
notifyHasManyAdded: function (key) {
//We need to notifyPropertyChange in the adding case because we need to make sure
//we fetch the newly added record in case it is unloaded
//TODO(Igor): Consider whether we could do this only if the record state is unloaded
//Goes away once hasMany is double promisified
this.notifyPropertyChange(key);
}
});
var ember$data$lib$system$relationships$has$many$$default = ember$data$lib$system$relationships$has$many$$hasMany;
function ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta) {
var modelName;
modelName = meta.type || meta.key;
if (meta.kind === 'hasMany') {
modelName = ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(modelName));
}
return modelName;
}
function ember$data$lib$system$relationship$meta$$relationshipFromMeta(meta) {
return {
key: meta.key,
kind: meta.kind,
type: ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta),
options: meta.options,
parentType: meta.parentType,
isRelationship: true
};
}
var ember$data$lib$system$relationships$ext$$get = Ember.get;
var ember$data$lib$system$relationships$ext$$filter = Ember.ArrayPolyfills.filter;
var ember$data$lib$system$relationships$ext$$relationshipsDescriptor = Ember.computed(function () {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable = false;
}
var map = new ember$data$lib$system$map$$MapWithDefault({
defaultValue: function () {
return [];
}
});
// Loop through each computed property on the class
this.eachComputedProperty(function (name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
meta.key = name;
var relationshipsForType = map.get(ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta));
relationshipsForType.push({
name: name,
kind: meta.kind
});
}
});
return map;
}).readOnly();
var ember$data$lib$system$relationships$ext$$relatedTypesDescriptor = Ember.computed(function () {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable = false;
}
var modelName;
var types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
meta.key = name;
modelName = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta);
if (!types.contains(modelName)) {
types.push(modelName);
}
}
});
return types;
}).readOnly();
var ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor = Ember.computed(function () {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable = false;
}
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
meta.key = name;
var relationship = ember$data$lib$system$relationship$meta$$relationshipFromMeta(meta);
relationship.type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta);
map.set(name, relationship);
}
});
return map;
}).readOnly();
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
ember$data$lib$system$model$$default.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param {Object} proto
@param {String} key
@param {Ember.ComputedProperty} value
*/
didDefineProperty: function (proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
ember$data$lib$system$model$$default.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@param {store} store an instance of DS.Store
@return {DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function (name, store) {
var relationship = ember$data$lib$system$relationships$ext$$get(this, "relationshipsByName").get(name);
return relationship && store.modelFor(relationship.type);
},
inverseMap: Ember.computed(function () {
return Ember.create(null);
}),
/**
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('message')
});
```
```app/models/message.js
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('post')
});
```
App.Post.inverseFor('comments') -> {type: App.Message, name:'owner', kind:'belongsTo'}
App.Message.inverseFor('owner') -> {type: App.Post, name:'comments', kind:'hasMany'}
@method inverseFor
@static
@param {String} name the name of the relationship
@return {Object} the inverse relationship, or null
*/
inverseFor: function (name, store) {
var inverseMap = ember$data$lib$system$relationships$ext$$get(this, "inverseMap");
if (inverseMap[name]) {
return inverseMap[name];
} else {
var inverse = this._findInverseFor(name, store);
inverseMap[name] = inverse;
return inverse;
}
},
//Calculate the inverse, ignoring the cache
_findInverseFor: function (name, store) {
var inverseType = this.typeForRelationship(name, store);
if (!inverseType) {
return null;
}
var propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', {inverse: null})`
var options = propertyMeta.options;
if (options.inverse === null) {
return null;
}
var inverseName, inverseKind, inverse;
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, "relationshipsByName").get(inverseName);
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) {
return null;
}
var filteredRelationships = ember$data$lib$system$relationships$ext$$filter.call(possibleRelationships, function (possibleRelationship) {
var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
if (filteredRelationships.length === 1) {
possibleRelationships = filteredRelationships;
}
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, relationshipsSoFar) {
var possibleRelationships = relationshipsSoFar || [];
var relationshipMap = ember$data$lib$system$relationships$ext$$get(inverseType, "relationships");
if (!relationshipMap) {
return possibleRelationships;
}
var relationships = relationshipMap.get(type.modelName);
relationships = ember$data$lib$system$relationships$ext$$filter.call(relationships, function (relationship) {
var optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationships = Ember.get(Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: ember$data$lib$system$relationships$ext$$relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function () {
var names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: ember$data$lib$system$relationships$ext$$relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
```
```js
import Ember from 'ember';
import Blog from 'app/models/blog';
var fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function () {
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, "attribute");
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function (callback, binding) {
ember$data$lib$system$relationships$ext$$get(this, "relationshipsByName").forEach(function (relationship, name) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function (callback, binding) {
ember$data$lib$system$relationships$ext$$get(this, "relatedTypes").forEach(function (type) {
callback.call(binding, type);
});
},
determineRelationshipType: function (knownSide, store) {
var knownKey = knownSide.key;
var knownKind = knownSide.kind;
var inverse = this.inverseFor(knownKey, store);
var key, otherKind;
if (!inverse) {
return knownKind === "belongsTo" ? "oneToNone" : "manyToNone";
}
key = inverse.name;
otherKind = inverse.kind;
if (otherKind === "belongsTo") {
return knownKind === "belongsTo" ? "oneToOne" : "manyToOne";
} else {
return knownKind === "belongsTo" ? "oneToMany" : "manyToMany";
}
}
});
ember$data$lib$system$model$$default.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, descriptor);
```
- `name` the name of the current property in the iteration
- `descriptor` the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- **key** <span class="type">String</span> the name of this relationship on the Model
- **kind** <span class="type">String</span> "hasMany" or "belongsTo"
- **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
- **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship
- **type** <span class="type">DS.Model</span> the type of the related Model
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
var serializedHasManyName = name.toUpperCase() + '_IDS';
json[name.toUpperCase()] = record.get(name).mapBy('id');
}
});
return json;
}
});
```
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function (callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor: function (name) {
return ember$data$lib$system$relationships$ext$$get(this.constructor, "relationshipsByName").get(name);
},
inverseFor: function (key) {
return this.constructor.inverseFor(key, this.store);
}
});
/**
Ember Data
@module ember-data
@main ember-data
*/
if (Ember.VERSION.match(/^1\.[0-7]\./)) {
throw new Ember.Error("Ember Data requires at least Ember 1.8.0, but you have " + Ember.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data");
}
if (Ember.VERSION.match(/^1\.12\.0/)) {
throw new Ember.Error("Ember Data does not work with Ember 1.12.0. Please upgrade to Ember 1.12.1 or higher.");
}
// support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast
Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;ember$data$lib$core$$default.Store = ember$data$lib$system$store$$Store;
ember$data$lib$core$$default.PromiseArray = ember$data$lib$system$promise$proxies$$PromiseArray;
ember$data$lib$core$$default.PromiseObject = ember$data$lib$system$promise$proxies$$PromiseObject;
ember$data$lib$core$$default.PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseManyArray;
ember$data$lib$core$$default.Model = ember$data$lib$system$model$$default;
ember$data$lib$core$$default.RootState = ember$data$lib$system$model$states$$default;
ember$data$lib$core$$default.attr = ember$data$lib$system$model$attributes$$default;
ember$data$lib$core$$default.Errors = ember$data$lib$system$model$errors$$default;
ember$data$lib$core$$default.InternalModel = ember$data$lib$system$model$internal$model$$default;
ember$data$lib$core$$default.Snapshot = ember$data$lib$system$snapshot$$default;
ember$data$lib$core$$default.Adapter = ember$data$lib$system$adapter$$Adapter;
ember$data$lib$core$$default.InvalidError = ember$data$lib$system$model$errors$invalid$$default;
ember$data$lib$core$$default.Serializer = ember$data$lib$system$serializer$$default;
ember$data$lib$core$$default.DebugAdapter = ember$data$lib$system$debug$$default;
ember$data$lib$core$$default.RecordArray = ember$data$lib$system$record$arrays$record$array$$default;
ember$data$lib$core$$default.FilteredRecordArray = ember$data$lib$system$record$arrays$filtered$record$array$$default;
ember$data$lib$core$$default.AdapterPopulatedRecordArray = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default;
ember$data$lib$core$$default.ManyArray = ember$data$lib$system$many$array$$default;
ember$data$lib$core$$default.RecordArrayManager = ember$data$lib$system$record$array$manager$$default;
ember$data$lib$core$$default.RESTAdapter = ember$data$lib$adapters$rest$adapter$$default;
ember$data$lib$core$$default.BuildURLMixin = ember$data$lib$adapters$build$url$mixin$$default;
ember$data$lib$core$$default.RESTSerializer = ember$data$lib$serializers$rest$serializer$$default;
ember$data$lib$core$$default.JSONSerializer = ember$data$lib$serializers$json$serializer$$default;
ember$data$lib$core$$default.Transform = ember$data$lib$transforms$base$$default;
ember$data$lib$core$$default.DateTransform = ember$data$lib$transforms$date$$default;
ember$data$lib$core$$default.StringTransform = ember$data$lib$transforms$string$$default;
ember$data$lib$core$$default.NumberTransform = ember$data$lib$transforms$number$$default;
ember$data$lib$core$$default.BooleanTransform = ember$data$lib$transforms$boolean$$default;
ember$data$lib$core$$default.ActiveModelAdapter = activemodel$adapter$lib$system$active$model$adapter$$default;
ember$data$lib$core$$default.ActiveModelSerializer = activemodel$adapter$lib$system$active$model$serializer$$default;
ember$data$lib$core$$default.EmbeddedRecordsMixin = ember$data$lib$serializers$embedded$records$mixin$$default;
ember$data$lib$core$$default.belongsTo = ember$data$lib$system$relationships$belongs$to$$default;
ember$data$lib$core$$default.hasMany = ember$data$lib$system$relationships$has$many$$default;
ember$data$lib$core$$default.Relationship = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$core$$default.ContainerProxy = ember$data$lib$system$container$proxy$$default;
ember$data$lib$core$$default._setupContainer = ember$data$lib$setup$container$$default;
Ember.defineProperty(ember$data$lib$core$$default, "normalizeModelName", {
enumerable: true,
writable: false,
configurable: false,
value: ember$data$lib$system$normalize$model$name$$default
});
var ember$data$lib$main$$fixtureAdapterWasDeprecated = false;
if (Ember.platform.hasPropertyAccessors) {
Ember.defineProperty(ember$data$lib$core$$default, "FixtureAdapter", {
get: function () {
if (!ember$data$lib$main$$fixtureAdapterWasDeprecated) {
ember$data$lib$main$$fixtureAdapterWasDeprecated = true;
}
return ember$data$lib$adapters$fixture$adapter$$default;
}
});
} else {
ember$data$lib$core$$default.FixtureAdapter = ember$data$lib$adapters$fixture$adapter$$default;
}
Ember.lookup.DS = ember$data$lib$core$$default;
var ember$data$lib$main$$default = ember$data$lib$core$$default;
}).call(this);
|
.eslintrc.js | NotBlizzard/bluebird | module.exports = {
root: true,
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"plugin:react/recommended",
"prettier/@typescript-eslint",
],
rules: {
"@typescript-eslint/no-unused-vars": [
"error",
{
args: "none",
},
],
"@typescript-eslint/no-non-null-assertion": [0],
"@typescript-eslint/explicit-function-return-type": [
"error",
{ allowExpressions: true },
],
"dot-notation": [2],
},
};
|
ui-web/stories/DiceSelect.stories.js | JimBarrows/SavageWorldsVirtualTableTop | /**
* Created by JimBarrows on 2019-01-20.
*/
import {action} from '@storybook/addon-actions'
import {storiesOf} from '@storybook/react'
import React from 'react'
import DiceSelect from '../src/components/DiceSelect'
storiesOf('components/DiceSelect', module)
.addDecorator((story) => <div className="container" >{<form >{story()}</form >}</div >)
.add('Default', () => <DiceSelect id={'default'} onChange={action('default clicked')} />)
.add('Shows a d6 ', () => <DiceSelect id={'default'} onChange={action('default clicked')} value={'d6'} />)
|
node_modules/native-base/src/basic/Label.js | odapplications/WebView-with-Lower-Tab-Menu | import React, { Component } from 'react';
import { Text } from 'react-native';
import { connectStyle } from '@shoutem/theme';
import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames';
class Label extends Component {
render() {
return (
<Text ref={c => this._root = c} {...this.props} />
);
}
}
Label.propTypes = {
...Text.propTypes,
style: React.PropTypes.object,
};
const StyledLabel = connectStyle('NativeBase.Label', {}, mapPropsToStyleNames)(Label);
export {
StyledLabel as Label,
};
|
web/sites/default/files/js/js_YRP-Nv6QcQ9G1PtoNBtY3Coa5p5BvdsW5lO9p7eFoRo.js | BenjaminFeu/adimeo_project | /*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c;
}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ea.test(f)?this.mouseHooks:da.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==ia()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===ia()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ga:ha):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ha,isPropagationStopped:ha,isImmediatePropagationStopped:ha,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ga,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ga,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ga,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ja(this,a,b,c,d)},one:function(a,b,c,d){return ja(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ha),this.each(function(){n.event.remove(this,a,c,b)})}});var ka=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,la=/<script|<style|<link/i,ma=/checked\s*(?:[^=]|=\s*.checked.)/i,na=/^true\/(.*)/,oa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=wa[0].contentDocument,b.write(),b.close(),c=ya(a,b),wa.detach()),xa[a]=c),c}var Aa=/^margin/,Ba=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ca=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Ea=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");if(h.style){h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h);function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Ea.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Ea.removeChild(g)}n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Ea.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Ea.removeChild(g),h.removeChild(c),b}})}}();function Fa(a,b,c){var d,e,f,g,h=a.style;return c=c||Ca(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Ba.test(g)&&Aa.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0!==g?g+"":g}function Ga(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ha=/^(none|table(?!-c[ea]).+)/,Ia={position:"absolute",visibility:"hidden",display:"block"},Ja={letterSpacing:"0",fontWeight:"400"},Ka=["Webkit","O","Moz","ms"],La=d.createElement("div").style;function Ma(a){if(a in La)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ka.length;while(c--)if(a=Ka[c]+b,a in La)return a}function Na(a,b,c){var d=T.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Oa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Pa(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ca(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Fa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ba.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Oa(a,b,c||(g?"border":"content"),d,f)+"px"}function Qa(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=N.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=N.access(d,"olddisplay",za(d.nodeName)))):(e=V(d),"none"===c&&e||N.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Fa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=T.exec(c))&&e[1]&&(c=W(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Fa(a,b,d)),"normal"===e&&b in Ja&&(e=Ja[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Ha.test(n.css(a,"display"))&&0===a.offsetWidth?Da(a,Ia,function(){return Pa(a,b,d)}):Pa(a,b,d):void 0},set:function(a,c,d){var e,f=d&&Ca(a),g=d&&Oa(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=T.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Na(a,c,g)}}}),n.cssHooks.marginLeft=Ga(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Fa(a,"marginLeft"))||a.getBoundingClientRect().left-Da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),n.cssHooks.marginRight=Ga(l.reliableMarginRight,function(a,b){return b?Da(a,{display:"inline-block"},Fa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Aa.test(a)||(n.cssHooks[a+b].set=Na)}),n.fn.extend({css:function(a,b){return K(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ca(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Qa(this,!0)},hide:function(){return Qa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function Ra(a,b,c,d,e){return new Ra.prototype.init(a,b,c,d,e)}n.Tween=Ra,Ra.prototype={constructor:Ra,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ra.propHooks[this.prop];return a&&a.get?a.get(this):Ra.propHooks._default.get(this)},run:function(a){var b,c=Ra.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ra.propHooks._default.set(this),this}},Ra.prototype.init.prototype=Ra.prototype,Ra.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Ra.propHooks.scrollTop=Ra.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Ra.prototype.init,n.fx.step={};var Sa,Ta,Ua=/^(?:toggle|show|hide)$/,Va=/queueHooks$/;function Wa(){return a.setTimeout(function(){Sa=void 0}),Sa=n.now()}function Xa(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=U[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ya(a,b,c){for(var d,e=(_a.tweeners[b]||[]).concat(_a.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Za(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&V(a),q=N.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?N.get(a,"olddisplay")||za(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ua.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?za(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=N.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;N.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ya(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function $a(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function _a(a,b,c){var d,e,f=0,g=_a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sa||Wa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Sa||Wa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for($a(k,j.opts.specialEasing);g>f;f++)if(d=_a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Ya,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(_a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return W(c.elem,a,T.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],_a.tweeners[c]=_a.tweeners[c]||[],_a.tweeners[c].unshift(b)},prefilters:[Za],prefilter:function(a,b){b?_a.prefilters.unshift(a):_a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=_a(this,n.extend({},a),f);(e||N.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=N.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Va.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=N.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Xa(b,!0),a,d,e)}}),n.each({slideDown:Xa("show"),slideUp:Xa("hide"),slideToggle:Xa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Sa=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Sa=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ta||(Ta=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Ta),Ta=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var ab,bb=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return K(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ab:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),ab={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=bb[b]||n.find.attr;bb[b]=function(a,b,d){var e,f;return d||(f=bb[b],bb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,bb[b]=f),e}});var cb=/^(?:input|select|textarea|button)$/i,db=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return K(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),
void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!L(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b)}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=N.access(d,b);e||d.addEventListener(a,c,!0),N.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=N.access(d,b)-1;e?N.access(d,b,e):(d.removeEventListener(a,c,!0),N.remove(d,b))}}});var jb=a.location,kb=n.now(),lb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var mb=/#.*$/,nb=/([?&])_=[^&]*/,ob=/^(.*?):[ \t]*([^\r\n]*)$/gm,pb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qb=/^(?:GET|HEAD)$/,rb=/^\/\//,sb={},tb={},ub="*/".concat("*"),vb=d.createElement("a");vb.href=jb.href;function wb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function xb(a,b,c,d){var e={},f=a===tb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function yb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function zb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Ab(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:jb.href,type:"GET",isLocal:pb.test(jb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":ub,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?yb(yb(a,n.ajaxSettings),b):yb(n.ajaxSettings,a)},ajaxPrefilter:wb(sb),ajaxTransport:wb(tb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=ob.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>v)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),z(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||jb.href)+"").replace(mb,"").replace(rb,jb.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(G)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=vb.protocol+"//"+vb.host!=j.protocol+"//"+j.host}catch(y){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),xb(sb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0===n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!qb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(lb.test(f)?"&":"?")+m.data,delete m.data),m.cache===!1&&(m.url=nb.test(f)?f.replace(nb,"$1_="+kb++):f+(lb.test(f)?"&":"?")+"_="+kb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+ub+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(o,x,m)===!1||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=xb(tb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,z)}catch(y){if(!(2>v))throw y;z(-1,y)}}else z(-1,"No Transport");function z(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(u=zb(m,x,d)),u=Ab(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Bb=/%20/g,Cb=/\[\]$/,Db=/\r?\n/g,Eb=/^(?:submit|button|image|reset|file)$/i,Fb=/^(?:input|select|textarea|keygen)/i;function Gb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Cb.test(a)?d(a,e):Gb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Gb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Gb(c,a[c],b,e);return d.join("&").replace(Bb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Fb.test(this.nodeName)&&!Eb.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Db,"\r\n")}}):{name:b.name,value:c.replace(Db,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Hb={0:200,1223:204},Ib=n.ajaxSettings.xhr();l.cors=!!Ib&&"withCredentials"in Ib,l.ajax=Ib=!!Ib,n.ajaxTransport(function(b){var c,d;return l.cors||Ib&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Hb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Jb=[],Kb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Jb.pop()||n.expando+"_"+kb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Kb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Kb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Kb,"$1"+e):b.jsonp!==!1&&(b.url+=(lb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Jb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ca([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Lb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Lb)return Lb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Mb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Mb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ea})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return K(this,function(a,d,e){var f=Mb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ga(l.pixelPosition,function(a,c){return c?(c=Fa(a,b),Ba.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return K(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Nb=a.jQuery,Ob=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Ob),b&&a.jQuery===n&&(a.jQuery=Nb),n},b||(a.jQuery=a.$=n),n});
;
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this);
(function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,n){e.Backbone=t(e,n,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(n){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var n=t.Backbone;var s=Array.prototype.slice;e.VERSION="1.2.3";e.$=r;e.noConflict=function(){t.Backbone=n;return this};e.emulateHTTP=false;e.emulateJSON=false;var a=function(t,e,r){switch(t){case 1:return function(){return i[e](this[r])};case 2:return function(t){return i[e](this[r],t)};case 3:return function(t,n){return i[e](this[r],h(t,this),n)};case 4:return function(t,n,s){return i[e](this[r],h(t,this),n,s)};default:return function(){var t=s.call(arguments);t.unshift(this[r]);return i[e].apply(i,t)}}};var o=function(t,e,r){i.each(e,function(e,n){if(i[n])t.prototype[n]=a(e,n,r)})};var h=function(t,e){if(i.isFunction(t))return t;if(i.isObject(t)&&!e._isModel(t))return u(t);if(i.isString(t))return function(e){return e.get(t)};return t};var u=function(t){var e=i.matches(t);return function(t){return e(t.attributes)}};var l=e.Events={};var c=/\s+/;var f=function(t,e,r,n,s){var a=0,o;if(r&&typeof r==="object"){if(n!==void 0&&"context"in s&&s.context===void 0)s.context=n;for(o=i.keys(r);a<o.length;a++){e=f(t,e,o[a],r[o[a]],s)}}else if(r&&c.test(r)){for(o=r.split(c);a<o.length;a++){e=t(e,o[a],n,s)}}else{e=t(e,r,n,s)}return e};l.on=function(t,e,i){return d(this,t,e,i)};var d=function(t,e,i,r,n){t._events=f(v,t._events||{},e,i,{context:r,ctx:t,listening:n});if(n){var s=t._listeners||(t._listeners={});s[n.id]=n}return t};l.listenTo=function(t,e,r){if(!t)return this;var n=t._listenId||(t._listenId=i.uniqueId("l"));var s=this._listeningTo||(this._listeningTo={});var a=s[n];if(!a){var o=this._listenId||(this._listenId=i.uniqueId("l"));a=s[n]={obj:t,objId:n,id:o,listeningTo:s,count:0}}d(t,e,r,this,a);return this};var v=function(t,e,i,r){if(i){var n=t[e]||(t[e]=[]);var s=r.context,a=r.ctx,o=r.listening;if(o)o.count++;n.push({callback:i,context:s,ctx:s||a,listening:o})}return t};l.off=function(t,e,i){if(!this._events)return this;this._events=f(g,this._events,t,e,{context:i,listeners:this._listeners});return this};l.stopListening=function(t,e,r){var n=this._listeningTo;if(!n)return this;var s=t?[t._listenId]:i.keys(n);for(var a=0;a<s.length;a++){var o=n[s[a]];if(!o)break;o.obj.off(e,r,this)}if(i.isEmpty(n))this._listeningTo=void 0;return this};var g=function(t,e,r,n){if(!t)return;var s=0,a;var o=n.context,h=n.listeners;if(!e&&!r&&!o){var u=i.keys(h);for(;s<u.length;s++){a=h[u[s]];delete h[a.id];delete a.listeningTo[a.objId]}return}var l=e?[e]:i.keys(t);for(;s<l.length;s++){e=l[s];var c=t[e];if(!c)break;var f=[];for(var d=0;d<c.length;d++){var v=c[d];if(r&&r!==v.callback&&r!==v.callback._callback||o&&o!==v.context){f.push(v)}else{a=v.listening;if(a&&--a.count===0){delete h[a.id];delete a.listeningTo[a.objId]}}}if(f.length){t[e]=f}else{delete t[e]}}if(i.size(t))return t};l.once=function(t,e,r){var n=f(p,{},t,e,i.bind(this.off,this));return this.on(n,void 0,r)};l.listenToOnce=function(t,e,r){var n=f(p,{},e,r,i.bind(this.stopListening,this,t));return this.listenTo(t,n)};var p=function(t,e,r,n){if(r){var s=t[e]=i.once(function(){n(e,s);r.apply(this,arguments)});s._callback=r}return t};l.trigger=function(t){if(!this._events)return this;var e=Math.max(0,arguments.length-1);var i=Array(e);for(var r=0;r<e;r++)i[r]=arguments[r+1];f(m,this._events,t,void 0,i);return this};var m=function(t,e,i,r){if(t){var n=t[e];var s=t.all;if(n&&s)s=s.slice();if(n)_(n,r);if(s)_(s,[e].concat(r))}return t};var _=function(t,e){var i,r=-1,n=t.length,s=e[0],a=e[1],o=e[2];switch(e.length){case 0:while(++r<n)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<n)(i=t[r]).callback.call(i.ctx,s);return;case 2:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a);return;case 3:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a,o);return;default:while(++r<n)(i=t[r]).callback.apply(i.ctx,e);return}};l.bind=l.on;l.unbind=l.off;i.extend(e,l);var y=e.Model=function(t,e){var r=t||{};e||(e={});this.cid=i.uniqueId(this.cidPrefix);this.attributes={};if(e.collection)this.collection=e.collection;if(e.parse)r=this.parse(r,e)||{};r=i.defaults({},r,i.result(this,"defaults"));this.set(r,e);this.changed={};this.initialize.apply(this,arguments)};i.extend(y.prototype,l,{changed:null,validationError:null,idAttribute:"id",cidPrefix:"c",initialize:function(){},toJSON:function(t){return i.clone(this.attributes)},sync:function(){return e.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return i.escape(this.get(t))},has:function(t){return this.get(t)!=null},matches:function(t){return!!i.iteratee(t,this)(this.attributes)},set:function(t,e,r){if(t==null)return this;var n;if(typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r||(r={});if(!this._validate(n,r))return false;var s=r.unset;var a=r.silent;var o=[];var h=this._changing;this._changing=true;if(!h){this._previousAttributes=i.clone(this.attributes);this.changed={}}var u=this.attributes;var l=this.changed;var c=this._previousAttributes;for(var f in n){e=n[f];if(!i.isEqual(u[f],e))o.push(f);if(!i.isEqual(c[f],e)){l[f]=e}else{delete l[f]}s?delete u[f]:u[f]=e}this.id=this.get(this.idAttribute);if(!a){if(o.length)this._pending=r;for(var d=0;d<o.length;d++){this.trigger("change:"+o[d],this,u[o[d]],r)}}if(h)return this;if(!a){while(this._pending){r=this._pending;this._pending=false;this.trigger("change",this,r)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,i.extend({},e,{unset:true}))},clear:function(t){var e={};for(var r in this.attributes)e[r]=void 0;return this.set(e,i.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!i.isEmpty(this.changed);return i.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?i.clone(this.changed):false;var e=this._changing?this._previousAttributes:this.attributes;var r={};for(var n in t){var s=t[n];if(i.isEqual(e[n],s))continue;r[n]=s}return i.size(r)?r:false},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(t){t=i.extend({parse:true},t);var e=this;var r=t.success;t.success=function(i){var n=t.parse?e.parse(i,t):i;if(!e.set(n,t))return false;if(r)r.call(t.context,e,i,t);e.trigger("sync",e,i,t)};z(this,t);return this.sync("read",this,t)},save:function(t,e,r){var n;if(t==null||typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r=i.extend({validate:true,parse:true},r);var s=r.wait;if(n&&!s){if(!this.set(n,r))return false}else{if(!this._validate(n,r))return false}var a=this;var o=r.success;var h=this.attributes;r.success=function(t){a.attributes=h;var e=r.parse?a.parse(t,r):t;if(s)e=i.extend({},n,e);if(e&&!a.set(e,r))return false;if(o)o.call(r.context,a,t,r);a.trigger("sync",a,t,r)};z(this,r);if(n&&s)this.attributes=i.extend({},h,n);var u=this.isNew()?"create":r.patch?"patch":"update";if(u==="patch"&&!r.attrs)r.attrs=n;var l=this.sync(u,this,r);this.attributes=h;return l},destroy:function(t){t=t?i.clone(t):{};var e=this;var r=t.success;var n=t.wait;var s=function(){e.stopListening();e.trigger("destroy",e,e.collection,t)};t.success=function(i){if(n)s();if(r)r.call(t.context,e,i,t);if(!e.isNew())e.trigger("sync",e,i,t)};var a=false;if(this.isNew()){i.defer(t.success)}else{z(this,t);a=this.sync("delete",this,t)}if(!n)s();return a},url:function(){var t=i.result(this,"urlRoot")||i.result(this.collection,"url")||F();if(this.isNew())return t;var e=this.get(this.idAttribute);return t.replace(/[^\/]$/,"$&/")+encodeURIComponent(e)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(t){return this._validate({},i.defaults({validate:true},t))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=i.extend({},this.attributes,t);var r=this.validationError=this.validate(t,e)||null;if(!r)return true;this.trigger("invalid",this,r,i.extend(e,{validationError:r}));return false}});var b={keys:1,values:1,pairs:1,invert:1,pick:0,omit:0,chain:1,isEmpty:1};o(y,b,"attributes");var x=e.Collection=function(t,e){e||(e={});if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,i.extend({silent:true},e))};var w={add:true,remove:true,merge:true};var E={add:true,remove:false};var k=function(t,e,i){i=Math.min(Math.max(i,0),t.length);var r=Array(t.length-i);var n=e.length;for(var s=0;s<r.length;s++)r[s]=t[s+i];for(s=0;s<n;s++)t[s+i]=e[s];for(s=0;s<r.length;s++)t[s+n+i]=r[s]};i.extend(x.prototype,l,{model:y,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return e.sync.apply(this,arguments)},add:function(t,e){return this.set(t,i.extend({merge:false},e,E))},remove:function(t,e){e=i.extend({},e);var r=!i.isArray(t);t=r?[t]:i.clone(t);var n=this._removeModels(t,e);if(!e.silent&&n)this.trigger("update",this,e);return r?n[0]:n},set:function(t,e){if(t==null)return;e=i.defaults({},e,w);if(e.parse&&!this._isModel(t))t=this.parse(t,e);var r=!i.isArray(t);t=r?[t]:t.slice();var n=e.at;if(n!=null)n=+n;if(n<0)n+=this.length+1;var s=[];var a=[];var o=[];var h={};var u=e.add;var l=e.merge;var c=e.remove;var f=false;var d=this.comparator&&n==null&&e.sort!==false;var v=i.isString(this.comparator)?this.comparator:null;var g;for(var p=0;p<t.length;p++){g=t[p];var m=this.get(g);if(m){if(l&&g!==m){var _=this._isModel(g)?g.attributes:g;if(e.parse)_=m.parse(_,e);m.set(_,e);if(d&&!f)f=m.hasChanged(v)}if(!h[m.cid]){h[m.cid]=true;s.push(m)}t[p]=m}else if(u){g=t[p]=this._prepareModel(g,e);if(g){a.push(g);this._addReference(g,e);h[g.cid]=true;s.push(g)}}}if(c){for(p=0;p<this.length;p++){g=this.models[p];if(!h[g.cid])o.push(g)}if(o.length)this._removeModels(o,e)}var y=false;var b=!d&&u&&c;if(s.length&&b){y=this.length!=s.length||i.some(this.models,function(t,e){return t!==s[e]});this.models.length=0;k(this.models,s,0);this.length=this.models.length}else if(a.length){if(d)f=true;k(this.models,a,n==null?this.length:n);this.length=this.models.length}if(f)this.sort({silent:true});if(!e.silent){for(p=0;p<a.length;p++){if(n!=null)e.index=n+p;g=a[p];g.trigger("add",g,this,e)}if(f||y)this.trigger("sort",this,e);if(a.length||o.length)this.trigger("update",this,e)}return r?t[0]:t},reset:function(t,e){e=e?i.clone(e):{};for(var r=0;r<this.models.length;r++){this._removeReference(this.models[r],e)}e.previousModels=this.models;this._reset();t=this.add(t,i.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return t},push:function(t,e){return this.add(t,i.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);return this.remove(e,t)},unshift:function(t,e){return this.add(t,i.extend({at:0},e))},shift:function(t){var e=this.at(0);return this.remove(e,t)},slice:function(){return s.apply(this.models,arguments)},get:function(t){if(t==null)return void 0;var e=this.modelId(this._isModel(t)?t.attributes:t);return this._byId[t]||this._byId[e]||this._byId[t.cid]},at:function(t){if(t<0)t+=this.length;return this.models[t]},where:function(t,e){return this[e?"find":"filter"](t)},findWhere:function(t){return this.where(t,true)},sort:function(t){var e=this.comparator;if(!e)throw new Error("Cannot sort a set without a comparator");t||(t={});var r=e.length;if(i.isFunction(e))e=i.bind(e,this);if(r===1||i.isString(e)){this.models=this.sortBy(e)}else{this.models.sort(e)}if(!t.silent)this.trigger("sort",this,t);return this},pluck:function(t){return i.invoke(this.models,"get",t)},fetch:function(t){t=i.extend({parse:true},t);var e=t.success;var r=this;t.success=function(i){var n=t.reset?"reset":"set";r[n](i,t);if(e)e.call(t.context,r,i,t);r.trigger("sync",r,i,t)};z(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?i.clone(e):{};var r=e.wait;t=this._prepareModel(t,e);if(!t)return false;if(!r)this.add(t,e);var n=this;var s=e.success;e.success=function(t,e,i){if(r)n.add(t,i);if(s)s.call(i.context,t,e,i)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models,{model:this.model,comparator:this.comparator})},modelId:function(t){return t[this.model.prototype.idAttribute||"id"]},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(this._isModel(t)){if(!t.collection)t.collection=this;return t}e=e?i.clone(e):{};e.collection=this;var r=new this.model(t,e);if(!r.validationError)return r;this.trigger("invalid",this,r.validationError,e);return false},_removeModels:function(t,e){var i=[];for(var r=0;r<t.length;r++){var n=this.get(t[r]);if(!n)continue;var s=this.indexOf(n);this.models.splice(s,1);this.length--;if(!e.silent){e.index=s;n.trigger("remove",n,this,e)}i.push(n);this._removeReference(n,e)}return i.length?i:false},_isModel:function(t){return t instanceof y},_addReference:function(t,e){this._byId[t.cid]=t;var i=this.modelId(t.attributes);if(i!=null)this._byId[i]=t;t.on("all",this._onModelEvent,this)},_removeReference:function(t,e){delete this._byId[t.cid];var i=this.modelId(t.attributes);if(i!=null)delete this._byId[i];if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(t==="change"){var n=this.modelId(e.previousAttributes());var s=this.modelId(e.attributes);if(n!==s){if(n!=null)delete this._byId[n];if(s!=null)this._byId[s]=e}}this.trigger.apply(this,arguments)}});var S={forEach:3,each:3,map:3,collect:3,reduce:4,foldl:4,inject:4,reduceRight:4,foldr:4,find:3,detect:3,filter:3,select:3,reject:3,every:3,all:3,some:3,any:3,include:3,includes:3,contains:3,invoke:0,max:3,min:3,toArray:1,size:1,first:3,head:3,take:3,initial:3,rest:3,tail:3,drop:3,last:3,without:0,difference:0,indexOf:3,shuffle:1,lastIndexOf:3,isEmpty:1,chain:1,sample:3,partition:3,groupBy:3,countBy:3,sortBy:3,indexBy:3};o(x,S,"models");var I=e.View=function(t){this.cid=i.uniqueId("view");i.extend(this,i.pick(t,P));this._ensureElement();this.initialize.apply(this,arguments)};var T=/^(\S+)\s*(.*)$/;var P=["model","collection","el","id","attributes","className","tagName","events"];i.extend(I.prototype,l,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this._removeElement();this.stopListening();return this},_removeElement:function(){this.$el.remove()},setElement:function(t){this.undelegateEvents();this._setElement(t);this.delegateEvents();return this},_setElement:function(t){this.$el=t instanceof e.$?t:e.$(t);this.el=this.$el[0]},delegateEvents:function(t){t||(t=i.result(this,"events"));if(!t)return this;this.undelegateEvents();for(var e in t){var r=t[e];if(!i.isFunction(r))r=this[r];if(!r)continue;var n=e.match(T);this.delegate(n[1],n[2],i.bind(r,this))}return this},delegate:function(t,e,i){this.$el.on(t+".delegateEvents"+this.cid,e,i);return this},undelegateEvents:function(){if(this.$el)this.$el.off(".delegateEvents"+this.cid);return this},undelegate:function(t,e,i){this.$el.off(t+".delegateEvents"+this.cid,e,i);return this},_createElement:function(t){return document.createElement(t)},_ensureElement:function(){if(!this.el){var t=i.extend({},i.result(this,"attributes"));if(this.id)t.id=i.result(this,"id");if(this.className)t["class"]=i.result(this,"className");this.setElement(this._createElement(i.result(this,"tagName")));this._setAttributes(t)}else{this.setElement(i.result(this,"el"))}},_setAttributes:function(t){this.$el.attr(t)}});e.sync=function(t,r,n){var s=H[t];i.defaults(n||(n={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:s,dataType:"json"};if(!n.url){a.url=i.result(r,"url")||F()}if(n.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(n.attrs||r.toJSON(n))}if(n.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(n.emulateHTTP&&(s==="PUT"||s==="DELETE"||s==="PATCH")){a.type="POST";if(n.emulateJSON)a.data._method=s;var o=n.beforeSend;n.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",s);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!n.emulateJSON){a.processData=false}var h=n.error;n.error=function(t,e,i){n.textStatus=e;n.errorThrown=i;if(h)h.call(n.context,t,e,i)};var u=n.xhr=e.ajax(i.extend(a,n));r.trigger("request",r,u,n);return u};var H={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var A=/\((.*?)\)/g;var C=/(\(\?)?:\w+/g;var R=/\*\w+/g;var j=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,l,{initialize:function(){},route:function(t,r,n){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){n=r;r=""}if(!n)n=this[r];var s=this;e.history.route(t,function(i){var a=s._extractParameters(t,i);if(s.execute(n,a,r)!==false){s.trigger.apply(s,["route:"+r].concat(a));s.trigger("route",r,a);e.history.trigger("route",s,r,a)}});return this},execute:function(t,e,i){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(j,"\\$&").replace(A,"(?:$1)?").replace(C,function(t,e){return e?t:"([^/?]+)"}).replace(R,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var M=e.History=function(){this.handlers=[];this.checkUrl=i.bind(this.checkUrl,this);if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var N=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var U=/#.*$/;M.started=false;i.extend(M.prototype,l,{interval:50,atRoot:function(){var t=this.location.pathname.replace(/[^\/]$/,"$&/");return t===this.root&&!this.getSearch()},matchRoot:function(){var t=this.decodeFragment(this.location.pathname);var e=t.slice(0,this.root.length-1)+"/";return e===this.root},decodeFragment:function(t){return decodeURI(t.replace(/%25/g,"%2525"))},getSearch:function(){var t=this.location.href.replace(/#.*/,"").match(/\?.+/);return t?t[0]:""},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getPath:function(){var t=this.decodeFragment(this.location.pathname+this.getSearch()).slice(this.root.length-1);return t.charAt(0)==="/"?t.slice(1):t},getFragment:function(t){if(t==null){if(this._usePushState||!this._wantsHashChange){t=this.getPath()}else{t=this.getHash()}}return t.replace(N,"")},start:function(t){if(M.started)throw new Error("Backbone.history has already been started");M.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._hasHashChange="onhashchange"in window&&(document.documentMode===void 0||document.documentMode>7);this._useHashChange=this._wantsHashChange&&this._hasHashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.history&&this.history.pushState);this._usePushState=this._wantsPushState&&this._hasPushState;this.fragment=this.getFragment();this.root=("/"+this.root+"/").replace(O,"/");if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||"/";this.location.replace(e+"#"+this.getPath());return true}else if(this._hasPushState&&this.atRoot()){this.navigate(this.getHash(),{replace:true})}}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe");this.iframe.src="javascript:0";this.iframe.style.display="none";this.iframe.tabIndex=-1;var r=document.body;var n=r.insertBefore(this.iframe,r.firstChild).contentWindow;n.document.open();n.document.close();n.location.hash="#"+this.fragment}var s=window.addEventListener||function(t,e){return attachEvent("on"+t,e)};if(this._usePushState){s("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){s("hashchange",this.checkUrl,false)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}if(!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent("on"+t,e)};if(this._usePushState){t("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){t("hashchange",this.checkUrl,false)}if(this.iframe){document.body.removeChild(this.iframe);this.iframe=null}if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);M.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getHash(this.iframe.contentWindow)}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){if(!this.matchRoot())return false;t=this.fragment=this.getFragment(t);return i.some(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!M.started)return false;if(!e||e===true)e={trigger:!!e};t=this.getFragment(t||"");var i=this.root;if(t===""||t.charAt(0)==="?"){i=i.slice(0,-1)||"/"}var r=i+t;t=this.decodeFragment(t.replace(U,""));if(this.fragment===t)return;this.fragment=t;if(this._usePushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,r)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;if(!e.replace){n.document.open();n.document.close()}this._updateHash(n.location,t,e.replace)}}else{return this.location.assign(r)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new M;var q=function(t,e){var r=this;var n;if(t&&i.has(t,"constructor")){n=t.constructor}else{n=function(){return r.apply(this,arguments)}}i.extend(n,r,e);var s=function(){this.constructor=n};s.prototype=r.prototype;n.prototype=new s;if(t)i.extend(n.prototype,t);n.__super__=r.prototype;return n};y.extend=x.extend=$.extend=I.extend=M.extend=q;var F=function(){throw new Error('A "url" property or function must be specified')};var z=function(t,e){var i=e.error;e.error=function(r){if(i)i.call(e.context,t,r,e);t.trigger("error",t,r,e)}};return e});
/*!
* jQuery Once v2.1.1 - http://github.com/robloach/jquery-once
* @license MIT, GPL-2.0
* http://opensource.org/licenses/MIT
* http://opensource.org/licenses/GPL-2.0
*/
(function(e){"use strict";if(typeof exports==="object"){e(require("jquery"))}else if(typeof define==="function"&&define.amd){define(["jquery"],e)}else{e(jQuery)}})(function(e){"use strict";var n=function(e){e=e||"once";if(typeof e!=="string"){throw new Error("The jQuery Once id parameter must be a string")}return e};e.fn.once=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)!==true}).data(r,true)};e.fn.removeOnce=function(e){return this.findOnce(e).removeData("jquery-once-"+n(e))};e.fn.findOnce=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)===true})}});
/**
* @file
* Parse inline JSON and initialize the drupalSettings global object.
*/
(function () {
'use strict';
// Use direct child elements to harden against XSS exploits when CSP is on.
var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');
/**
* Variable generated by Drupal with all the configuration created from PHP.
*
* @global
*
* @type {object}
*/
window.drupalSettings = {};
if (settingsElement !== null) {
window.drupalSettings = JSON.parse(settingsElement.textContent);
}
})();
;
/**
* @file
* Defines the Drupal JavaScript API.
*/
/**
* A jQuery object, typically the return value from a `$(selector)` call.
*
* Holds an HTMLElement or a collection of HTMLElements.
*
* @typedef {object} jQuery
*
* @prop {number} length=0
* Number of elements contained in the jQuery object.
*/
/**
* Variable generated by Drupal that holds all translated strings from PHP.
*
* Content of this variable is automatically created by Drupal when using the
* Interface Translation module. It holds the translation of strings used on
* the page.
*
* This variable is used to pass data from the backend to the frontend. Data
* contained in `drupalSettings` is used during behavior initialization.
*
* @global
*
* @var {object} drupalTranslations
*/
/**
* Global Drupal object.
*
* All Drupal JavaScript APIs are contained in this namespace.
*
* @global
*
* @namespace
*/
window.Drupal = {behaviors: {}, locale: {}};
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it in an anonymous closure.
(function (Drupal, drupalSettings, drupalTranslations) {
'use strict';
/**
* Helper to rethrow errors asynchronously.
*
* This way Errors bubbles up outside of the original callstack, making it
* easier to debug errors in the browser.
*
* @param {Error|string} error
* The error to be thrown.
*/
Drupal.throwError = function (error) {
setTimeout(function () { throw error; }, 0);
};
/**
* Custom error thrown after attach/detach if one or more behaviors failed.
* Initializes the JavaScript behaviors for page loads and Ajax requests.
*
* @callback Drupal~behaviorAttach
*
* @param {HTMLDocument|HTMLElement} context
* An element to detach behaviors from.
* @param {?object} settings
* An object containing settings for the current context. It is rarely used.
*
* @see Drupal.attachBehaviors
*/
/**
* Reverts and cleans up JavaScript behavior initialization.
*
* @callback Drupal~behaviorDetach
*
* @param {HTMLDocument|HTMLElement} context
* An element to attach behaviors to.
* @param {object} settings
* An object containing settings for the current context.
* @param {string} trigger
* One of `'unload'`, `'move'`, or `'serialize'`.
*
* @see Drupal.detachBehaviors
*/
/**
* @typedef {object} Drupal~behavior
*
* @prop {Drupal~behaviorAttach} attach
* Function run on page load and after an Ajax call.
* @prop {Drupal~behaviorDetach} detach
* Function run when content is serialized or removed from the page.
*/
/**
* Holds all initialization methods.
*
* @namespace Drupal.behaviors
*
* @type {Object.<string, Drupal~behavior>}
*/
/**
* Defines a behavior to be run during attach and detach phases.
*
* Attaches all registered behaviors to a page element.
*
* Behaviors are event-triggered actions that attach to page elements,
* enhancing default non-JavaScript UIs. Behaviors are registered in the
* {@link Drupal.behaviors} object using the method 'attach' and optionally
* also 'detach'.
*
* {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event
* and therefore runs on initial page load. Developers implementing Ajax in
* their solutions should also call this function after new page content has
* been loaded, feeding in an element to be processed, in order to attach all
* behaviors to the new content.
*
* Behaviors should use `var elements =
* $(context).find(selector).once('behavior-name');` to ensure the behavior is
* attached only once to a given element. (Doing so enables the reprocessing
* of given elements, which may be needed on occasion despite the ability to
* limit behavior attachment to a particular element.)
*
* @example
* Drupal.behaviors.behaviorName = {
* attach: function (context, settings) {
* // ...
* },
* detach: function (context, settings, trigger) {
* // ...
* }
* };
*
* @param {HTMLDocument|HTMLElement} [context=document]
* An element to attach behaviors to.
* @param {object} [settings=drupalSettings]
* An object containing settings for the current context. If none is given,
* the global {@link drupalSettings} object is used.
*
* @see Drupal~behaviorAttach
* @see Drupal.detachBehaviors
*
* @throws {Drupal~DrupalBehaviorError}
*/
Drupal.attachBehaviors = function (context, settings) {
context = context || document;
settings = settings || drupalSettings;
var behaviors = Drupal.behaviors;
// Execute all of them.
for (var i in behaviors) {
if (behaviors.hasOwnProperty(i) && typeof behaviors[i].attach === 'function') {
// Don't stop the execution of behaviors in case of an error.
try {
behaviors[i].attach(context, settings);
}
catch (e) {
Drupal.throwError(e);
}
}
}
};
/**
* Detaches registered behaviors from a page element.
*
* Developers implementing Ajax in their solutions should call this function
* before page content is about to be removed, feeding in an element to be
* processed, in order to allow special behaviors to detach from the content.
*
* Such implementations should use `.findOnce()` and `.removeOnce()` to find
* elements with their corresponding `Drupal.behaviors.behaviorName.attach`
* implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior
* is detached only from previously processed elements.
*
* @param {HTMLDocument|HTMLElement} [context=document]
* An element to detach behaviors from.
* @param {object} [settings=drupalSettings]
* An object containing settings for the current context. If none given,
* the global {@link drupalSettings} object is used.
* @param {string} [trigger='unload']
* A string containing what's causing the behaviors to be detached. The
* possible triggers are:
* - `'unload'`: The context element is being removed from the DOM.
* - `'move'`: The element is about to be moved within the DOM (for example,
* during a tabledrag row swap). After the move is completed,
* {@link Drupal.attachBehaviors} is called, so that the behavior can undo
* whatever it did in response to the move. Many behaviors won't need to
* do anything simply in response to the element being moved, but because
* IFRAME elements reload their "src" when being moved within the DOM,
* behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
* take some action.
* - `'serialize'`: When an Ajax form is submitted, this is called with the
* form as the context. This provides every behavior within the form an
* opportunity to ensure that the field elements have correct content
* in them before the form is serialized. The canonical use-case is so
* that WYSIWYG editors can update the hidden textarea to which they are
* bound.
*
* @throws {Drupal~DrupalBehaviorError}
*
* @see Drupal~behaviorDetach
* @see Drupal.attachBehaviors
*/
Drupal.detachBehaviors = function (context, settings, trigger) {
context = context || document;
settings = settings || drupalSettings;
trigger = trigger || 'unload';
var behaviors = Drupal.behaviors;
// Execute all of them.
for (var i in behaviors) {
if (behaviors.hasOwnProperty(i) && typeof behaviors[i].detach === 'function') {
// Don't stop the execution of behaviors in case of an error.
try {
behaviors[i].detach(context, settings, trigger);
}
catch (e) {
Drupal.throwError(e);
}
}
}
};
/**
* Encodes special characters in a plain-text string for display as HTML.
*
* @param {string} str
* The string to be encoded.
*
* @return {string}
* The encoded string.
*
* @ingroup sanitization
*/
Drupal.checkPlain = function (str) {
str = str.toString()
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
return str;
};
/**
* Replaces placeholders with sanitized values in a string.
*
* @param {string} str
* A string with placeholders.
* @param {object} args
* An object of replacements pairs to make. Incidences of any key in this
* array are replaced with the corresponding value. Based on the first
* character of the key, the value is escaped and/or themed:
* - `'!variable'`: inserted as is.
* - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
* - `'%variable'`: escape text and theme as a placeholder for user-
* submitted content ({@link Drupal.checkPlain} +
* `{@link Drupal.theme}('placeholder')`).
*
* @return {string}
* The formatted string.
*
* @see Drupal.t
*/
Drupal.formatString = function (str, args) {
// Keep args intact.
var processedArgs = {};
// Transform arguments before inserting them.
for (var key in args) {
if (args.hasOwnProperty(key)) {
switch (key.charAt(0)) {
// Escaped only.
case '@':
processedArgs[key] = Drupal.checkPlain(args[key]);
break;
// Pass-through.
case '!':
processedArgs[key] = args[key];
break;
// Escaped and placeholder.
default:
processedArgs[key] = Drupal.theme('placeholder', args[key]);
break;
}
}
}
return Drupal.stringReplace(str, processedArgs, null);
};
/**
* Replaces substring.
*
* The longest keys will be tried first. Once a substring has been replaced,
* its new value will not be searched again.
*
* @param {string} str
* A string with placeholders.
* @param {object} args
* Key-value pairs.
* @param {Array|null} keys
* Array of keys from `args`. Internal use only.
*
* @return {string}
* The replaced string.
*/
Drupal.stringReplace = function (str, args, keys) {
if (str.length === 0) {
return str;
}
// If the array of keys is not passed then collect the keys from the args.
if (!Array.isArray(keys)) {
keys = [];
for (var k in args) {
if (args.hasOwnProperty(k)) {
keys.push(k);
}
}
// Order the keys by the character length. The shortest one is the first.
keys.sort(function (a, b) { return a.length - b.length; });
}
if (keys.length === 0) {
return str;
}
// Take next longest one from the end.
var key = keys.pop();
var fragments = str.split(key);
if (keys.length) {
for (var i = 0; i < fragments.length; i++) {
// Process each fragment with a copy of remaining keys.
fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
}
}
return fragments.join(args[key]);
};
/**
* Translates strings to the page language, or a given language.
*
* See the documentation of the server-side t() function for further details.
*
* @param {string} str
* A string containing the English text to translate.
* @param {Object.<string, string>} [args]
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See {@link Drupal.formatString}.
* @param {object} [options]
* Additional options for translation.
* @param {string} [options.context='']
* The context the source string belongs to.
*
* @return {string}
* The formatted string.
* The translated string.
*/
Drupal.t = function (str, args, options) {
options = options || {};
options.context = options.context || '';
// Fetch the localized version of the string.
if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
str = drupalTranslations.strings[options.context][str];
}
if (args) {
str = Drupal.formatString(str, args);
}
return str;
};
/**
* Returns the URL to a Drupal page.
*
* @param {string} path
* Drupal path to transform to URL.
*
* @return {string}
* The full URL.
*/
Drupal.url = function (path) {
return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
};
/**
* Returns the passed in URL as an absolute URL.
*
* @param {string} url
* The URL string to be normalized to an absolute URL.
*
* @return {string}
* The normalized, absolute URL.
*
* @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
* @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
* @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
*/
Drupal.url.toAbsolute = function (url) {
var urlParsingNode = document.createElement('a');
// Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
// strings may throw an exception.
try {
url = decodeURIComponent(url);
}
catch (e) {
// Empty.
}
urlParsingNode.setAttribute('href', url);
// IE <= 7 normalizes the URL when assigned to the anchor node similar to
// the other browsers.
return urlParsingNode.cloneNode(false).href;
};
/**
* Returns true if the URL is within Drupal's base path.
*
* @param {string} url
* The URL string to be tested.
*
* @return {bool}
* `true` if local.
*
* @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
*/
Drupal.url.isLocal = function (url) {
// Always use browser-derived absolute URLs in the comparison, to avoid
// attempts to break out of the base path using directory traversal.
var absoluteUrl = Drupal.url.toAbsolute(url);
var protocol = location.protocol;
// Consider URLs that match this site's base URL but use HTTPS instead of HTTP
// as local as well.
if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
protocol = 'https:';
}
var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1);
// Decoding non-UTF-8 strings may throw an exception.
try {
absoluteUrl = decodeURIComponent(absoluteUrl);
}
catch (e) {
// Empty.
}
try {
baseUrl = decodeURIComponent(baseUrl);
}
catch (e) {
// Empty.
}
// The given URL matches the site's base URL, or has a path under the site's
// base URL.
return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
};
/**
* Formats a string containing a count of items.
*
* This function ensures that the string is pluralized correctly. Since
* {@link Drupal.t} is called by this function, make sure not to pass
* already-localized strings to it.
*
* See the documentation of the server-side
* \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
* function for more details.
*
* @param {number} count
* The item count to display.
* @param {string} singular
* The string for the singular case. Please make sure it is clear this is
* singular, to ease translation (e.g. use "1 new comment" instead of "1
* new"). Do not use @count in the singular string.
* @param {string} plural
* The string for the plural case. Please make sure it is clear this is
* plural, to ease translation. Use @count in place of the item count, as in
* "@count new comments".
* @param {object} [args]
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See {@link Drupal.formatString}.
* Note that you do not need to include @count in this array.
* This replacement is done automatically for the plural case.
* @param {object} [options]
* The options to pass to the {@link Drupal.t} function.
*
* @return {string}
* A translated string.
*/
Drupal.formatPlural = function (count, singular, plural, args, options) {
args = args || {};
args['@count'] = count;
var pluralDelimiter = drupalSettings.pluralDelimiter;
var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
var index = 0;
// Determine the index of the plural form.
if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula['default'];
}
else if (args['@count'] !== 1) {
index = 1;
}
return translations[index];
};
/**
* Encodes a Drupal path for use in a URL.
*
* For aesthetic reasons slashes are not escaped.
*
* @param {string} item
* Unencoded path.
*
* @return {string}
* The encoded path.
*/
Drupal.encodePath = function (item) {
return window.encodeURIComponent(item).replace(/%2F/g, '/');
};
/**
* Generates the themed representation of a Drupal object.
*
* All requests for themed output must go through this function. It examines
* the request and routes it to the appropriate theme function. If the current
* theme does not provide an override function, the generic theme function is
* called.
*
* @example
* <caption>To retrieve the HTML for text that should be emphasized and
* displayed as a placeholder inside a sentence.</caption>
* Drupal.theme('placeholder', text);
*
* @namespace
*
* @param {function} func
* The name of the theme function to call.
* @param {...args}
* Additional arguments to pass along to the theme function.
*
* @return {string|object|HTMLElement|jQuery}
* Any data the theme function returns. This could be a plain HTML string,
* but also a complex object.
*/
Drupal.theme = function (func) {
var args = Array.prototype.slice.apply(arguments, [1]);
if (func in Drupal.theme) {
return Drupal.theme[func].apply(this, args);
}
};
/**
* Formats text for emphasized display in a placeholder inside a sentence.
*
* @param {string} str
* The text to format (plain-text).
*
* @return {string}
* The formatted text (html).
*/
Drupal.theme.placeholder = function (str) {
return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
};
})(Drupal, window.drupalSettings, window.drupalTranslations);
;
// Allow other JavaScript libraries to use $.
if (window.jQuery) {
jQuery.noConflict();
}
// Class indicating that JS is enabled; used for styling purpose.
document.documentElement.className += ' js';
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it in an anonymous closure.
(function (domready, Drupal, drupalSettings) {
'use strict';
// Attach all behaviors.
domready(function () { Drupal.attachBehaviors(document, drupalSettings); });
})(domready, Drupal, window.drupalSettings);
;
/*!
* jQuery UI Core 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,r){var i,s,o,u=t.nodeName.toLowerCase();return"area"===u?(i=t.parentNode,s=i.name,!t.href||!s||i.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap='#"+s+"']")[0],!!o&&n(o))):(/^(input|select|textarea|button|object)$/.test(u)?!t.disabled:"a"===u?t.href||r:r)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return e.css(this,"visibility")==="hidden"}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var n=this.css("position"),r=n==="absolute",i=t?/(auto|scroll|hidden)/:/(auto|scroll)/,s=this.parents().filter(function(){var t=e(this);return r&&t.css("position")==="static"?!1:i.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return n==="fixed"||!s.length?e(this[0].ownerDocument||document):s},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(n){return t(n,!isNaN(e.attr(n,"tabindex")))},tabbable:function(n){var r=e.attr(n,"tabindex"),i=isNaN(r);return(i||r>=0)&&t(n,!i)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,n){function o(t,n,i,s){return e.each(r,function(){n-=parseFloat(e.css(t,"padding"+this))||0,i&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var r=n==="Width"?["Left","Right"]:["Top","Bottom"],i=n.toLowerCase(),s={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(t){return t===undefined?s["inner"+n].call(this):this.each(function(){e(this).css(i,o(this,t)+"px")})},e.fn["outer"+n]=function(t,r){return typeof t!="number"?s["outer"+n].call(this,t):this.each(function(){e(this).css(i,o(this,t,!0,r)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(n,r){return typeof n=="number"?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(t!==undefined)return this.css("zIndex",t);if(this.length){var n=e(this[0]),r,i;while(n.length&&n[0]!==document){r=n.css("position");if(r==="absolute"||r==="relative"||r==="fixed"){i=parseInt(n.css("zIndex"),10);if(!isNaN(i)&&i!==0)return i}n=n.parent()}}return 0}}),e.ui.plugin={add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n,r){var i,s=e.plugins[t];if(!s)return;if(!r&&(!e.element[0].parentNode||e.element[0].parentNode.nodeType===11))return;for(i=0;i<s.length;i++)e.options[s[i][0]]&&s[i][1].apply(e.element,n)}}});;
/*!
* jQuery UI Widget 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){var t=0,n=Array.prototype.slice;return e.cleanData=function(t){return function(n){var r,i,s;for(s=0;(i=n[s])!=null;s++)try{r=e._data(i,"events"),r&&r.remove&&e(i).triggerHandler("remove")}catch(o){}t(n)}}(e.cleanData),e.widget=function(t,n,r){var i,s,o,u,a={},f=t.split(".")[0];return t=t.split(".")[1],i=f+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[f]=e[f]||{},s=e[f][t],o=e[f][t]=function(e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)},e.extend(o,s,{version:r.version,_proto:e.extend({},r),_childConstructors:[]}),u=new n,u.options=e.widget.extend({},u.options),e.each(r,function(t,r){if(!e.isFunction(r)){a[t]=r;return}a[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=function(e){return n.prototype[t].apply(this,e)};return function(){var t=this._super,n=this._superApply,s;return this._super=e,this._superApply=i,s=r.apply(this,arguments),this._super=t,this._superApply=n,s}}()}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix||t:t},a,{constructor:o,namespace:f,widgetName:t,widgetFullName:i}),s?(e.each(s._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,o,n._proto)}),delete s._childConstructors):n._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){var r=n.call(arguments,1),i=0,s=r.length,o,u;for(;i<s;i++)for(o in r[i])u=r[i][o],r[i].hasOwnProperty(o)&&u!==undefined&&(e.isPlainObject(u)?t[o]=e.isPlainObject(t[o])?e.widget.extend({},t[o],u):e.widget.extend({},u):t[o]=u);return t},e.widget.bridge=function(t,r){var i=r.prototype.widgetFullName||t;e.fn[t]=function(s){var o=typeof s=="string",u=n.call(arguments,1),a=this;return o?this.each(function(){var n,r=e.data(this,i);if(s==="instance")return a=r,!1;if(!r)return e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+s+"'");if(!e.isFunction(r[s])||s.charAt(0)==="_")return e.error("no such method '"+s+"' for "+t+" widget instance");n=r[s].apply(r,u);if(n!==r&&n!==undefined)return a=n&&n.jquery?a.pushStack(n.get()):n,!1}):(u.length&&(s=e.widget.extend.apply(null,[s].concat(u))),this.each(function(){var t=e.data(this,i);t?(t.option(s||{}),t._init&&t._init()):e.data(this,i,new r(s,this))})),a}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(n,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=t++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&&(e.data(r,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),n),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,n){var r=t,i,s,o;if(arguments.length===0)return e.widget.extend({},this.options);if(typeof t=="string"){r={},i=t.split("."),t=i.shift();if(i.length){s=r[t]=e.widget.extend({},this.options[t]);for(o=0;o<i.length-1;o++)s[i[o]]=s[i[o]]||{},s=s[i[o]];t=i.pop();if(arguments.length===1)return s[t]===undefined?null:s[t];s[t]=n}else{if(arguments.length===1)return this.options[t]===undefined?null:this.options[t];r[t]=n}}return this._setOptions(r),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,e==="disabled"&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,n,r){var i,s=this;typeof t!="boolean"&&(r=n,n=t,t=!1),r?(n=i=e(n),this.bindings=this.bindings.add(n)):(r=n,n=this.element,i=this.widget()),e.each(r,function(r,o){function u(){if(!t&&(s.options.disabled===!0||e(this).hasClass("ui-state-disabled")))return;return(typeof o=="string"?s[o]:o).apply(s,arguments)}typeof o!="string"&&(u.guid=o.guid=o.guid||u.guid||e.guid++);var a=r.match(/^([\w:-]*)\s*(.*)$/),f=a[1]+s.eventNamespace,l=a[2];l?i.delegate(l,f,u):n.bind(f,u)})},_off:function(t,n){n=(n||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(n).undelegate(n),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function n(){return(typeof e=="string"?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,s,o=this.options[t];r=r||{},n=e.Event(n),n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),n.target=this.element[0],s=n.originalEvent;if(s)for(i in s)i in n||(n[i]=s[i]);return this.element.trigger(n,r),!(e.isFunction(o)&&o.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,s){typeof i=="string"&&(i={effect:i});var o,u=i?i===!0||typeof i=="number"?n:i.effect||n:t;i=i||{},typeof i=="number"&&(i={duration:i}),o=!e.isEmptyObject(i),i.complete=s,i.delay&&r.delay(i.delay),o&&e.effects&&e.effects.effect[u]?r[t](i):u!==t&&r[u]?r[u](i.duration,i.easing,s):r.queue(function(n){e(this)[t](),s&&s.call(r[0]),n()})}}),e.widget});;
/**
* @file
* Attaches behaviors for the Contextual module.
*/
(function ($, Drupal, drupalSettings, _, Backbone, JSON, storage) {
'use strict';
var options = $.extend(drupalSettings.contextual,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
open: Drupal.t('Open'),
close: Drupal.t('Close')
}
}
);
// Clear the cached contextual links whenever the current user's set of
// permissions changes.
var cachedPermissionsHash = storage.getItem('Drupal.contextual.permissionsHash');
var permissionsHash = drupalSettings.user.permissionsHash;
if (cachedPermissionsHash !== permissionsHash) {
if (typeof permissionsHash === 'string') {
_.chain(storage).keys().each(function (key) {
if (key.substring(0, 18) === 'Drupal.contextual.') {
storage.removeItem(key);
}
});
}
storage.setItem('Drupal.contextual.permissionsHash', permissionsHash);
}
/**
* Initializes a contextual link: updates its DOM, sets up model and views.
*
* @param {jQuery} $contextual
* A contextual links placeholder DOM element, containing the actual
* contextual links as rendered by the server.
* @param {string} html
* The server-side rendered HTML for this contextual link.
*/
function initContextual($contextual, html) {
var $region = $contextual.closest('.contextual-region');
var contextual = Drupal.contextual;
$contextual
// Update the placeholder to contain its rendered contextual links.
.html(html)
// Use the placeholder as a wrapper with a specific class to provide
// positioning and behavior attachment context.
.addClass('contextual')
// Ensure a trigger element exists before the actual contextual links.
.prepend(Drupal.theme('contextualTrigger'));
// Set the destination parameter on each of the contextual links.
var destination = 'destination=' + Drupal.encodePath(drupalSettings.path.currentPath);
$contextual.find('.contextual-links a').each(function () {
var url = this.getAttribute('href');
var glue = (url.indexOf('?') === -1) ? '?' : '&';
this.setAttribute('href', url + glue + destination);
});
// Create a model and the appropriate views.
var model = new contextual.StateModel({
title: $region.find('h2').eq(0).text().trim()
});
var viewOptions = $.extend({el: $contextual, model: model}, options);
contextual.views.push({
visual: new contextual.VisualView(viewOptions),
aural: new contextual.AuralView(viewOptions),
keyboard: new contextual.KeyboardView(viewOptions)
});
contextual.regionViews.push(new contextual.RegionView(
$.extend({el: $region, model: model}, options))
);
// Add the model to the collection. This must happen after the views have
// been associated with it, otherwise collection change event handlers can't
// trigger the model change event handler in its views.
contextual.collection.add(model);
// Let other JavaScript react to the adding of a new contextual link.
$(document).trigger('drupalContextualLinkAdded', {
$el: $contextual,
$region: $region,
model: model
});
// Fix visual collisions between contextual link triggers.
adjustIfNestedAndOverlapping($contextual);
}
/**
* Determines if a contextual link is nested & overlapping, if so: adjusts it.
*
* This only deals with two levels of nesting; deeper levels are not touched.
*
* @param {jQuery} $contextual
* A contextual links placeholder DOM element, containing the actual
* contextual links as rendered by the server.
*/
function adjustIfNestedAndOverlapping($contextual) {
var $contextuals = $contextual
// @todo confirm that .closest() is not sufficient
.parents('.contextual-region').eq(-1)
.find('.contextual');
// Early-return when there's no nesting.
if ($contextuals.length === 1) {
return;
}
// If the two contextual links overlap, then we move the second one.
var firstTop = $contextuals.eq(0).offset().top;
var secondTop = $contextuals.eq(1).offset().top;
if (firstTop === secondTop) {
var $nestedContextual = $contextuals.eq(1);
// Retrieve height of nested contextual link.
var height = 0;
var $trigger = $nestedContextual.find('.trigger');
// Elements with the .visually-hidden class have no dimensions, so this
// class must be temporarily removed to the calculate the height.
$trigger.removeClass('visually-hidden');
height = $nestedContextual.height();
$trigger.addClass('visually-hidden');
// Adjust nested contextual link's position.
$nestedContextual.css({top: $nestedContextual.position().top + height});
}
}
/**
* Attaches outline behavior for regions associated with contextual links.
*
* Events
* Contextual triggers an event that can be used by other scripts.
* - drupalContextualLinkAdded: Triggered when a contextual link is added.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the outline behavior to the right context.
*/
Drupal.behaviors.contextual = {
attach: function (context) {
var $context = $(context);
// Find all contextual links placeholders, if any.
var $placeholders = $context.find('[data-contextual-id]').once('contextual-render');
if ($placeholders.length === 0) {
return;
}
// Collect the IDs for all contextual links placeholders.
var ids = [];
$placeholders.each(function () {
ids.push($(this).attr('data-contextual-id'));
});
// Update all contextual links placeholders whose HTML is cached.
var uncachedIDs = _.filter(ids, function initIfCached(contextualID) {
var html = storage.getItem('Drupal.contextual.' + contextualID);
if (html && html.length) {
// Initialize after the current execution cycle, to make the AJAX
// request for retrieving the uncached contextual links as soon as
// possible, but also to ensure that other Drupal behaviors have had
// the chance to set up an event listener on the Backbone collection
// Drupal.contextual.collection.
window.setTimeout(function () {
initContextual($context.find('[data-contextual-id="' + contextualID + '"]'), html);
});
return false;
}
return true;
});
// Perform an AJAX request to let the server render the contextual links
// for each of the placeholders.
if (uncachedIDs.length > 0) {
$.ajax({
url: Drupal.url('contextual/render'),
type: 'POST',
data: {'ids[]': uncachedIDs},
dataType: 'json',
success: function (results) {
_.each(results, function (html, contextualID) {
// Store the metadata.
storage.setItem('Drupal.contextual.' + contextualID, html);
// If the rendered contextual links are empty, then the current
// user does not have permission to access the associated links:
// don't render anything.
if (html.length > 0) {
// Update the placeholders to contain its rendered contextual
// links. Usually there will only be one placeholder, but it's
// possible for multiple identical placeholders exist on the
// page (probably because the same content appears more than
// once).
$placeholders = $context.find('[data-contextual-id="' + contextualID + '"]');
// Initialize the contextual links.
for (var i = 0; i < $placeholders.length; i++) {
initContextual($placeholders.eq(i), html);
}
}
});
}
});
}
}
};
/**
* Namespace for contextual related functionality.
*
* @namespace
*/
Drupal.contextual = {
/**
* The {@link Drupal.contextual.View} instances associated with each list
* element of contextual links.
*
* @type {Array}
*/
views: [],
/**
* The {@link Drupal.contextual.RegionView} instances associated with each
* contextual region element.
*
* @type {Array}
*/
regionViews: []
};
/**
* A Backbone.Collection of {@link Drupal.contextual.StateModel} instances.
*
* @type {Backbone.Collection}
*/
Drupal.contextual.collection = new Backbone.Collection([], {model: Drupal.contextual.StateModel});
/**
* A trigger is an interactive element often bound to a click handler.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.contextualTrigger = function () {
return '<button class="trigger visually-hidden focusable" type="button"></button>';
};
})(jQuery, Drupal, drupalSettings, _, Backbone, window.JSON, window.sessionStorage);
;
/**
* @file
* A Backbone Model for the state of a contextual link's trigger, list & region.
*/
(function (Drupal, Backbone) {
'use strict';
/**
* Models the state of a contextual link's trigger, list & region.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.contextual.StateModel = Backbone.Model.extend(/** @lends Drupal.contextual.StateModel# */{
/**
* @type {object}
*
* @prop {string} title
* @prop {bool} regionIsHovered
* @prop {bool} hasFocus
* @prop {bool} isOpen
* @prop {bool} isLocked
*/
defaults: /** @lends Drupal.contextual.StateModel# */{
/**
* The title of the entity to which these contextual links apply.
*
* @type {string}
*/
title: '',
/**
* Represents if the contextual region is being hovered.
*
* @type {bool}
*/
regionIsHovered: false,
/**
* Represents if the contextual trigger or options have focus.
*
* @type {bool}
*/
hasFocus: false,
/**
* Represents if the contextual options for an entity are available to
* be selected (i.e. whether the list of options is visible).
*
* @type {bool}
*/
isOpen: false,
/**
* When the model is locked, the trigger remains active.
*
* @type {bool}
*/
isLocked: false
},
/**
* Opens or closes the contextual link.
*
* If it is opened, then also give focus.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
toggleOpen: function () {
var newIsOpen = !this.get('isOpen');
this.set('isOpen', newIsOpen);
if (newIsOpen) {
this.focus();
}
return this;
},
/**
* Closes this contextual link.
*
* Does not call blur() because we want to allow a contextual link to have
* focus, yet be closed for example when hovering.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
close: function () {
this.set('isOpen', false);
return this;
},
/**
* Gives focus to this contextual link.
*
* Also closes + removes focus from every other contextual link.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
focus: function () {
this.set('hasFocus', true);
var cid = this.cid;
this.collection.each(function (model) {
if (model.cid !== cid) {
model.close().blur();
}
});
return this;
},
/**
* Removes focus from this contextual link, unless it is open.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
blur: function () {
if (!this.get('isOpen')) {
this.set('hasFocus', false);
}
return this;
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides the aural view of a contextual link.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextual.AuralView = Backbone.View.extend(/** @lends Drupal.contextual.AuralView# */{
/**
* Renders the aural view of a contextual link (i.e. screen reader support).
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
*/
initialize: function (options) {
this.options = options;
this.listenTo(this.model, 'change', this.render);
// Use aria-role form so that the number of items in the list is spoken.
this.$el.attr('role', 'form');
// Initial render.
this.render();
},
/**
* @inheritdoc
*/
render: function () {
var isOpen = this.model.get('isOpen');
// Set the hidden property of the links.
this.$el.find('.contextual-links')
.prop('hidden', !isOpen);
// Update the view of the trigger.
this.$el.find('.trigger')
.text(Drupal.t('@action @title configuration options', {
'@action': (!isOpen) ? this.options.strings.open : this.options.strings.close,
'@title': this.model.get('title')
}))
.attr('aria-pressed', isOpen);
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides keyboard interaction for a contextual link.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextual.KeyboardView = Backbone.View.extend(/** @lends Drupal.contextual.KeyboardView# */{
/**
* @type {object}
*/
events: {
'focus .trigger': 'focus',
'focus .contextual-links a': 'focus',
'blur .trigger': function () { this.model.blur(); },
'blur .contextual-links a': function () {
// Set up a timeout to allow a user to tab between the trigger and the
// contextual links without the menu dismissing.
var that = this;
this.timer = window.setTimeout(function () {
that.model.close().blur();
}, 150);
}
},
/**
* Provides keyboard interaction for a contextual link.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
/**
* The timer is used to create a delay before dismissing the contextual
* links on blur. This is only necessary when keyboard users tab into
* contextual links without edit mode (i.e. without TabbingManager).
* That means that if we decide to disable tabbing of contextual links
* without edit mode, all this timer logic can go away.
*
* @type {NaN|number}
*/
this.timer = NaN;
},
/**
* Sets focus on the model; Clears the timer that dismisses the links.
*/
focus: function () {
// Clear the timeout that might have been set by blurring a link.
window.clearTimeout(this.timer);
this.model.focus();
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that renders the visual view of a contextual region element.
*/
(function (Drupal, Backbone, Modernizr) {
'use strict';
Drupal.contextual.RegionView = Backbone.View.extend(/** @lends Drupal.contextual.RegionView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
var mapping = {
mouseenter: function () { this.model.set('regionIsHovered', true); },
mouseleave: function () {
this.model.close().blur().set('regionIsHovered', false);
}
};
// We don't want mouse hover events on touch.
if (Modernizr.touchevents) {
mapping = {};
}
return mapping;
},
/**
* Renders the visual view of a contextual region element.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:hasFocus', this.render);
},
/**
* @inheritdoc
*
* @return {Drupal.contextual.RegionView}
* The current contextual region view.
*/
render: function () {
this.$el.toggleClass('focus', this.model.get('hasFocus'));
return this;
}
});
})(Drupal, Backbone, Modernizr);
;
/**
* @file
* A Backbone View that provides the visual view of a contextual link.
*/
(function (Drupal, Backbone, Modernizr) {
'use strict';
Drupal.contextual.VisualView = Backbone.View.extend(/** @lends Drupal.contextual.VisualView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
var mapping = {
'click .trigger': function () { this.model.toggleOpen(); },
'touchend .trigger': touchEndToClick,
'click .contextual-links a': function () { this.model.close().blur(); },
'touchend .contextual-links a': touchEndToClick
};
// We only want mouse hover events on non-touch.
if (!Modernizr.touchevents) {
mapping.mouseenter = function () { this.model.focus(); };
}
return mapping;
},
/**
* Renders the visual view of a contextual link. Listens to mouse & touch.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
/**
* @inheritdoc
*
* @return {Drupal.contextual.VisualView}
* The current contextual visual view.
*/
render: function () {
var isOpen = this.model.get('isOpen');
// The trigger should be visible when:
// - the mouse hovered over the region,
// - the trigger is locked,
// - and for as long as the contextual menu is open.
var isVisible = this.model.get('isLocked') || this.model.get('regionIsHovered') || isOpen;
this.$el
// The open state determines if the links are visible.
.toggleClass('open', isOpen)
// Update the visibility of the trigger.
.find('.trigger').toggleClass('visually-hidden', !isVisible);
// Nested contextual region handling: hide any nested contextual triggers.
if ('isOpen' in this.model.changed) {
this.$el.closest('.contextual-region')
.find('.contextual .trigger:not(:first)')
.toggle(!isOpen);
}
return this;
}
});
})(Drupal, Backbone, Modernizr);
;
/*!
* jQuery Form Plugin
* version: 3.51.0-2014.06.20
* Requires jQuery v1.5 or later
* Copyright (c) 2014 M. Alsup
* Examples and documentation at: http://malsup.com/jquery/form/
* Project repository: https://github.com/malsup/form
* Dual licensed under the MIT and GPL licenses.
* https://github.com/malsup/form#copyright-and-license
*/
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):e("undefined"!=typeof jQuery?jQuery:window.Zepto)}(function(e){"use strict";function t(t){var r=t.data;t.isDefaultPrevented()||(t.preventDefault(),e(t.target).ajaxSubmit(r))}function r(t){var r=t.target,a=e(r);if(!a.is("[type=submit],[type=image]")){var n=a.closest("[type=submit]");if(0===n.length)return;r=n[0]}var i=this;if(i.clk=r,"image"==r.type)if(void 0!==t.offsetX)i.clk_x=t.offsetX,i.clk_y=t.offsetY;else if("function"==typeof e.fn.offset){var o=a.offset();i.clk_x=t.pageX-o.left,i.clk_y=t.pageY-o.top}else i.clk_x=t.pageX-r.offsetLeft,i.clk_y=t.pageY-r.offsetTop;setTimeout(function(){i.clk=i.clk_x=i.clk_y=null},100)}function a(){if(e.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}var n={};n.fileapi=void 0!==e("<input type='file'/>").get(0).files,n.formdata=void 0!==window.FormData;var i=!!e.fn.prop;e.fn.attr2=function(){if(!i)return this.attr.apply(this,arguments);var e=this.prop.apply(this,arguments);return e&&e.jquery||"string"==typeof e?e:this.attr.apply(this,arguments)},e.fn.ajaxSubmit=function(t){function r(r){var a,n,i=e.param(r,t.traditional).split("&"),o=i.length,s=[];for(a=0;o>a;a++)i[a]=i[a].replace(/\+/g," "),n=i[a].split("="),s.push([decodeURIComponent(n[0]),decodeURIComponent(n[1])]);return s}function o(a){for(var n=new FormData,i=0;i<a.length;i++)n.append(a[i].name,a[i].value);if(t.extraData){var o=r(t.extraData);for(i=0;i<o.length;i++)o[i]&&n.append(o[i][0],o[i][1])}t.data=null;var s=e.extend(!0,{},e.ajaxSettings,t,{contentType:!1,processData:!1,cache:!1,type:u||"POST"});t.uploadProgress&&(s.xhr=function(){var r=e.ajaxSettings.xhr();return r.upload&&r.upload.addEventListener("progress",function(e){var r=0,a=e.loaded||e.position,n=e.total;e.lengthComputable&&(r=Math.ceil(a/n*100)),t.uploadProgress(e,a,n,r)},!1),r}),s.data=null;var c=s.beforeSend;return s.beforeSend=function(e,r){r.data=t.formData?t.formData:n,c&&c.call(this,e,r)},e.ajax(s)}function s(r){function n(e){var t=null;try{e.contentWindow&&(t=e.contentWindow.document)}catch(r){a("cannot get iframe.contentWindow document: "+r)}if(t)return t;try{t=e.contentDocument?e.contentDocument:e.document}catch(r){a("cannot get iframe.contentDocument: "+r),t=e.document}return t}function o(){function t(){try{var e=n(g).readyState;a("state = "+e),e&&"uninitialized"==e.toLowerCase()&&setTimeout(t,50)}catch(r){a("Server abort: ",r," (",r.name,")"),s(k),j&&clearTimeout(j),j=void 0}}var r=f.attr2("target"),i=f.attr2("action"),o="multipart/form-data",c=f.attr("enctype")||f.attr("encoding")||o;w.setAttribute("target",p),(!u||/post/i.test(u))&&w.setAttribute("method","POST"),i!=m.url&&w.setAttribute("action",m.url),m.skipEncodingOverride||u&&!/post/i.test(u)||f.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"}),m.timeout&&(j=setTimeout(function(){T=!0,s(D)},m.timeout));var l=[];try{if(m.extraData)for(var d in m.extraData)m.extraData.hasOwnProperty(d)&&l.push(e.isPlainObject(m.extraData[d])&&m.extraData[d].hasOwnProperty("name")&&m.extraData[d].hasOwnProperty("value")?e('<input type="hidden" name="'+m.extraData[d].name+'">').val(m.extraData[d].value).appendTo(w)[0]:e('<input type="hidden" name="'+d+'">').val(m.extraData[d]).appendTo(w)[0]);m.iframeTarget||v.appendTo("body"),g.attachEvent?g.attachEvent("onload",s):g.addEventListener("load",s,!1),setTimeout(t,15);try{w.submit()}catch(h){var x=document.createElement("form").submit;x.apply(w)}}finally{w.setAttribute("action",i),w.setAttribute("enctype",c),r?w.setAttribute("target",r):f.removeAttr("target"),e(l).remove()}}function s(t){if(!x.aborted&&!F){if(M=n(g),M||(a("cannot access response document"),t=k),t===D&&x)return x.abort("timeout"),void S.reject(x,"timeout");if(t==k&&x)return x.abort("server abort"),void S.reject(x,"error","server abort");if(M&&M.location.href!=m.iframeSrc||T){g.detachEvent?g.detachEvent("onload",s):g.removeEventListener("load",s,!1);var r,i="success";try{if(T)throw"timeout";var o="xml"==m.dataType||M.XMLDocument||e.isXMLDoc(M);if(a("isXml="+o),!o&&window.opera&&(null===M.body||!M.body.innerHTML)&&--O)return a("requeing onLoad callback, DOM not available"),void setTimeout(s,250);var u=M.body?M.body:M.documentElement;x.responseText=u?u.innerHTML:null,x.responseXML=M.XMLDocument?M.XMLDocument:M,o&&(m.dataType="xml"),x.getResponseHeader=function(e){var t={"content-type":m.dataType};return t[e.toLowerCase()]},u&&(x.status=Number(u.getAttribute("status"))||x.status,x.statusText=u.getAttribute("statusText")||x.statusText);var c=(m.dataType||"").toLowerCase(),l=/(json|script|text)/.test(c);if(l||m.textarea){var f=M.getElementsByTagName("textarea")[0];if(f)x.responseText=f.value,x.status=Number(f.getAttribute("status"))||x.status,x.statusText=f.getAttribute("statusText")||x.statusText;else if(l){var p=M.getElementsByTagName("pre")[0],h=M.getElementsByTagName("body")[0];p?x.responseText=p.textContent?p.textContent:p.innerText:h&&(x.responseText=h.textContent?h.textContent:h.innerText)}}else"xml"==c&&!x.responseXML&&x.responseText&&(x.responseXML=X(x.responseText));try{E=_(x,c,m)}catch(y){i="parsererror",x.error=r=y||i}}catch(y){a("error caught: ",y),i="error",x.error=r=y||i}x.aborted&&(a("upload aborted"),i=null),x.status&&(i=x.status>=200&&x.status<300||304===x.status?"success":"error"),"success"===i?(m.success&&m.success.call(m.context,E,"success",x),S.resolve(x.responseText,"success",x),d&&e.event.trigger("ajaxSuccess",[x,m])):i&&(void 0===r&&(r=x.statusText),m.error&&m.error.call(m.context,x,i,r),S.reject(x,"error",r),d&&e.event.trigger("ajaxError",[x,m,r])),d&&e.event.trigger("ajaxComplete",[x,m]),d&&!--e.active&&e.event.trigger("ajaxStop"),m.complete&&m.complete.call(m.context,x,i),F=!0,m.timeout&&clearTimeout(j),setTimeout(function(){m.iframeTarget?v.attr("src",m.iframeSrc):v.remove(),x.responseXML=null},100)}}}var c,l,m,d,p,v,g,x,y,b,T,j,w=f[0],S=e.Deferred();if(S.abort=function(e){x.abort(e)},r)for(l=0;l<h.length;l++)c=e(h[l]),i?c.prop("disabled",!1):c.removeAttr("disabled");if(m=e.extend(!0,{},e.ajaxSettings,t),m.context=m.context||m,p="jqFormIO"+(new Date).getTime(),m.iframeTarget?(v=e(m.iframeTarget),b=v.attr2("name"),b?p=b:v.attr2("name",p)):(v=e('<iframe name="'+p+'" src="'+m.iframeSrc+'" />'),v.css({position:"absolute",top:"-1000px",left:"-1000px"})),g=v[0],x={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(t){var r="timeout"===t?"timeout":"aborted";a("aborting upload... "+r),this.aborted=1;try{g.contentWindow.document.execCommand&&g.contentWindow.document.execCommand("Stop")}catch(n){}v.attr("src",m.iframeSrc),x.error=r,m.error&&m.error.call(m.context,x,r,t),d&&e.event.trigger("ajaxError",[x,m,r]),m.complete&&m.complete.call(m.context,x,r)}},d=m.global,d&&0===e.active++&&e.event.trigger("ajaxStart"),d&&e.event.trigger("ajaxSend",[x,m]),m.beforeSend&&m.beforeSend.call(m.context,x,m)===!1)return m.global&&e.active--,S.reject(),S;if(x.aborted)return S.reject(),S;y=w.clk,y&&(b=y.name,b&&!y.disabled&&(m.extraData=m.extraData||{},m.extraData[b]=y.value,"image"==y.type&&(m.extraData[b+".x"]=w.clk_x,m.extraData[b+".y"]=w.clk_y)));var D=1,k=2,A=e("meta[name=csrf-token]").attr("content"),L=e("meta[name=csrf-param]").attr("content");L&&A&&(m.extraData=m.extraData||{},m.extraData[L]=A),m.forceSync?o():setTimeout(o,10);var E,M,F,O=50,X=e.parseXML||function(e,t){return window.ActiveXObject?(t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(e)):t=(new DOMParser).parseFromString(e,"text/xml"),t&&t.documentElement&&"parsererror"!=t.documentElement.nodeName?t:null},C=e.parseJSON||function(e){return window.eval("("+e+")")},_=function(t,r,a){var n=t.getResponseHeader("content-type")||"",i="xml"===r||!r&&n.indexOf("xml")>=0,o=i?t.responseXML:t.responseText;return i&&"parsererror"===o.documentElement.nodeName&&e.error&&e.error("parsererror"),a&&a.dataFilter&&(o=a.dataFilter(o,r)),"string"==typeof o&&("json"===r||!r&&n.indexOf("json")>=0?o=C(o):("script"===r||!r&&n.indexOf("javascript")>=0)&&e.globalEval(o)),o};return S}if(!this.length)return a("ajaxSubmit: skipping submit process - no element selected"),this;var u,c,l,f=this;"function"==typeof t?t={success:t}:void 0===t&&(t={}),u=t.type||this.attr2("method"),c=t.url||this.attr2("action"),l="string"==typeof c?e.trim(c):"",l=l||window.location.href||"",l&&(l=(l.match(/^([^#]+)/)||[])[1]),t=e.extend(!0,{url:l,success:e.ajaxSettings.success,type:u||e.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},t);var m={};if(this.trigger("form-pre-serialize",[this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(t.beforeSerialize&&t.beforeSerialize(this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var d=t.traditional;void 0===d&&(d=e.ajaxSettings.traditional);var p,h=[],v=this.formToArray(t.semantic,h);if(t.data&&(t.extraData=t.data,p=e.param(t.data,d)),t.beforeSubmit&&t.beforeSubmit(v,this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[v,this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;var g=e.param(v,d);p&&(g=g?g+"&"+p:p),"GET"==t.type.toUpperCase()?(t.url+=(t.url.indexOf("?")>=0?"&":"?")+g,t.data=null):t.data=g;var x=[];if(t.resetForm&&x.push(function(){f.resetForm()}),t.clearForm&&x.push(function(){f.clearForm(t.includeHidden)}),!t.dataType&&t.target){var y=t.success||function(){};x.push(function(r){var a=t.replaceTarget?"replaceWith":"html";e(t.target)[a](r).each(y,arguments)})}else t.success&&x.push(t.success);if(t.success=function(e,r,a){for(var n=t.context||this,i=0,o=x.length;o>i;i++)x[i].apply(n,[e,r,a||f,f])},t.error){var b=t.error;t.error=function(e,r,a){var n=t.context||this;b.apply(n,[e,r,a,f])}}if(t.complete){var T=t.complete;t.complete=function(e,r){var a=t.context||this;T.apply(a,[e,r,f])}}var j=e("input[type=file]:enabled",this).filter(function(){return""!==e(this).val()}),w=j.length>0,S="multipart/form-data",D=f.attr("enctype")==S||f.attr("encoding")==S,k=n.fileapi&&n.formdata;a("fileAPI :"+k);var A,L=(w||D)&&!k;t.iframe!==!1&&(t.iframe||L)?t.closeKeepAlive?e.get(t.closeKeepAlive,function(){A=s(v)}):A=s(v):A=(w||D)&&k?o(v):e.ajax(t),f.removeData("jqxhr").data("jqxhr",A);for(var E=0;E<h.length;E++)h[E]=null;return this.trigger("form-submit-notify",[this,t]),this},e.fn.ajaxForm=function(n){if(n=n||{},n.delegation=n.delegation&&e.isFunction(e.fn.on),!n.delegation&&0===this.length){var i={s:this.selector,c:this.context};return!e.isReady&&i.s?(a("DOM not ready, queuing ajaxForm"),e(function(){e(i.s,i.c).ajaxForm(n)}),this):(a("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)")),this)}return n.delegation?(e(document).off("submit.form-plugin",this.selector,t).off("click.form-plugin",this.selector,r).on("submit.form-plugin",this.selector,n,t).on("click.form-plugin",this.selector,n,r),this):this.ajaxFormUnbind().bind("submit.form-plugin",n,t).bind("click.form-plugin",n,r)},e.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")},e.fn.formToArray=function(t,r){var a=[];if(0===this.length)return a;var i,o=this[0],s=this.attr("id"),u=t?o.getElementsByTagName("*"):o.elements;if(u&&!/MSIE [678]/.test(navigator.userAgent)&&(u=e(u).get()),s&&(i=e(':input[form="'+s+'"]').get(),i.length&&(u=(u||[]).concat(i))),!u||!u.length)return a;var c,l,f,m,d,p,h;for(c=0,p=u.length;p>c;c++)if(d=u[c],f=d.name,f&&!d.disabled)if(t&&o.clk&&"image"==d.type)o.clk==d&&(a.push({name:f,value:e(d).val(),type:d.type}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}));else if(m=e.fieldValue(d,!0),m&&m.constructor==Array)for(r&&r.push(d),l=0,h=m.length;h>l;l++)a.push({name:f,value:m[l]});else if(n.fileapi&&"file"==d.type){r&&r.push(d);var v=d.files;if(v.length)for(l=0;l<v.length;l++)a.push({name:f,value:v[l],type:d.type});else a.push({name:f,value:"",type:d.type})}else null!==m&&"undefined"!=typeof m&&(r&&r.push(d),a.push({name:f,value:m,type:d.type,required:d.required}));if(!t&&o.clk){var g=e(o.clk),x=g[0];f=x.name,f&&!x.disabled&&"image"==x.type&&(a.push({name:f,value:g.val()}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}))}return a},e.fn.formSerialize=function(t){return e.param(this.formToArray(t))},e.fn.fieldSerialize=function(t){var r=[];return this.each(function(){var a=this.name;if(a){var n=e.fieldValue(this,t);if(n&&n.constructor==Array)for(var i=0,o=n.length;o>i;i++)r.push({name:a,value:n[i]});else null!==n&&"undefined"!=typeof n&&r.push({name:this.name,value:n})}}),e.param(r)},e.fn.fieldValue=function(t){for(var r=[],a=0,n=this.length;n>a;a++){var i=this[a],o=e.fieldValue(i,t);null===o||"undefined"==typeof o||o.constructor==Array&&!o.length||(o.constructor==Array?e.merge(r,o):r.push(o))}return r},e.fieldValue=function(t,r){var a=t.name,n=t.type,i=t.tagName.toLowerCase();if(void 0===r&&(r=!0),r&&(!a||t.disabled||"reset"==n||"button"==n||("checkbox"==n||"radio"==n)&&!t.checked||("submit"==n||"image"==n)&&t.form&&t.form.clk!=t||"select"==i&&-1==t.selectedIndex))return null;if("select"==i){var o=t.selectedIndex;if(0>o)return null;for(var s=[],u=t.options,c="select-one"==n,l=c?o+1:u.length,f=c?o:0;l>f;f++){var m=u[f];if(m.selected){var d=m.value;if(d||(d=m.attributes&&m.attributes.value&&!m.attributes.value.specified?m.text:m.value),c)return d;s.push(d)}}return s}return e(t).val()},e.fn.clearForm=function(t){return this.each(function(){e("input,select,textarea",this).clearFields(t)})},e.fn.clearFields=e.fn.clearInputs=function(t){var r=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var a=this.type,n=this.tagName.toLowerCase();r.test(a)||"textarea"==n?this.value="":"checkbox"==a||"radio"==a?this.checked=!1:"select"==n?this.selectedIndex=-1:"file"==a?/MSIE/.test(navigator.userAgent)?e(this).replaceWith(e(this).clone(!0)):e(this).val(""):t&&(t===!0&&/hidden/.test(a)||"string"==typeof t&&e(this).is(t))&&(this.value="")})},e.fn.resetForm=function(){return this.each(function(){("function"==typeof this.reset||"object"==typeof this.reset&&!this.reset.nodeType)&&this.reset()})},e.fn.enable=function(e){return void 0===e&&(e=!0),this.each(function(){this.disabled=!e})},e.fn.selected=function(t){return void 0===t&&(t=!0),this.each(function(){var r=this.type;if("checkbox"==r||"radio"==r)this.checked=t;else if("option"==this.tagName.toLowerCase()){var a=e(this).parent("select");t&&a[0]&&"select-one"==a[0].type&&a.find("option").selected(!1),this.selected=t}})},e.fn.ajaxSubmit.debug=!1});
;
/*!
* jQuery UI Position 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){return function(){function h(e,t,n){return[parseFloat(e[0])*(l.test(e[0])?t/100:1),parseFloat(e[1])*(l.test(e[1])?n/100:1)]}function p(t,n){return parseInt(e.css(t,n),10)||0}function d(t){var n=t[0];return n.nodeType===9?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var t,n,r=Math.max,i=Math.abs,s=Math.round,o=/left|center|right/,u=/top|center|bottom/,a=/[\+\-]\d+(\.[\d]+)?%?/,f=/^\w+/,l=/%$/,c=e.fn.position;e.position={scrollbarWidth:function(){if(t!==undefined)return t;var n,r,i=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),s=i.children()[0];return e("body").append(i),n=s.offsetWidth,i.css("overflow","scroll"),r=s.offsetWidth,n===r&&(r=i[0].clientWidth),i.remove(),t=n-r},getScrollInfo:function(t){var n=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),r=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:s?e.position.scrollbarWidth():0,height:i?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]),i=!!n[0]&&n[0].nodeType===9;return{element:n,isWindow:r,isDocument:i,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r||i?n.width():n.outerWidth(),height:r||i?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return c.apply(this,arguments);t=e.extend({},t);var l,v,m,g,y,b,w=e(t.of),E=e.position.getWithinInfo(t.within),S=e.position.getScrollInfo(E),x=(t.collision||"flip").split(" "),T={};return b=d(w),w[0].preventDefault&&(t.at="left top"),v=b.width,m=b.height,g=b.offset,y=e.extend({},g),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=o.test(e[0])?e.concat(["center"]):u.test(e[0])?["center"].concat(e):["center","center"]),e[0]=o.test(e[0])?e[0]:"center",e[1]=u.test(e[1])?e[1]:"center",n=a.exec(e[0]),r=a.exec(e[1]),T[this]=[n?n[0]:0,r?r[0]:0],t[this]=[f.exec(e[0])[0],f.exec(e[1])[0]]}),x.length===1&&(x[1]=x[0]),t.at[0]==="right"?y.left+=v:t.at[0]==="center"&&(y.left+=v/2),t.at[1]==="bottom"?y.top+=m:t.at[1]==="center"&&(y.top+=m/2),l=h(T.at,v,m),y.left+=l[0],y.top+=l[1],this.each(function(){var o,u,a=e(this),f=a.outerWidth(),c=a.outerHeight(),d=p(this,"marginLeft"),b=p(this,"marginTop"),N=f+d+p(this,"marginRight")+S.width,C=c+b+p(this,"marginBottom")+S.height,k=e.extend({},y),L=h(T.my,a.outerWidth(),a.outerHeight());t.my[0]==="right"?k.left-=f:t.my[0]==="center"&&(k.left-=f/2),t.my[1]==="bottom"?k.top-=c:t.my[1]==="center"&&(k.top-=c/2),k.left+=L[0],k.top+=L[1],n||(k.left=s(k.left),k.top=s(k.top)),o={marginLeft:d,marginTop:b},e.each(["left","top"],function(n,r){e.ui.position[x[n]]&&e.ui.position[x[n]][r](k,{targetWidth:v,targetHeight:m,elemWidth:f,elemHeight:c,collisionPosition:o,collisionWidth:N,collisionHeight:C,offset:[l[0]+L[0],l[1]+L[1]],my:t.my,at:t.at,within:E,elem:a})}),t.using&&(u=function(e){var n=g.left-k.left,s=n+v-f,o=g.top-k.top,u=o+m-c,l={target:{element:w,left:g.left,top:g.top,width:v,height:m},element:{element:a,left:k.left,top:k.top,width:f,height:c},horizontal:s<0?"left":n>0?"right":"center",vertical:u<0?"top":o>0?"bottom":"middle"};v<f&&i(n+s)<v&&(l.horizontal="center"),m<c&&i(o+u)<m&&(l.vertical="middle"),r(i(n),i(s))>r(i(o),i(u))?l.important="horizontal":l.important="vertical",t.using.call(this,e,l)}),a.offset(e.extend(k,{using:u}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,i=n.isWindow?n.scrollLeft:n.offset.left,s=n.width,o=e.left-t.collisionPosition.marginLeft,u=i-o,a=o+t.collisionWidth-s-i,f;t.collisionWidth>s?u>0&&a<=0?(f=e.left+u+t.collisionWidth-s-i,e.left+=u-f):a>0&&u<=0?e.left=i:u>a?e.left=i+s-t.collisionWidth:e.left=i:u>0?e.left+=u:a>0?e.left-=a:e.left=r(e.left-o,e.left)},top:function(e,t){var n=t.within,i=n.isWindow?n.scrollTop:n.offset.top,s=t.within.height,o=e.top-t.collisionPosition.marginTop,u=i-o,a=o+t.collisionHeight-s-i,f;t.collisionHeight>s?u>0&&a<=0?(f=e.top+u+t.collisionHeight-s-i,e.top+=u-f):a>0&&u<=0?e.top=i:u>a?e.top=i+s-t.collisionHeight:e.top=i:u>0?e.top+=u:a>0?e.top-=a:e.top=r(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,s=n.width,o=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-o,f=u+t.collisionWidth-s-o,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-s-r;if(p<0||p<i(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-o;if(d>0||i(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,s=n.height,o=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-o,f=u+t.collisionHeight-s-o,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;if(a<0){v=e.top+c+h+p+t.collisionHeight-s-r;if(v<0||v<i(a))e.top+=c+h+p}else if(f>0){d=e.top-t.collisionPosition.marginTop+c+h+p-o;if(d>0||i(d)<f)e.top+=c+h+p}}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,r,i,s,o,u=document.getElementsByTagName("body")[0],a=document.createElement("div");t=document.createElement(u?"div":"body"),i={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},u&&e.extend(i,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in i)t.style[o]=i[o];t.appendChild(a),r=u||document.documentElement,r.insertBefore(t,r.firstChild),a.style.cssText="position: absolute; left: 10.7432222px;",s=e(a).offset().left,n=s>10&&s<11,t.innerHTML="",r.removeChild(t)}()}(),e.ui.position});;
/**
* @file
* Adapted from underscore.js with the addition Drupal namespace.
*/
/**
* Limits the invocations of a function in a given time frame.
*
* The debounce function wrapper should be used sparingly. One clear use case
* is limiting the invocation of a callback attached to the window resize event.
*
* Before using the debounce function wrapper, consider first whether the
* callback could be attached to an event that fires less frequently or if the
* function can be written in such a way that it is only invoked under specific
* conditions.
*
* @param {function} func
* The function to be invoked.
* @param {number} wait
* The time period within which the callback function should only be
* invoked once. For example if the wait period is 250ms, then the callback
* will only be called at most 4 times per second.
* @param {bool} immediate
* Whether we wait at the beginning or end to execute the function.
*
* @return {function}
* The debounced function.
*/
Drupal.debounce = function (func, wait, immediate) {
'use strict';
var timeout;
var result;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
};
;
/**
* @file
* Manages elements that can offset the size of the viewport.
*
* Measures and reports viewport offset dimensions from elements like the
* toolbar that can potentially displace the positioning of other elements.
*/
/**
* @typedef {object} Drupal~displaceOffset
*
* @prop {number} top
* @prop {number} left
* @prop {number} right
* @prop {number} bottom
*/
/**
* Triggers when layout of the page changes.
*
* This is used to position fixed element on the page during page resize and
* Toolbar toggling.
*
* @event drupalViewportOffsetChange
*/
(function ($, Drupal, debounce) {
'use strict';
/**
* @name Drupal.displace.offsets
*
* @type {Drupal~displaceOffset}
*/
var offsets = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
/**
* Registers a resize handler on the window.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.drupalDisplace = {
attach: function () {
// Mark this behavior as processed on the first pass.
if (this.displaceProcessed) {
return;
}
this.displaceProcessed = true;
$(window).on('resize.drupalDisplace', debounce(displace, 200));
}
};
/**
* Informs listeners of the current offset dimensions.
*
* @function Drupal.displace
*
* @prop {Drupal~displaceOffset} offsets
*
* @param {bool} [broadcast]
* When true or undefined, causes the recalculated offsets values to be
* broadcast to listeners.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*
* @fires event:drupalViewportOffsetChange
*/
function displace(broadcast) {
offsets = Drupal.displace.offsets = calculateOffsets();
if (typeof broadcast === 'undefined' || broadcast) {
$(document).trigger('drupalViewportOffsetChange', offsets);
}
return offsets;
}
/**
* Determines the viewport offsets.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*/
function calculateOffsets() {
return {
top: calculateOffset('top'),
right: calculateOffset('right'),
bottom: calculateOffset('bottom'),
left: calculateOffset('left')
};
}
/**
* Gets a specific edge's offset.
*
* Any element with the attribute data-offset-{edge} e.g. data-offset-top will
* be considered in the viewport offset calculations. If the attribute has a
* numeric value, that value will be used. If no value is provided, one will
* be calculated using the element's dimensions and placement.
*
* @function Drupal.displace.calculateOffset
*
* @param {string} edge
* The name of the edge to calculate. Can be 'top', 'right',
* 'bottom' or 'left'.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function calculateOffset(edge) {
var edgeOffset = 0;
var displacingElements = document.querySelectorAll('[data-offset-' + edge + ']');
var n = displacingElements.length;
for (var i = 0; i < n; i++) {
var el = displacingElements[i];
// If the element is not visible, do consider its dimensions.
if (el.style.display === 'none') {
continue;
}
// If the offset data attribute contains a displacing value, use it.
var displacement = parseInt(el.getAttribute('data-offset-' + edge), 10);
// If the element's offset data attribute exits
// but is not a valid number then get the displacement
// dimensions directly from the element.
if (isNaN(displacement)) {
displacement = getRawOffset(el, edge);
}
// If the displacement value is larger than the current value for this
// edge, use the displacement value.
edgeOffset = Math.max(edgeOffset, displacement);
}
return edgeOffset;
}
/**
* Calculates displacement for element based on its dimensions and placement.
*
* @param {HTMLElement} el
* The jQuery element whose dimensions and placement will be measured.
*
* @param {string} edge
* The name of the edge of the viewport that the element is associated
* with.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function getRawOffset(el, edge) {
var $el = $(el);
var documentElement = document.documentElement;
var displacement = 0;
var horizontal = (edge === 'left' || edge === 'right');
// Get the offset of the element itself.
var placement = $el.offset()[horizontal ? 'left' : 'top'];
// Subtract scroll distance from placement to get the distance
// to the edge of the viewport.
placement -= window['scroll' + (horizontal ? 'X' : 'Y')] || document.documentElement['scroll' + (horizontal ? 'Left' : 'Top')] || 0;
// Find the displacement value according to the edge.
switch (edge) {
// Left and top elements displace as a sum of their own offset value
// plus their size.
case 'top':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerHeight();
break;
case 'left':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerWidth();
break;
// Right and bottom elements displace according to their left and
// top offset. Their size isn't important.
case 'bottom':
displacement = documentElement.clientHeight - placement;
break;
case 'right':
displacement = documentElement.clientWidth - placement;
break;
default:
displacement = 0;
}
return displacement;
}
/**
* Assign the displace function to a property of the Drupal global object.
*
* @ignore
*/
Drupal.displace = displace;
$.extend(Drupal.displace, {
/**
* Expose offsets to other scripts to avoid having to recalculate offsets.
*
* @ignore
*/
offsets: offsets,
/**
* Expose method to compute a single edge offsets.
*
* @ignore
*/
calculateOffset: calculateOffset
});
})(jQuery, Drupal, Drupal.debounce);
;
/*! jquery.cookie v1.4.1 | MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});;
/**
* @file
* Form features.
*/
/**
* Triggers when a value in the form changed.
*
* The event triggers when content is typed or pasted in a text field, before
* the change event triggers.
*
* @event formUpdated
*/
(function ($, Drupal, debounce) {
'use strict';
/**
* Retrieves the summary for the first element.
*
* @return {string}
* The text of the summary.
*/
$.fn.drupalGetSummary = function () {
var callback = this.data('summaryCallback');
return (this[0] && callback) ? $.trim(callback(this[0])) : '';
};
/**
* Sets the summary for all matched elements.
*
* @param {function} callback
* Either a function that will be called each time the summary is
* retrieved or a string (which is returned each time).
*
* @return {jQuery}
* jQuery collection of the current element.
*
* @fires event:summaryUpdated
*
* @listens event:formUpdated
*/
$.fn.drupalSetSummary = function (callback) {
var self = this;
// To facilitate things, the callback should always be a function. If it's
// not, we wrap it into an anonymous function which just returns the value.
if (typeof callback !== 'function') {
var val = callback;
callback = function () { return val; };
}
return this
.data('summaryCallback', callback)
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.off('formUpdated.summary')
.on('formUpdated.summary', function () {
self.trigger('summaryUpdated');
})
// The actual summaryUpdated handler doesn't fire when the callback is
// changed, so we have to do this manually.
.trigger('summaryUpdated');
};
/**
* Prevents consecutive form submissions of identical form values.
*
* Repetitive form submissions that would submit the identical form values
* are prevented, unless the form values are different to the previously
* submitted values.
*
* This is a simplified re-implementation of a user-agent behavior that
* should be natively supported by major web browsers, but at this time, only
* Firefox has a built-in protection.
*
* A form value-based approach ensures that the constraint is triggered for
* consecutive, identical form submissions only. Compared to that, a form
* button-based approach would (1) rely on [visible] buttons to exist where
* technically not required and (2) require more complex state management if
* there are multiple buttons in a form.
*
* This implementation is based on form-level submit events only and relies
* on jQuery's serialize() method to determine submitted form values. As such,
* the following limitations exist:
*
* - Event handlers on form buttons that preventDefault() do not receive a
* double-submit protection. That is deemed to be fine, since such button
* events typically trigger reversible client-side or server-side
* operations that are local to the context of a form only.
* - Changed values in advanced form controls, such as file inputs, are not
* part of the form values being compared between consecutive form submits
* (due to limitations of jQuery.serialize()). That is deemed to be
* acceptable, because if the user forgot to attach a file, then the size of
* HTTP payload will most likely be small enough to be fully passed to the
* server endpoint within (milli)seconds. If a user mistakenly attached a
* wrong file and is technically versed enough to cancel the form submission
* (and HTTP payload) in order to attach a different file, then that
* edge-case is not supported here.
*
* Lastly, all forms submitted via HTTP GET are idempotent by definition of
* HTTP standards, so excluded in this implementation.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.formSingleSubmit = {
attach: function () {
function onFormSubmit(e) {
var $form = $(e.currentTarget);
var formValues = $form.serialize();
var previousValues = $form.attr('data-drupal-form-submit-last');
if (previousValues === formValues) {
e.preventDefault();
}
else {
$form.attr('data-drupal-form-submit-last', formValues);
}
}
$('body').once('form-single-submit')
.on('submit.singleSubmit', 'form:not([method~="GET"])', onFormSubmit);
}
};
/**
* Sends a 'formUpdated' event each time a form element is modified.
*
* @param {HTMLElement} element
* The element to trigger a form updated event on.
*
* @fires event:formUpdated
*/
function triggerFormUpdated(element) {
$(element).trigger('formUpdated');
}
/**
* Collects the IDs of all form fields in the given form.
*
* @param {HTMLFormElement} form
* The form element to search.
*
* @return {Array}
* Array of IDs for form fields.
*/
function fieldsList(form) {
var $fieldList = $(form).find('[name]').map(function (index, element) {
// We use id to avoid name duplicates on radio fields and filter out
// elements with a name but no id.
return element.getAttribute('id');
});
// Return a true array.
return $.makeArray($fieldList);
}
/**
* Triggers the 'formUpdated' event on form elements when they are modified.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches formUpdated behaviors.
* @prop {Drupal~behaviorDetach} detach
* Detaches formUpdated behaviors.
*
* @fires event:formUpdated
*/
Drupal.behaviors.formUpdated = {
attach: function (context) {
var $context = $(context);
var contextIsForm = $context.is('form');
var $forms = (contextIsForm ? $context : $context.find('form')).once('form-updated');
var formFields;
if ($forms.length) {
// Initialize form behaviors, use $.makeArray to be able to use native
// forEach array method and have the callback parameters in the right
// order.
$.makeArray($forms).forEach(function (form) {
var events = 'change.formUpdated input.formUpdated ';
var eventHandler = debounce(function (event) { triggerFormUpdated(event.target); }, 300);
formFields = fieldsList(form).join(',');
form.setAttribute('data-drupal-form-fields', formFields);
$(form).on(events, eventHandler);
});
}
// On ajax requests context is the form element.
if (contextIsForm) {
formFields = fieldsList(context).join(',');
// @todo replace with form.getAttribute() when #1979468 is in.
var currentFields = $(context).attr('data-drupal-form-fields');
// If there has been a change in the fields or their order, trigger
// formUpdated.
if (formFields !== currentFields) {
triggerFormUpdated(context);
}
}
},
detach: function (context, settings, trigger) {
var $context = $(context);
var contextIsForm = $context.is('form');
if (trigger === 'unload') {
var $forms = (contextIsForm ? $context : $context.find('form')).removeOnce('form-updated');
if ($forms.length) {
$.makeArray($forms).forEach(function (form) {
form.removeAttribute('data-drupal-form-fields');
$(form).off('.formUpdated');
});
}
}
}
};
/**
* Prepopulate form fields with information from the visitor browser.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the behavior for filling user info from browser.
*/
Drupal.behaviors.fillUserInfoFromBrowser = {
attach: function (context, settings) {
var userInfo = ['name', 'mail', 'homepage'];
var $forms = $('[data-user-info-from-browser]').once('user-info-from-browser');
if ($forms.length) {
userInfo.map(function (info) {
var $element = $forms.find('[name=' + info + ']');
var browserData = localStorage.getItem('Drupal.visitor.' + info);
var emptyOrDefault = ($element.val() === '' || ($element.attr('data-drupal-default-value') === $element.val()));
if ($element.length && emptyOrDefault && browserData) {
$element.val(browserData);
}
});
}
$forms.on('submit', function () {
userInfo.map(function (info) {
var $element = $forms.find('[name=' + info + ']');
if ($element.length) {
localStorage.setItem('Drupal.visitor.' + info, $element.val());
}
});
});
}
};
})(jQuery, Drupal, Drupal.debounce);
;
/**
* @file
* Progress bar.
*/
(function ($, Drupal) {
'use strict';
/**
* Theme function for the progress bar.
*
* @param {string} id
* The id for the progress bar.
*
* @return {string}
* The HTML for the progress bar.
*/
Drupal.theme.progressBar = function (id) {
return '<div id="' + id + '" class="progress" aria-live="polite">' +
'<div class="progress__label"> </div>' +
'<div class="progress__track"><div class="progress__bar"></div></div>' +
'<div class="progress__percentage"></div>' +
'<div class="progress__description"> </div>' +
'</div>';
};
/**
* A progressbar object. Initialized with the given id. Must be inserted into
* the DOM afterwards through progressBar.element.
*
* Method is the function which will perform the HTTP request to get the
* progress bar state. Either "GET" or "POST".
*
* @example
* pb = new Drupal.ProgressBar('myProgressBar');
* some_element.appendChild(pb.element);
*
* @constructor
*
* @param {string} id
* The id for the progressbar.
* @param {function} updateCallback
* Callback to run on update.
* @param {string} method
* HTTP method to use.
* @param {function} errorCallback
* Callback to call on error.
*/
Drupal.ProgressBar = function (id, updateCallback, method, errorCallback) {
this.id = id;
this.method = method || 'GET';
this.updateCallback = updateCallback;
this.errorCallback = errorCallback;
// The WAI-ARIA setting aria-live="polite" will announce changes after
// users
// have completed their current activity and not interrupt the screen
// reader.
this.element = $(Drupal.theme('progressBar', id));
};
$.extend(Drupal.ProgressBar.prototype, /** @lends Drupal.ProgressBar# */{
/**
* Set the percentage and status message for the progressbar.
*
* @param {number} percentage
* The progress percentage.
* @param {string} message
* The message to show the user.
* @param {string} label
* The text for the progressbar label.
*/
setProgress: function (percentage, message, label) {
if (percentage >= 0 && percentage <= 100) {
$(this.element).find('div.progress__bar').css('width', percentage + '%');
$(this.element).find('div.progress__percentage').html(percentage + '%');
}
$('div.progress__description', this.element).html(message);
$('div.progress__label', this.element).html(label);
if (this.updateCallback) {
this.updateCallback(percentage, message, this);
}
},
/**
* Start monitoring progress via Ajax.
*
* @param {string} uri
* The URI to use for monitoring.
* @param {number} delay
* The delay for calling the monitoring URI.
*/
startMonitoring: function (uri, delay) {
this.delay = delay;
this.uri = uri;
this.sendPing();
},
/**
* Stop monitoring progress via Ajax.
*/
stopMonitoring: function () {
clearTimeout(this.timer);
// This allows monitoring to be stopped from within the callback.
this.uri = null;
},
/**
* Request progress data from server.
*/
sendPing: function () {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.uri) {
var pb = this;
// When doing a post request, you need non-null data. Otherwise a
// HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
var uri = this.uri;
if (uri.indexOf('?') === -1) {
uri += '?';
}
else {
uri += '&';
}
uri += '_format=json';
$.ajax({
type: this.method,
url: uri,
data: '',
dataType: 'json',
success: function (progress) {
// Display errors.
if (progress.status === 0) {
pb.displayError(progress.data);
return;
}
// Update display.
pb.setProgress(progress.percentage, progress.message, progress.label);
// Schedule next timer.
pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
},
error: function (xmlhttp) {
var e = new Drupal.AjaxError(xmlhttp, pb.uri);
pb.displayError('<pre>' + e.message + '</pre>');
}
});
}
},
/**
* Display errors on the page.
*
* @param {string} string
* The error message to show the user.
*/
displayError: function (string) {
var error = $('<div class="messages messages--error"></div>').html(string);
$(this.element).before(error).hide();
if (this.errorCallback) {
this.errorCallback(this);
}
}
});
})(jQuery, Drupal);
;
/**
* @file
* Provides Ajax page updating via jQuery $.ajax.
*
* Ajax is a method of making a request via JavaScript while viewing an HTML
* page. The request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*/
(function ($, window, Drupal, drupalSettings) {
'use strict';
/**
* Attaches the Ajax behavior to each Ajax form element.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Initialize all {@link Drupal.Ajax} objects declared in
* `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from
* DOM elements having the `use-ajax-submit` or `use-ajax` css class.
* @prop {Drupal~behaviorDetach} detach
* During `unload` remove all {@link Drupal.Ajax} objects related to
* the removed content.
*/
Drupal.behaviors.AJAX = {
attach: function (context, settings) {
function loadAjaxBehavior(base) {
var element_settings = settings.ajax[base];
if (typeof element_settings.selector === 'undefined') {
element_settings.selector = '#' + base;
}
$(element_settings.selector).once('drupal-ajax').each(function () {
element_settings.element = this;
element_settings.base = base;
Drupal.ajax(element_settings);
});
}
// Load all Ajax behaviors specified in the settings.
for (var base in settings.ajax) {
if (settings.ajax.hasOwnProperty(base)) {
loadAjaxBehavior(base);
}
}
// Bind Ajax behaviors to all items showing the class.
$('.use-ajax').once('ajax').each(function () {
var element_settings = {};
// Clicked links look better with the throbber than the progress bar.
element_settings.progress = {type: 'throbber'};
// For anchor tags, these will go to the target of the anchor rather
// than the usual location.
var href = $(this).attr('href');
if (href) {
element_settings.url = href;
element_settings.event = 'click';
}
element_settings.dialogType = $(this).data('dialog-type');
element_settings.dialog = $(this).data('dialog-options');
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
// This class means to submit the form to the action using Ajax.
$('.use-ajax-submit').once('ajax').each(function () {
var element_settings = {};
// Ajax submits specified in this manner automatically submit to the
// normal form action.
element_settings.url = $(this.form).attr('action');
// Form submit button clicks need to tell the form what was clicked so
// it gets passed in the POST request.
element_settings.setClick = true;
// Form buttons use the 'click' event rather than mousedown.
element_settings.event = 'click';
// Clicked form buttons look better with the throbber than the progress
// bar.
element_settings.progress = {type: 'throbber'};
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
Drupal.ajax.expired().forEach(function (instance) {
// Set this to null and allow garbage collection to reclaim
// the memory.
Drupal.ajax.instances[instance.instanceIndex] = null;
});
}
}
};
/**
* Extends Error to provide handling for Errors in Ajax.
*
* @constructor
*
* @augments Error
*
* @param {XMLHttpRequest} xmlhttp
* XMLHttpRequest object used for the failed request.
* @param {string} uri
* The URI where the error occurred.
* @param {string} customMessage
* The custom message.
*/
Drupal.AjaxError = function (xmlhttp, uri, customMessage) {
var statusCode;
var statusText;
var pathText;
var responseText;
var readyStateText;
if (xmlhttp.status) {
statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status});
}
else {
statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.');
}
statusCode += '\n' + Drupal.t('Debugging information follows.');
pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri});
statusText = '';
// In some cases, when statusCode === 0, xmlhttp.statusText may not be
// defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
// catch that and the test causes an exception. So we need to catch the
// exception here.
try {
statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)});
}
catch (e) {
// Empty.
}
responseText = '';
// Again, we don't have a way to know for sure whether accessing
// xmlhttp.responseText is going to throw an exception. So we'll catch it.
try {
responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)});
}
catch (e) {
// Empty.
}
// Make the responseText more readable by stripping HTML tags and newlines.
responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
responseText = responseText.replace(/[\n]+\s+/g, '\n');
// We don't need readyState except for status == 0.
readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : '';
customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : '';
/**
* Formatted and translated error message.
*
* @type {string}
*/
this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
/**
* Used by some browsers to display a more accurate stack trace.
*
* @type {string}
*/
this.name = 'AjaxError';
};
Drupal.AjaxError.prototype = new Error();
Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
/**
* Provides Ajax page updating via jQuery $.ajax.
*
* This function is designed to improve developer experience by wrapping the
* initialization of {@link Drupal.Ajax} objects and storing all created
* objects in the {@link Drupal.ajax.instances} array.
*
* @example
* Drupal.behaviors.myCustomAJAXStuff = {
* attach: function (context, settings) {
*
* var ajaxSettings = {
* url: 'my/url/path',
* // If the old version of Drupal.ajax() needs to be used those
* // properties can be added
* base: 'myBase',
* element: $(context).find('.someElement')
* };
*
* var myAjaxObject = Drupal.ajax(ajaxSettings);
*
* // Declare a new Ajax command specifically for this Ajax object.
* myAjaxObject.commands.insert = function (ajax, response, status) {
* $('#my-wrapper').append(response.data);
* alert('New content was appended to #my-wrapper');
* };
*
* // This command will remove this Ajax object from the page.
* myAjaxObject.commands.destroyObject = function (ajax, response, status) {
* Drupal.ajax.instances[this.instanceIndex] = null;
* };
*
* // Programmatically trigger the Ajax request.
* myAjaxObject.execute();
* }
* };
*
* @param {object} settings
* The settings object passed to {@link Drupal.Ajax} constructor.
* @param {string} [settings.base]
* Base is passed to {@link Drupal.Ajax} constructor as the 'base'
* parameter.
* @param {HTMLElement} [settings.element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
*
* @return {Drupal.Ajax}
* The created Ajax object.
*
* @see Drupal.AjaxCommands
*/
Drupal.ajax = function (settings) {
if (arguments.length !== 1) {
throw new Error('Drupal.ajax() function must be called with one configuration object only');
}
// Map those config keys to variables for the old Drupal.ajax function.
var base = settings.base || false;
var element = settings.element || false;
delete settings.base;
delete settings.element;
// By default do not display progress for ajax calls without an element.
if (!settings.progress && !element) {
settings.progress = false;
}
var ajax = new Drupal.Ajax(base, element, settings);
ajax.instanceIndex = Drupal.ajax.instances.length;
Drupal.ajax.instances.push(ajax);
return ajax;
};
/**
* Contains all created Ajax objects.
*
* @type {Array.<Drupal.Ajax|null>}
*/
Drupal.ajax.instances = [];
/**
* List all objects where the associated element is not in the DOM
*
* This method ignores {@link Drupal.Ajax} objects not bound to DOM elements
* when created with {@link Drupal.ajax}.
*
* @return {Array.<Drupal.Ajax>}
* The list of expired {@link Drupal.Ajax} objects.
*/
Drupal.ajax.expired = function () {
return Drupal.ajax.instances.filter(function (instance) {
return instance && instance.element !== false && !document.body.contains(instance.element);
});
};
/**
* Settings for an Ajax object.
*
* @typedef {object} Drupal.Ajax~element_settings
*
* @prop {string} url
* Target of the Ajax request.
* @prop {?string} [event]
* Event bound to settings.element which will trigger the Ajax request.
* @prop {bool} [keypress=true]
* Triggers a request on keypress events.
* @prop {?string} selector
* jQuery selector targeting the element to bind events to or used with
* {@link Drupal.AjaxCommands}.
* @prop {string} [effect='none']
* Name of the jQuery method to use for displaying new Ajax content.
* @prop {string|number} [speed='none']
* Speed with which to apply the effect.
* @prop {string} [method]
* Name of the jQuery method used to insert new content in the targeted
* element.
* @prop {object} [progress]
* Settings for the display of a user-friendly loader.
* @prop {string} [progress.type='throbber']
* Type of progress element, core provides `'bar'`, `'throbber'` and
* `'fullscreen'`.
* @prop {string} [progress.message=Drupal.t('Please wait...')]
* Custom message to be used with the bar indicator.
* @prop {object} [submit]
* Extra data to be sent with the Ajax request.
* @prop {bool} [submit.js=true]
* Allows the PHP side to know this comes from an Ajax request.
* @prop {object} [dialog]
* Options for {@link Drupal.dialog}.
* @prop {string} [dialogType]
* One of `'modal'` or `'dialog'`.
* @prop {string} [prevent]
* List of events on which to stop default action and stop propagation.
*/
/**
* Ajax constructor.
*
* The Ajax request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*
* @constructor
*
* @param {string} [base]
* Base parameter of {@link Drupal.Ajax} constructor
* @param {HTMLElement} [element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
* @param {Drupal.Ajax~element_settings} element_settings
* Settings for this Ajax object.
*/
Drupal.Ajax = function (base, element, element_settings) {
var defaults = {
event: element ? 'mousedown' : null,
keypress: true,
selector: base ? '#' + base : null,
effect: 'none',
speed: 'none',
method: 'replaceWith',
progress: {
type: 'throbber',
message: Drupal.t('Please wait...')
},
submit: {
js: true
}
};
$.extend(this, defaults, element_settings);
/**
* @type {Drupal.AjaxCommands}
*/
this.commands = new Drupal.AjaxCommands();
/**
* @type {bool|number}
*/
this.instanceIndex = false;
// @todo Remove this after refactoring the PHP code to:
// - Call this 'selector'.
// - Include the '#' for ID-based selectors.
// - Support non-ID-based selectors.
if (this.wrapper) {
/**
* @type {string}
*/
this.wrapper = '#' + this.wrapper;
}
/**
* @type {HTMLElement}
*/
this.element = element;
/**
* @type {Drupal.Ajax~element_settings}
*/
this.element_settings = element_settings;
// If there isn't a form, jQuery.ajax() will be used instead, allowing us to
// bind Ajax to links as well.
if (this.element && this.element.form) {
/**
* @type {jQuery}
*/
this.$form = $(this.element.form);
}
// If no Ajax callback URL was given, use the link href or form action.
if (!this.url) {
var $element = $(this.element);
if ($element.is('a')) {
this.url = $element.attr('href');
}
else if (this.element && element.form) {
this.url = this.$form.attr('action');
}
}
// Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
// the server detect when it needs to degrade gracefully.
// There are four scenarios to check for:
// 1. /nojs/
// 2. /nojs$ - The end of a URL string.
// 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
// 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
var originalUrl = this.url;
/**
* Processed Ajax URL.
*
* @type {string}
*/
this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1');
// If the 'nojs' version of the URL is trusted, also trust the 'ajax'
// version.
if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
drupalSettings.ajaxTrustedUrl[this.url] = true;
}
// Set the options for the ajaxSubmit function.
// The 'this' variable will not persist inside of the options object.
var ajax = this;
/**
* Options for the jQuery.ajax function.
*
* @name Drupal.Ajax#options
*
* @type {object}
*
* @prop {string} url
* Ajax URL to be called.
* @prop {object} data
* Ajax payload.
* @prop {function} beforeSerialize
* Implement jQuery beforeSerialize function to call
* {@link Drupal.Ajax#beforeSerialize}.
* @prop {function} beforeSubmit
* Implement jQuery beforeSubmit function to call
* {@link Drupal.Ajax#beforeSubmit}.
* @prop {function} beforeSend
* Implement jQuery beforeSend function to call
* {@link Drupal.Ajax#beforeSend}.
* @prop {function} success
* Implement jQuery success function to call
* {@link Drupal.Ajax#success}.
* @prop {function} complete
* Implement jQuery success function to clean up ajax state and trigger an
* error if needed.
* @prop {string} dataType='json'
* Type of the response expected.
* @prop {string} type='POST'
* HTTP method to use for the Ajax request.
*/
ajax.options = {
url: ajax.url,
data: ajax.submit,
beforeSerialize: function (element_settings, options) {
return ajax.beforeSerialize(element_settings, options);
},
beforeSubmit: function (form_values, element_settings, options) {
ajax.ajaxing = true;
return ajax.beforeSubmit(form_values, element_settings, options);
},
beforeSend: function (xmlhttprequest, options) {
ajax.ajaxing = true;
return ajax.beforeSend(xmlhttprequest, options);
},
success: function (response, status, xmlhttprequest) {
// Sanity check for browser support (object expected).
// When using iFrame uploads, responses must be returned as a string.
if (typeof response === 'string') {
response = $.parseJSON(response);
}
// Prior to invoking the response's commands, verify that they can be
// trusted by checking for a response header. See
// \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
// - Empty responses are harmless so can bypass verification. This
// avoids an alert message for server-generated no-op responses that
// skip Ajax rendering.
// - Ajax objects with trusted URLs (e.g., ones defined server-side via
// #ajax) can bypass header verification. This is especially useful
// for Ajax with multipart forms. Because IFRAME transport is used,
// the response headers cannot be accessed for verification.
if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
var customMessage = Drupal.t('The response failed verification so will not be processed.');
return ajax.error(xmlhttprequest, ajax.url, customMessage);
}
}
return ajax.success(response, status);
},
complete: function (xmlhttprequest, status) {
ajax.ajaxing = false;
if (status === 'error' || status === 'parsererror') {
return ajax.error(xmlhttprequest, ajax.url);
}
},
dataType: 'json',
type: 'POST'
};
if (element_settings.dialog) {
ajax.options.data.dialogOptions = element_settings.dialog;
}
// Ensure that we have a valid URL by adding ? when no query parameter is
// yet available, otherwise append using &.
if (ajax.options.url.indexOf('?') === -1) {
ajax.options.url += '?';
}
else {
ajax.options.url += '&';
}
ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax');
// Bind the ajaxSubmit function to the element event.
$(ajax.element).on(element_settings.event, function (event) {
if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
}
return ajax.eventResponse(this, event);
});
// If necessary, enable keyboard submission so that Ajax behaviors
// can be triggered through keyboard input as well as e.g. a mousedown
// action.
if (element_settings.keypress) {
$(ajax.element).on('keypress', function (event) {
return ajax.keypressResponse(this, event);
});
}
// If necessary, prevent the browser default action of an additional event.
// For example, prevent the browser default action of a click, even if the
// Ajax behavior binds to mousedown.
if (element_settings.prevent) {
$(ajax.element).on(element_settings.prevent, false);
}
};
/**
* URL query attribute to indicate the wrapper used to render a request.
*
* The wrapper format determines how the HTML is wrapped, for example in a
* modal dialog.
*
* @const {string}
*
* @default
*/
Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
/**
* Request parameter to indicate that a request is a Drupal Ajax request.
*
* @const {string}
*
* @default
*/
Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
/**
* Execute the ajax request.
*
* Allows developers to execute an Ajax request manually without specifying
* an event to respond to.
*
* @return {object}
* Returns the jQuery.Deferred object underlying the Ajax request. If
* pre-serialization fails, the Deferred will be returned in the rejected
* state.
*/
Drupal.Ajax.prototype.execute = function () {
// Do not perform another ajax command if one is already in progress.
if (this.ajaxing) {
return;
}
try {
this.beforeSerialize(this.element, this.options);
// Return the jqXHR so that external code can hook into the Deferred API.
return $.ajax(this.options);
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
this.ajaxing = false;
window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message);
// For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
// so that calling code can take appropriate action.
return $.Deferred().reject();
}
};
/**
* Handle a key press.
*
* The Ajax object will, if instructed, bind to a key press response. This
* will test to see if the key press is valid to trigger this event and
* if it is, trigger it for us and prevent other keypresses from triggering.
* In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
* and 32. RETURN is often used to submit a form when in a textfield, and
* SPACE is often used to activate an element without submitting.
*
* @param {HTMLElement} element
* Element the event was triggered on.
* @param {jQuery.Event} event
* Triggered event.
*/
Drupal.Ajax.prototype.keypressResponse = function (element, event) {
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Detect enter key and space bar and allow the standard response for them,
// except for form elements of type 'text', 'tel', 'number' and 'textarea',
// where the spacebar activation causes inappropriate activation if
// #ajax['keypress'] is TRUE. On a text-type widget a space should always
// be a space.
if (event.which === 13 || (event.which === 32 && element.type !== 'text' &&
element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) {
event.preventDefault();
event.stopPropagation();
$(ajax.element_settings.element).trigger(ajax.element_settings.event);
}
};
/**
* Handle an event that triggers an Ajax response.
*
* When an event that triggers an Ajax response happens, this method will
* perform the actual Ajax call. It is bound to the event using
* bind() in the constructor, and it uses the options specified on the
* Ajax object.
*
* @param {HTMLElement} element
* Element the event was triggered on.
* @param {jQuery.Event} event
* Triggered event.
*/
Drupal.Ajax.prototype.eventResponse = function (element, event) {
event.preventDefault();
event.stopPropagation();
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Do not perform another Ajax command if one is already in progress.
if (ajax.ajaxing) {
return;
}
try {
if (ajax.$form) {
// If setClick is set, we must set this to ensure that the button's
// value is passed.
if (ajax.setClick) {
// Mark the clicked button. 'form.clk' is a special variable for
// ajaxSubmit that tells the system which element got clicked to
// trigger the submit. Without it there would be no 'op' or
// equivalent.
element.form.clk = element;
}
ajax.$form.ajaxSubmit(ajax.options);
}
else {
ajax.beforeSerialize(ajax.element, ajax.options);
$.ajax(ajax.options);
}
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
ajax.ajaxing = false;
window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message);
}
};
/**
* Handler for the form serialization.
*
* Runs before the beforeSend() handler (see below), and unlike that one, runs
* before field data is collected.
*
* @param {object} [element]
* Ajax object's `element_settings`.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
// Allow detaching behaviors to update field values before collecting them.
// This is only needed when field values are added to the POST data, so only
// when there is a form such that this.$form.ajaxSubmit() is used instead of
// $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
// isn't called, but don't rely on that: explicitly check this.$form.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
}
// Inform Drupal that this is an AJAX request.
options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
// Allow Drupal to return new JavaScript and CSS files to load without
// returning the ones already loaded.
// @see \Drupal\Core\Theme\AjaxBasePageNegotiator
// @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
// @see system_js_settings_alter()
var pageState = drupalSettings.ajaxPageState;
options.data['ajax_page_state[theme]'] = pageState.theme;
options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
options.data['ajax_page_state[libraries]'] = pageState.libraries;
};
/**
* Modify form values prior to form submission.
*
* @param {Array.<object>} form_values
* Processed form values.
* @param {jQuery} element
* The form node as a jQuery object.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
// This function is left empty to make it simple to override for modules
// that wish to add functionality here.
};
/**
* Prepare the Ajax request before it is sent.
*
* @param {XMLHttpRequest} xmlhttprequest
* Native Ajax object.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
// For forms without file inputs, the jQuery Form plugin serializes the
// form values, and then calls jQuery's $.ajax() function, which invokes
// this handler. In this circumstance, options.extraData is never used. For
// forms with file inputs, the jQuery Form plugin uses the browser's normal
// form submission mechanism, but captures the response in a hidden IFRAME.
// In this circumstance, it calls this handler first, and then appends
// hidden fields to the form to submit the values in options.extraData.
// There is no simple way to know which submission mechanism will be used,
// so we add to extraData regardless, and allow it to be ignored in the
// former case.
if (this.$form) {
options.extraData = options.extraData || {};
// Let the server know when the IFRAME submission mechanism is used. The
// server can use this information to wrap the JSON response in a
// TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
options.extraData.ajax_iframe_upload = '1';
// The triggering element is about to be disabled (see below), but if it
// contains a value (e.g., a checkbox, textfield, select, etc.), ensure
// that value is included in the submission. As per above, submissions
// that use $.ajax() are already serialized prior to the element being
// disabled, so this is only needed for IFRAME submissions.
var v = $.fieldValue(this.element);
if (v !== null) {
options.extraData[this.element.name] = v;
}
}
// Disable the element that received the change to prevent user interface
// interaction while the Ajax request is in progress. ajax.ajaxing prevents
// the element from triggering a new request, but does not prevent the user
// from changing its value.
$(this.element).prop('disabled', true);
if (!this.progress || !this.progress.type) {
return;
}
// Insert progress indicator.
var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase();
if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
this[progressIndicatorMethod].call(this);
}
};
/**
* Sets the progress bar progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
if (this.progress.message) {
progressBar.setProgress(-1, this.progress.message);
}
if (this.progress.url) {
progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
}
this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
this.progress.object = progressBar;
$(this.element).after(this.progress.element);
};
/**
* Sets the throbber progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
if (this.progress.message) {
this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>');
}
$(this.element).after(this.progress.element);
};
/**
* Sets the fullscreen progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen"> </div>');
$('body').after(this.progress.element);
};
/**
* Handler for the form redirection completion.
*
* @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
* Drupal Ajax response.
* @param {number} status
* XMLHttpRequest status.
*/
Drupal.Ajax.prototype.success = function (response, status) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
$(this.element).prop('disabled', false);
// Save element's ancestors tree so if the element is removed from the dom
// we can try to refocus one of its parents. Using addBack reverse the
// result array, meaning that index 0 is the highest parent in the hierarchy
// in this situation it is usually a <form> element.
var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray();
// Track if any command is altering the focus so we can avoid changing the
// focus set by the Ajax command.
var focusChanged = false;
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
if (response[i].command === 'invoke' && response[i].method === 'focus') {
focusChanged = true;
}
}
}
// If the focus hasn't be changed by the ajax commands, try to refocus the
// triggering element or one of its parents if that element does not exist
// anymore.
if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) {
var target = false;
for (var n = elementParents.length - 1; !target && n > 0; n--) {
target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]');
}
if (target) {
$(target).trigger('focus');
}
}
// Reattach behaviors, if they were detached in beforeSerialize(). The
// attachBehaviors() called on the new content from processing the response
// commands is not sufficient, because behaviors from the entire form need
// to be reattached.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
// Remove any response-specific settings so they don't get used on the next
// call by mistake.
this.settings = null;
};
/**
* Build an effect object to apply an effect when adding new HTML.
*
* @param {object} response
* Drupal Ajax response.
* @param {string} [response.effect]
* Override the default value of {@link Drupal.Ajax#element_settings}.
* @param {string|number} [response.speed]
* Override the default value of {@link Drupal.Ajax#element_settings}.
*
* @return {object}
* Returns an object with `showEffect`, `hideEffect` and `showSpeed`
* properties.
*/
Drupal.Ajax.prototype.getEffect = function (response) {
var type = response.effect || this.effect;
var speed = response.speed || this.speed;
var effect = {};
if (type === 'none') {
effect.showEffect = 'show';
effect.hideEffect = 'hide';
effect.showSpeed = '';
}
else if (type === 'fade') {
effect.showEffect = 'fadeIn';
effect.hideEffect = 'fadeOut';
effect.showSpeed = speed;
}
else {
effect.showEffect = type + 'Toggle';
effect.hideEffect = type + 'Toggle';
effect.showSpeed = speed;
}
return effect;
};
/**
* Handler for the form redirection error.
*
* @param {object} xmlhttprequest
* Native XMLHttpRequest object.
* @param {string} uri
* Ajax Request URI.
* @param {string} [customMessage]
* Extra message to print with the Ajax error.
*/
Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
// Undo hide.
$(this.wrapper).show();
// Re-enable the element.
$(this.element).prop('disabled', false);
// Reattach behaviors, if they were detached in beforeSerialize().
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
};
/**
* @typedef {object} Drupal.AjaxCommands~commandDefinition
*
* @prop {string} command
* @prop {string} [method]
* @prop {string} [selector]
* @prop {string} [data]
* @prop {object} [settings]
* @prop {bool} [asterisk]
* @prop {string} [text]
* @prop {string} [title]
* @prop {string} [url]
* @prop {object} [argument]
* @prop {string} [name]
* @prop {string} [value]
* @prop {string} [old]
* @prop {string} [new]
* @prop {bool} [merge]
* @prop {Array} [args]
*
* @see Drupal.AjaxCommands
*/
/**
* Provide a series of commands that the client will perform.
*
* @constructor
*/
Drupal.AjaxCommands = function () {};
Drupal.AjaxCommands.prototype = {
/**
* Command to insert new content into the DOM.
*
* @param {Drupal.Ajax} ajax
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.data
* The data to use with the jQuery method.
* @param {string} [response.method]
* The jQuery DOM manipulation method to be used.
* @param {string} [response.selector]
* A optional jQuery selector string.
* @param {object} [response.settings]
* An optional array of settings that will be used.
* @param {number} [status]
* The XMLHttpRequest status.
*/
insert: function (ajax, response, status) {
// Get information from the response. If it is not there, default to
// our presets.
var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
var method = response.method || ajax.method;
var effect = ajax.getEffect(response);
var settings;
// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly interpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('<div></div>').replaceWith(response.data).
var $new_content_wrapped = $('<div></div>').html(response.data);
var $new_content = $new_content_wrapped.contents();
// For legacy reasons, the effects processing code assumes that
// $new_content consists of a single top-level element. Also, it has not
// been sufficiently tested whether attachBehaviors() can be successfully
// called with a context object that includes top-level text nodes.
// However, to give developers full control of the HTML appearing in the
// page, and to enable Ajax content to be inserted in places where <div>
// elements are not allowed (e.g., within <table>, <tr>, and <span>
// parents), we check if the new content satisfies the requirement
// of a single top-level element, and only use the container <div> created
// above when it doesn't. For more information, please see
// https://www.drupal.org/node/736066.
if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) {
$new_content = $new_content_wrapped;
}
// If removing content from the wrapper, detach behaviors first.
switch (method) {
case 'html':
case 'replaceWith':
case 'replaceAll':
case 'empty':
case 'remove':
settings = response.settings || ajax.settings || drupalSettings;
Drupal.detachBehaviors($wrapper.get(0), settings);
}
// Add the new content to the page.
$wrapper[method]($new_content);
// Immediately hide the new content if we're using any effects.
if (effect.showEffect !== 'show') {
$new_content.hide();
}
// Determine which effect to use and what content will receive the
// effect, then show the new content.
if ($new_content.find('.ajax-new-content').length > 0) {
$new_content.find('.ajax-new-content').hide();
$new_content.show();
$new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
}
else if (effect.showEffect !== 'show') {
$new_content[effect.showEffect](effect.showSpeed);
}
// Attach all JavaScript behaviors to the new content, if it was
// successfully added to the page, this if statement allows
// `#ajax['wrapper']` to be optional.
if ($new_content.parents('html').length > 0) {
// Apply any settings from the returned JSON if available.
settings = response.settings || ajax.settings || drupalSettings;
Drupal.attachBehaviors($new_content.get(0), settings);
}
},
/**
* Command to remove a chunk from the page.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {object} [response.settings]
* An optional array of settings that will be used.
* @param {number} [status]
* The XMLHttpRequest status.
*/
remove: function (ajax, response, status) {
var settings = response.settings || ajax.settings || drupalSettings;
$(response.selector).each(function () {
Drupal.detachBehaviors(this, settings);
})
.remove();
},
/**
* Command to mark a chunk changed.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The JSON response object from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {bool} [response.asterisk]
* An optional CSS selector. If specified, an asterisk will be
* appended to the HTML inside the provided selector.
* @param {number} [status]
* The request status.
*/
changed: function (ajax, response, status) {
var $element = $(response.selector);
if (!$element.hasClass('ajax-changed')) {
$element.addClass('ajax-changed');
if (response.asterisk) {
$element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> ');
}
}
},
/**
* Command to provide an alert.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The JSON response from the Ajax request.
* @param {string} response.text
* The text that will be displayed in an alert dialog.
* @param {number} [status]
* The XMLHttpRequest status.
*/
alert: function (ajax, response, status) {
window.alert(response.text, response.title);
},
/**
* Command to set the window.location, redirecting the browser.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.url
* The URL to redirect to.
* @param {number} [status]
* The XMLHttpRequest status.
*/
redirect: function (ajax, response, status) {
window.location = response.url;
},
/**
* Command to provide the jQuery css() function.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {object} response.argument
* An array of key/value pairs to set in the CSS for the selector.
* @param {number} [status]
* The XMLHttpRequest status.
*/
css: function (ajax, response, status) {
$(response.selector).css(response.argument);
},
/**
* Command to set the settings used for other commands in this response.
*
* This method will also remove expired `drupalSettings.ajax` settings.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {bool} response.merge
* Determines whether the additional settings should be merged to the
* global settings.
* @param {object} response.settings
* Contains additional settings to add to the global settings.
* @param {number} [status]
* The XMLHttpRequest status.
*/
settings: function (ajax, response, status) {
var ajaxSettings = drupalSettings.ajax;
// Clean up drupalSettings.ajax.
if (ajaxSettings) {
Drupal.ajax.expired().forEach(function (instance) {
// If the Ajax object has been created through drupalSettings.ajax
// it will have a selector. When there is no selector the object
// has been initialized with a special class name picked up by the
// Ajax behavior.
if (instance.selector) {
var selector = instance.selector.replace('#', '');
if (selector in ajaxSettings) {
delete ajaxSettings[selector];
}
}
});
}
if (response.merge) {
$.extend(true, drupalSettings, response.settings);
}
else {
ajax.settings = response.settings;
}
},
/**
* Command to attach data using jQuery's data API.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.name
* The name or key (in the key value pair) of the data attached to this
* selector.
* @param {string} response.selector
* A jQuery selector string.
* @param {string|object} response.value
* The value of to be attached.
* @param {number} [status]
* The XMLHttpRequest status.
*/
data: function (ajax, response, status) {
$(response.selector).data(response.name, response.value);
},
/**
* Command to apply a jQuery method.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {Array} response.args
* An array of arguments to the jQuery method, if any.
* @param {string} response.method
* The jQuery method to invoke.
* @param {string} response.selector
* A jQuery selector string.
* @param {number} [status]
* The XMLHttpRequest status.
*/
invoke: function (ajax, response, status) {
var $element = $(response.selector);
$element[response.method].apply($element, response.args);
},
/**
* Command to restripe a table.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {number} [status]
* The XMLHttpRequest status.
*/
restripe: function (ajax, response, status) {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$(response.selector).find('> tbody > tr:visible, > tr:visible')
.removeClass('odd even')
.filter(':even').addClass('odd').end()
.filter(':odd').addClass('even');
},
/**
* Command to update a form's build ID.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.old
* The old form build ID.
* @param {string} response.new
* The new form build ID.
* @param {number} [status]
* The XMLHttpRequest status.
*/
update_build_id: function (ajax, response, status) {
$('input[name="form_build_id"][value="' + response.old + '"]').val(response.new);
},
/**
* Command to add css.
*
* Uses the proprietary addImport method if available as browsers which
* support that method ignore @import statements in dynamically added
* stylesheets.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.data
* A string that contains the styles to be added.
* @param {number} [status]
* The XMLHttpRequest status.
*/
add_css: function (ajax, response, status) {
// Add the styles in the normal way.
$('head').prepend(response.data);
// Add imports in the styles using the addImport method if available.
var match;
var importMatch = /^@import url\("(.*)"\);$/igm;
if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
importMatch.lastIndex = 0;
do {
match = importMatch.exec(response.data);
document.styleSheets[0].addImport(match[1]);
} while (match);
}
}
};
})(jQuery, window, Drupal, drupalSettings);
;
/*!
* jQuery UI Button 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/button/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery","./core","./widget"],e):e(jQuery)})(function(e){var t,n="ui-button ui-widget ui-state-default ui-corner-all",r="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",i=function(){var t=e(this);setTimeout(function(){t.find(":ui-button").button("refresh")},1)},s=function(t){var n=t.name,r=t.form,i=e([]);return n&&(n=n.replace(/'/g,"\\'"),r?i=e(r).find("[name='"+n+"'][type=radio]"):i=e("[name='"+n+"'][type=radio]",t.ownerDocument).filter(function(){return!this.form})),i};return e.widget("ui.button",{version:"1.11.4",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,i),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var r=this,o=this.options,u=this.type==="checkbox"||this.type==="radio",a=u?"":"ui-state-active";o.label===null&&(o.label=this.type==="input"?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(n).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){if(o.disabled)return;this===t&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){if(o.disabled)return;e(this).removeClass(a)}).bind("click"+this.eventNamespace,function(e){o.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),u&&this.element.bind("change"+this.eventNamespace,function(){r.refresh()}),this.type==="checkbox"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(o.disabled)return!1}):this.type==="radio"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(o.disabled)return!1;e(this).addClass("ui-state-active"),r.buttonElement.attr("aria-pressed","true");var t=r.element[0];s(t).not(t).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){if(o.disabled)return!1;e(this).addClass("ui-state-active"),t=this,r.document.one("mouseup",function(){t=null})}).bind("mouseup"+this.eventNamespace,function(){if(o.disabled)return!1;e(this).removeClass("ui-state-active")}).bind("keydown"+this.eventNamespace,function(t){if(o.disabled)return!1;(t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active")}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",o.disabled),this._resetButton()},_determineButtonType:function(){var e,t,n;this.element.is("[type=checkbox]")?this.type="checkbox":this.element.is("[type=radio]")?this.type="radio":this.element.is("input")?this.type="input":this.type="button",this.type==="checkbox"||this.type==="radio"?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),n=this.element.is(":checked"),n&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",n)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(n+" ui-state-active "+r).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){this._super(e,t);if(e==="disabled"){this.widget().toggleClass("ui-state-disabled",!!t),this.element.prop("disabled",!!t),t&&(this.type==="checkbox"||this.type==="radio"?this.buttonElement.removeClass("ui-state-focus"):this.buttonElement.removeClass("ui-state-focus ui-state-active"));return}this._resetButton()},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),this.type==="radio"?s(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var t=this.buttonElement.removeClass(r),n=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),i=this.options.icons,s=i.primary&&i.secondary,o=[];i.primary||i.secondary?(this.options.text&&o.push("ui-button-text-icon"+(s?"s":i.primary?"-primary":"-secondary")),i.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+i.primary+"'></span>"),i.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+i.secondary+"'></span>"),this.options.text||(o.push(s?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(n)))):o.push("ui-button-text-only"),t.addClass(o.join(" "))}}),e.widget("ui.buttonset",{version:"1.11.4",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){e==="disabled"&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t=this.element.css("direction")==="rtl",n=this.element.find(this.options.items),r=n.filter(":ui-button");n.not(":ui-button").button(),r.button("refresh"),this.buttons=n.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}}),e.ui.button});;
/*!
* jQuery UI Mouse 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/mouse/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery","./widget"],e):e(jQuery)})(function(e){var t=!1;return e(document).mouseup(function(){t=!1}),e.widget("ui.mouse",{version:"1.11.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent"))return e.removeData(n.target,t.widgetName+".preventClickEvent"),n.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(n){if(t)return;this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(n),this._mouseDownEvent=n;var r=this,i=n.which===1,s=typeof this.options.cancel=="string"&&n.target.nodeName?e(n.target).closest(this.options.cancel).length:!1;if(!i||s||!this._mouseCapture(n))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(n)&&this._mouseDelayMet(n)){this._mouseStarted=this._mouseStart(n)!==!1;if(!this._mouseStarted)return n.preventDefault(),!0}return!0===e.data(n.target,this.widgetName+".preventClickEvent")&&e.removeData(n.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return r._mouseMove(e)},this._mouseUpDelegate=function(e){return r._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),n.preventDefault(),t=!0,!0},_mouseMove:function(t){if(this._mouseMoved){if(e.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(!t.which)return this._mouseUp(t)}if(t.which||t.button)this._mouseMoved=!0;return this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(n){return this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,n.target===this._mouseDownEvent.target&&e.data(n.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(n)),t=!1,!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})});;
/*!
* jQuery UI Draggable 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/draggable/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery","./core","./mouse","./widget"],e):e(jQuery)})(function(e){return e.widget("ui.draggable",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){this.options.helper==="original"&&this._setPositionRelative(),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._setHandleClassName(),this._mouseInit()},_setOption:function(e,t){this._super(e,t),e==="handle"&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){if((this.helper||this.element).is(".ui-draggable-dragging")){this.destroyOnClear=!0;return}this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this._blurActiveElement(t),this.helper||n.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(this._blockFrames(n.iframeFix===!0?"iframe":n.iframeFix),!0):!1)},_blockFrames:function(t){this.iframeBlocks=this.document.find(t).map(function(){var t=e(this);return e("<div>").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var n=this.document[0];if(!this.handleElement.is(t.target))return;try{n.activeElement&&n.activeElement.nodeName.toLowerCase()!=="body"&&e(n.activeElement).blur()}catch(r){}},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return e(this).css("position")==="fixed"}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(t),this.originalPosition=this.position=this._generatePosition(t,!1),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&&this._adjustOffsetFromHelper(n.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._normalizeRightBottom(),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_refreshOffsets:function(e){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:e.pageX-this.offset.left,top:e.pageY-this.offset.top}},_mouseDrag:function(t,n){this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),this.positionAbs=this._convertPositionTo("absolute");if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1;this.position=r.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n=this,r=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(r=e.ui.ddmanager.drop(this,t)),this.dropped&&(r=this.dropped,this.dropped=!1),this.options.revert==="invalid"&&!r||this.options.revert==="valid"&&r||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,r)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){n._trigger("stop",t)!==!1&&n._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1},_mouseUp:function(t){return this._unblockFrames(),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),this.handleElement.is(t.target)&&this.element.focus(),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this.handleElement.addClass("ui-draggable-handle")},_removeHandleClassName:function(){this.handleElement.removeClass("ui-draggable-handle")},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper),i=r?e(n.helper.apply(this.element[0],[t])):n.helper==="clone"?this.element.clone().removeAttr("id"):this.element;return i.parents("body").length||i.appendTo(n.appendTo==="parent"?this.element[0].parentNode:n.appendTo),r&&i[0]===this.element[0]&&this._setPositionRelative(),i[0]!==this.element[0]&&!/(fixed|absolute)/.test(i.css("position"))&&i.css("position","absolute"),i},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_isRootNode:function(e){return/(html|body)/i.test(e.tagName)||e===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),n=this.document[0];return this.cssPosition==="absolute"&&this.scrollParent[0]!==n&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition!=="relative")return{top:0,left:0};var e=this.element.position(),t=this._isRootNode(this.scrollParent[0]);return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+(t?0:this.scrollParent.scrollTop()),left:e.left-(parseInt(this.helper.css("left"),10)||0)+(t?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options,s=this.document[0];this.relativeContainer=null;if(!i.containment){this.containment=null;return}if(i.containment==="window"){this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||s.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return}if(i.containment==="document"){this.containment=[0,0,e(s).width()-this.helperProportions.width-this.margins.left,(e(s).height()||s.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return}if(i.containment.constructor===Array){this.containment=i.containment;return}i.containment==="parent"&&(i.containment=this.helper[0].parentNode),n=e(i.containment),r=n[0];if(!r)return;t=/(scroll|auto)/.test(n.css("overflow")),this.containment=[(parseInt(n.css("borderLeftWidth"),10)||0)+(parseInt(n.css("paddingLeft"),10)||0),(parseInt(n.css("borderTopWidth"),10)||0)+(parseInt(n.css("paddingTop"),10)||0),(t?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(n.css("borderRightWidth"),10)||0)-(parseInt(n.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(n.css("borderBottomWidth"),10)||0)-(parseInt(n.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=n},_convertPositionTo:function(e,t){t||(t=this.position);var n=e==="absolute"?1:-1,r=this._isRootNode(this.scrollParent[0]);return{top:t.top+this.offset.relative.top*n+this.offset.parent.top*n-(this.cssPosition==="fixed"?-this.offset.scroll.top:r?0:this.offset.scroll.top)*n,left:t.left+this.offset.relative.left*n+this.offset.parent.left*n-(this.cssPosition==="fixed"?-this.offset.scroll.left:r?0:this.offset.scroll.left)*n}},_generatePosition:function(e,t){var n,r,i,s,o=this.options,u=this._isRootNode(this.scrollParent[0]),a=e.pageX,f=e.pageY;if(!u||!this.offset.scroll)this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()};return t&&(this.containment&&(this.relativeContainer?(r=this.relativeContainer.offset(),n=[this.containment[0]+r.left,this.containment[1]+r.top,this.containment[2]+r.left,this.containment[3]+r.top]):n=this.containment,e.pageX-this.offset.click.left<n[0]&&(a=n[0]+this.offset.click.left),e.pageY-this.offset.click.top<n[1]&&(f=n[1]+this.offset.click.top),e.pageX-this.offset.click.left>n[2]&&(a=n[2]+this.offset.click.left),e.pageY-this.offset.click.top>n[3]&&(f=n[3]+this.offset.click.top)),o.grid&&(i=o.grid[1]?this.originalPageY+Math.round((f-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,f=n?i-this.offset.click.top>=n[1]||i-this.offset.click.top>n[3]?i:i-this.offset.click.top>=n[1]?i-o.grid[1]:i+o.grid[1]:i,s=o.grid[0]?this.originalPageX+Math.round((a-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,a=n?s-this.offset.click.left>=n[0]||s-this.offset.click.left>n[2]?s:s-this.offset.click.left>=n[0]?s-o.grid[0]:s+o.grid[0]:s),o.axis==="y"&&(a=this.originalPageX),o.axis==="x"&&(f=this.originalPageY)),{top:f-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.offset.scroll.top:u?0:this.offset.scroll.top),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.offset.scroll.left:u?0:this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!==this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_normalizeRightBottom:function(){this.options.axis!=="y"&&this.helper.css("right")!=="auto"&&(this.helper.width(this.helper.width()),this.helper.css("right","auto")),this.options.axis!=="x"&&this.helper.css("bottom")!=="auto"&&(this.helper.height(this.helper.height()),this.helper.css("bottom","auto"))},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),r.offset=this.positionAbs),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n,r){var i=e.extend({},n,{item:r.element});r.sortables=[],e(r.options.connectToSortable).each(function(){var n=e(this).sortable("instance");n&&!n.options.disabled&&(r.sortables.push(n),n.refreshPositions(),n._trigger("activate",t,i))})},stop:function(t,n,r){var i=e.extend({},n,{item:r.element});r.cancelHelperRemoval=!1,e.each(r.sortables,function(){var e=this;e.isOver?(e.isOver=0,r.cancelHelperRemoval=!0,e.cancelHelperRemoval=!1,e._storedCSS={position:e.placeholder.css("position"),top:e.placeholder.css("top"),left:e.placeholder.css("left")},e._mouseStop(t),e.options.helper=e.options._helper):(e.cancelHelperRemoval=!0,e._trigger("deactivate",t,i))})},drag:function(t,n,r){e.each(r.sortables,function(){var i=!1,s=this;s.positionAbs=r.positionAbs,s.helperProportions=r.helperProportions,s.offset.click=r.offset.click,s._intersectsWith(s.containerCache)&&(i=!0,e.each(r.sortables,function(){return this.positionAbs=r.positionAbs,this.helperProportions=r.helperProportions,this.offset.click=r.offset.click,this!==s&&this._intersectsWith(this.containerCache)&&e.contains(s.element[0],this.element[0])&&(i=!1),i})),i?(s.isOver||(s.isOver=1,r._parent=n.helper.parent(),s.currentItem=n.helper.appendTo(s.element).data("ui-sortable-item",!0),s.options._helper=s.options.helper,s.options.helper=function(){return n.helper[0]},t.target=s.currentItem[0],s._mouseCapture(t,!0),s._mouseStart(t,!0,!0),s.offset.click.top=r.offset.click.top,s.offset.click.left=r.offset.click.left,s.offset.parent.left-=r.offset.parent.left-s.offset.parent.left,s.offset.parent.top-=r.offset.parent.top-s.offset.parent.top,r._trigger("toSortable",t),r.dropped=s.element,e.each(r.sortables,function(){this.refreshPositions()}),r.currentItem=r.element,s.fromOutside=r),s.currentItem&&(s._mouseDrag(t),n.position=s.position)):s.isOver&&(s.isOver=0,s.cancelHelperRemoval=!0,s.options._revert=s.options.revert,s.options.revert=!1,s._trigger("out",t,s._uiHash(s)),s._mouseStop(t,!0),s.options.revert=s.options._revert,s.options.helper=s.options._helper,s.placeholder&&s.placeholder.remove(),n.helper.appendTo(r._parent),r._refreshOffsets(t),n.position=r._generatePosition(t,!0),r._trigger("fromSortable",t),r.dropped=!1,e.each(r.sortables,function(){this.refreshPositions()}))})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,n,r){var i=e("body"),s=r.options;i.css("cursor")&&(s._cursor=i.css("cursor")),i.css("cursor",s.cursor)},stop:function(t,n,r){var i=r.options;i._cursor&&e("body").css("cursor",i._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n,r){var i=e(n.helper),s=r.options;i.css("opacity")&&(s._opacity=i.css("opacity")),i.css("opacity",s.opacity)},stop:function(t,n,r){var i=r.options;i._opacity&&e(n.helper).css("opacity",i._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(e,t,n){n.scrollParentNotHidden||(n.scrollParentNotHidden=n.helper.scrollParent(!1)),n.scrollParentNotHidden[0]!==n.document[0]&&n.scrollParentNotHidden[0].tagName!=="HTML"&&(n.overflowOffset=n.scrollParentNotHidden.offset())},drag:function(t,n,r){var i=r.options,s=!1,o=r.scrollParentNotHidden[0],u=r.document[0];if(o!==u&&o.tagName!=="HTML"){if(!i.axis||i.axis!=="x")r.overflowOffset.top+o.offsetHeight-t.pageY<i.scrollSensitivity?o.scrollTop=s=o.scrollTop+i.scrollSpeed:t.pageY-r.overflowOffset.top<i.scrollSensitivity&&(o.scrollTop=s=o.scrollTop-i.scrollSpeed);if(!i.axis||i.axis!=="y")r.overflowOffset.left+o.offsetWidth-t.pageX<i.scrollSensitivity?o.scrollLeft=s=o.scrollLeft+i.scrollSpeed:t.pageX-r.overflowOffset.left<i.scrollSensitivity&&(o.scrollLeft=s=o.scrollLeft-i.scrollSpeed)}else{if(!i.axis||i.axis!=="x")t.pageY-e(u).scrollTop()<i.scrollSensitivity?s=e(u).scrollTop(e(u).scrollTop()-i.scrollSpeed):e(window).height()-(t.pageY-e(u).scrollTop())<i.scrollSensitivity&&(s=e(u).scrollTop(e(u).scrollTop()+i.scrollSpeed));if(!i.axis||i.axis!=="y")t.pageX-e(u).scrollLeft()<i.scrollSensitivity?s=e(u).scrollLeft(e(u).scrollLeft()-i.scrollSpeed):e(window).width()-(t.pageX-e(u).scrollLeft())<i.scrollSensitivity&&(s=e(u).scrollLeft(e(u).scrollLeft()+i.scrollSpeed))}s!==!1&&e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(r,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,n,r){var i=r.options;r.snapElements=[],e(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var t=e(this),n=t.offset();this!==r.element[0]&&r.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:n.top,left:n.left})})},drag:function(t,n,r){var i,s,o,u,a,f,l,c,h,p,d=r.options,v=d.snapTolerance,m=n.offset.left,g=m+r.helperProportions.width,y=n.offset.top,b=y+r.helperProportions.height;for(h=r.snapElements.length-1;h>=0;h--){a=r.snapElements[h].left-r.margins.left,f=a+r.snapElements[h].width,l=r.snapElements[h].top-r.margins.top,c=l+r.snapElements[h].height;if(g<a-v||m>f+v||b<l-v||y>c+v||!e.contains(r.snapElements[h].item.ownerDocument,r.snapElements[h].item)){r.snapElements[h].snapping&&r.options.snap.release&&r.options.snap.release.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[h].item})),r.snapElements[h].snapping=!1;continue}d.snapMode!=="inner"&&(i=Math.abs(l-b)<=v,s=Math.abs(c-y)<=v,o=Math.abs(a-g)<=v,u=Math.abs(f-m)<=v,i&&(n.position.top=r._convertPositionTo("relative",{top:l-r.helperProportions.height,left:0}).top),s&&(n.position.top=r._convertPositionTo("relative",{top:c,left:0}).top),o&&(n.position.left=r._convertPositionTo("relative",{top:0,left:a-r.helperProportions.width}).left),u&&(n.position.left=r._convertPositionTo("relative",{top:0,left:f}).left)),p=i||s||o||u,d.snapMode!=="outer"&&(i=Math.abs(l-y)<=v,s=Math.abs(c-b)<=v,o=Math.abs(a-m)<=v,u=Math.abs(f-g)<=v,i&&(n.position.top=r._convertPositionTo("relative",{top:l,left:0}).top),s&&(n.position.top=r._convertPositionTo("relative",{top:c-r.helperProportions.height,left:0}).top),o&&(n.position.left=r._convertPositionTo("relative",{top:0,left:a}).left),u&&(n.position.left=r._convertPositionTo("relative",{top:0,left:f-r.helperProportions.width}).left)),!r.snapElements[h].snapping&&(i||s||o||u||p)&&r.options.snap.snap&&r.options.snap.snap.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[h].item})),r.snapElements[h].snapping=i||s||o||u||p}}}),e.ui.plugin.add("draggable","stack",{start:function(t,n,r){var i,s=r.options,o=e.makeArray(e(s.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!o.length)return;i=parseInt(e(o[0]).css("zIndex"),10)||0,e(o).each(function(t){e(this).css("zIndex",i+t)}),this.css("zIndex",i+o.length)}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n,r){var i=e(n.helper),s=r.options;i.css("zIndex")&&(s._zIndex=i.css("zIndex")),i.css("zIndex",s.zIndex)},stop:function(t,n,r){var i=r.options;i._zIndex&&e(n.helper).css("zIndex",i._zIndex)}}),e.ui.draggable});;
/*!
* jQuery UI Resizable 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/resizable/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery","./core","./mouse","./widget"],e):e(jQuery)})(function(e){return e.widget("ui.resizable",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(e){return parseInt(e,10)||0},_isNumber:function(e){return!isNaN(parseInt(e,10))},_hasScroll:function(t,n){if(e(t).css("overflow")==="hidden")return!1;var r=n&&n==="left"?"scrollLeft":"scrollTop",i=!1;return t[r]>0?!0:(t[r]=1,i=t[r]>0,t[r]=0,i)},_create:function(){var t,n,r,i,s,o=this,u=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!u.aspectRatio,aspectRatio:u.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:u.helper||u.ghost||u.animate?u.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(e("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=u.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=e();if(this.handles.constructor===String){this.handles==="all"&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={};for(n=0;n<t.length;n++)r=e.trim(t[n]),s="ui-resizable-"+r,i=e("<div class='ui-resizable-handle "+s+"'></div>"),i.css({zIndex:u.zIndex}),"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[r]=".ui-resizable-"+r,this.element.append(i)}this._renderAxis=function(t){var n,r,i,s;t=t||this.element;for(n in this.handles){if(this.handles[n].constructor===String)this.handles[n]=this.element.children(this.handles[n]).first().show();else if(this.handles[n].jquery||this.handles[n].nodeType)this.handles[n]=e(this.handles[n]),this._on(this.handles[n],{mousedown:o._mouseDown});this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(r=e(this.handles[n],this.element),s=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth(),i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize()),this._handles=this._handles.add(this.handles[n])}},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=i&&i[1]?i[1]:"se")}),u.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(u.disabled)return;e(this).removeClass("ui-resizable-autohide"),o._handles.show()}).mouseleave(function(){if(u.disabled)return;o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(n(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),n(this.originalElement),this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];if(r===t.target||e.contains(r,t.target))i=!0}return!this.options.disabled&&i},_mouseStart:function(t){var n,r,i,s=this.options,o=this.element;return this.resizing=!0,this._renderProxy(),n=this._num(this.helper.css("left")),r=this._num(this.helper.css("top")),s.containment&&(n+=e(s.containment).scrollLeft()||0,r+=e(s.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:n,top:r},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width(),height:o.height()},this.originalSize=this._helper?{width:o.outerWidth(),height:o.outerHeight()}:{width:o.width(),height:o.height()},this.sizeDiff={width:o.outerWidth()-o.width(),height:o.outerHeight()-o.height()},this.originalPosition={left:n,top:r},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof s.aspectRatio=="number"?s.aspectRatio:this.originalSize.width/this.originalSize.height||1,i=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor",i==="auto"?this.axis+"-resize":i),o.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var n,r,i=this.originalMousePosition,s=this.axis,o=t.pageX-i.left||0,u=t.pageY-i.top||0,a=this._change[s];this._updatePrevProperties();if(!a)return!1;n=a.apply(this,[t,o,u]),this._updateVirtualBoundaries(t.shiftKey);if(this._aspectRatio||t.shiftKey)n=this._updateRatio(n,t);return n=this._respectSize(n,t),this._updateCache(n),this._propagate("resize",t),r=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(r)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges()),!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,s,o,u,a,f=this.options,l=this;return this._helper&&(n=this._proportionallyResizeElements,r=n.length&&/textarea/i.test(n[0].nodeName),i=r&&this._hasScroll(n[0],"left")?0:l.sizeDiff.height,s=r?0:l.sizeDiff.width,o={width:l.helper.width()-s,height:l.helper.height()-i},u=parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left)||null,a=parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top)||null,f.animate||this.element.css(e.extend(o,{top:a,left:u})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!f.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var e={};return this.position.top!==this.prevPosition.top&&(e.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(e.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(e.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(e.height=this.size.height+"px"),this.helper.css(e),e},_updateVirtualBoundaries:function(e){var t,n,r,i,s,o=this.options;s={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:Infinity,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:Infinity};if(this._aspectRatio||e)t=s.minHeight*this.aspectRatio,r=s.minWidth/this.aspectRatio,n=s.maxHeight*this.aspectRatio,i=s.maxWidth/this.aspectRatio,t>s.minWidth&&(s.minWidth=t),r>s.minHeight&&(s.minHeight=r),n<s.maxWidth&&(s.maxWidth=n),i<s.maxHeight&&(s.maxHeight=i);this._vBoundaries=s},_updateCache:function(e){this.offset=this.helper.offset(),this._isNumber(e.left)&&(this.position.left=e.left),this._isNumber(e.top)&&(this.position.top=e.top),this._isNumber(e.height)&&(this.size.height=e.height),this._isNumber(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,n=this.size,r=this.axis;return this._isNumber(e.height)?e.width=e.height*this.aspectRatio:this._isNumber(e.width)&&(e.height=e.width/this.aspectRatio),r==="sw"&&(e.left=t.left+(n.width-e.width),e.top=null),r==="nw"&&(e.top=t.top+(n.height-e.height),e.left=t.left+(n.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,n=this.axis,r=this._isNumber(e.width)&&t.maxWidth&&t.maxWidth<e.width,i=this._isNumber(e.height)&&t.maxHeight&&t.maxHeight<e.height,s=this._isNumber(e.width)&&t.minWidth&&t.minWidth>e.width,o=this._isNumber(e.height)&&t.minHeight&&t.minHeight>e.height,u=this.originalPosition.left+this.originalSize.width,a=this.position.top+this.size.height,f=/sw|nw|w/.test(n),l=/nw|ne|n/.test(n);return s&&(e.width=t.minWidth),o&&(e.height=t.minHeight),r&&(e.width=t.maxWidth),i&&(e.height=t.maxHeight),s&&f&&(e.left=u-t.minWidth),r&&f&&(e.left=u-t.maxWidth),o&&l&&(e.top=a-t.minHeight),i&&l&&(e.top=a-t.maxHeight),!e.width&&!e.height&&!e.left&&e.top?e.top=null:!e.width&&!e.height&&!e.top&&e.left&&(e.left=null),e},_getPaddingPlusBorderDimensions:function(e){var t=0,n=[],r=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],i=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];for(;t<4;t++)n[t]=parseInt(r[t],10)||0,n[t]+=parseInt(i[t],10)||0;return{height:n[0]+n[2],width:n[1]+n[3]}},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length)return;var e,t=0,n=this.helper||this.element;for(;t<this._proportionallyResizeElements.length;t++)e=this._proportionallyResizeElements[t],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(e)),e.css({height:n.height()-this.outerDimensions.height||0,width:n.width()-this.outerDimensions.width||0})},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!=="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var n=e(this).resizable("instance"),r=n.options,i=n._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&n._hasScroll(i[0],"left")?0:n.sizeDiff.height,u=s?0:n.sizeDiff.width,a={width:n.size.width-u,height:n.size.height-o},f=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,l=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(a,l&&f?{top:l,left:f}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height}),n._updateCache(r),n._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,n,r,i,s,o,u,a=e(this).resizable("instance"),f=a.options,l=a.element,c=f.containment,h=c instanceof e?c.get(0):/parent/.test(c)?l.parent().get(0):c;if(!h)return;a.containerElement=e(h),/document/.test(c)||c===document?(a.containerOffset={left:0,top:0},a.containerPosition={left:0,top:0},a.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(h),n=[],e(["Top","Right","Left","Bottom"]).each(function(e,r){n[e]=a._num(t.css("padding"+r))}),a.containerOffset=t.offset(),a.containerPosition=t.position(),a.containerSize={height:t.innerHeight()-n[3],width:t.innerWidth()-n[1]},r=a.containerOffset,i=a.containerSize.height,s=a.containerSize.width,o=a._hasScroll(h,"left")?h.scrollWidth:s,u=a._hasScroll(h)?h.scrollHeight:i,a.parentData={element:h,left:r.left,top:r.top,width:o,height:u})},resize:function(t){var n,r,i,s,o=e(this).resizable("instance"),u=o.options,a=o.containerOffset,f=o.position,l=o._aspectRatio||t.shiftKey,c={top:0,left:0},h=o.containerElement,p=!0;h[0]!==document&&/static/.test(h.css("position"))&&(c=a),f.left<(o._helper?a.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-a.left:o.position.left-c.left),l&&(o.size.height=o.size.width/o.aspectRatio,p=!1),o.position.left=u.helper?a.left:0),f.top<(o._helper?a.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-a.top:o.position.top),l&&(o.size.width=o.size.height*o.aspectRatio,p=!1),o.position.top=o._helper?a.top:0),i=o.containerElement.get(0)===o.element.parent().get(0),s=/relative|absolute/.test(o.containerElement.css("position")),i&&s?(o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top):(o.offset.left=o.element.offset().left,o.offset.top=o.element.offset().top),n=Math.abs(o.sizeDiff.width+(o._helper?o.offset.left-c.left:o.offset.left-a.left)),r=Math.abs(o.sizeDiff.height+(o._helper?o.offset.top-c.top:o.offset.top-a.top)),n+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-n,l&&(o.size.height=o.size.width/o.aspectRatio,p=!1)),r+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-r,l&&(o.size.width=o.size.height*o.aspectRatio,p=!1)),p||(o.position.left=o.prevPosition.left,o.position.top=o.prevPosition.top,o.size.width=o.prevSize.width,o.size.height=o.prevSize.height)},stop:function(){var t=e(this).resizable("instance"),n=t.options,r=t.containerOffset,i=t.containerPosition,s=t.containerElement,o=e(t.helper),u=o.offset(),a=o.outerWidth()-t.sizeDiff.width,f=o.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f}),t._helper&&!n.animate&&/static/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).resizable("instance"),n=t.options;e(n.alsoResize).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})},resize:function(t,n){var r=e(this).resizable("instance"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0};e(i.alsoResize).each(function(){var t=e(this),r=e(this).data("ui-resizable-alsoresize"),i={},s=t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(s,function(e,t){var n=(r[t]||0)+(u[t]||0);n&&n>=0&&(i[t]=n||null)}),t.css(i)})},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).resizable("instance"),n=t.options,r=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof n.ghost=="string"?n.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t,n=e(this).resizable("instance"),r=n.options,i=n.size,s=n.originalSize,o=n.originalPosition,u=n.axis,a=typeof r.grid=="number"?[r.grid,r.grid]:r.grid,f=a[0]||1,l=a[1]||1,c=Math.round((i.width-s.width)/f)*f,h=Math.round((i.height-s.height)/l)*l,p=s.width+c,d=s.height+h,v=r.maxWidth&&r.maxWidth<p,m=r.maxHeight&&r.maxHeight<d,g=r.minWidth&&r.minWidth>p,y=r.minHeight&&r.minHeight>d;r.grid=a,g&&(p+=f),y&&(d+=l),v&&(p-=f),m&&(d-=l);if(/^(se|s|e)$/.test(u))n.size.width=p,n.size.height=d;else if(/^(ne)$/.test(u))n.size.width=p,n.size.height=d,n.position.top=o.top-h;else if(/^(sw)$/.test(u))n.size.width=p,n.size.height=d,n.position.left=o.left-c;else{if(d-l<=0||p-f<=0)t=n._getPaddingPlusBorderDimensions(this);d-l>0?(n.size.height=d,n.position.top=o.top-h):(d=l-t.height,n.size.height=d,n.position.top=o.top+s.height-d),p-f>0?(n.size.width=p,n.position.left=o.left-c):(p=f-t.width,n.size.width=p,n.position.left=o.left+s.width-p)}}}),e.ui.resizable});;
/*!
* jQuery UI Dialog 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/dialog/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery","./core","./widget","./button","./draggable","./mouse","./position","./resizable"],e):e(jQuery)})(function(e){return e.widget("ui.dialog",{version:"1.11.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"Close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var n=e(this).css(t).offset().top;n<0&&e(this).css("top",t.top-n)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var n,r=this;if(!this._isOpen||this._trigger("beforeClose",t)===!1)return;this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance();if(!this.opener.filter(":focusable").focus().length)try{n=this.document[0].activeElement,n&&n.nodeName.toLowerCase()!=="body"&&e(n).blur()}catch(i){}this._hide(this.uiDialog,this.options.hide,function(){r._trigger("close",t)})},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(t,n){var r=!1,i=this.uiDialog.siblings(".ui-front:visible").map(function(){return+e(this).css("z-index")}).get(),s=Math.max.apply(null,i);return s>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",s+1),r=!0),r&&!n&&this._trigger("focus",t),r},open:function(){var t=this;if(this._isOpen){this._moveToTop()&&this._focusTabbable();return}this._isOpen=!0,this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._makeFocusTarget(),this._trigger("open")},_focusTabbable:function(){var e=this._focusedElement;e||(e=this.element.find("[autofocus]")),e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function n(){var t=this.document[0].activeElement,n=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);n||this._focusTabbable()}t.preventDefault(),n.call(this),this._delay(n)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE){t.preventDefault(),this.close(t);return}if(t.keyCode!==e.ui.keyCode.TAB||t.isDefaultPrevented())return;var n=this.uiDialog.find(":tabbable"),r=n.filter(":first"),i=n.filter(":last");t.target!==i[0]&&t.target!==this.uiDialog[0]||!!t.shiftKey?(t.target===r[0]||t.target===this.uiDialog[0])&&t.shiftKey&&(this._delay(function(){i.focus()}),t.preventDefault()):(this._delay(function(){r.focus()}),t.preventDefault())},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html(" "),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,n=this.options.buttons;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty();if(e.isEmptyObject(n)||e.isArray(n)&&!n.length){this.uiDialog.removeClass("ui-dialog-buttons");return}e.each(n,function(n,r){var i,s;r=e.isFunction(r)?{click:r,text:n}:r,r=e.extend({type:"button"},r),i=r.click,r.click=function(){i.apply(t.element[0],arguments)},s={icons:r.icons,text:r.showText},delete r.icons,delete r.showText,e("<button></button>",r).button(s).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)},_makeDraggable:function(){function r(e){return{position:e.position,offset:e.offset}}var t=this,n=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(n,i){e(this).addClass("ui-dialog-dragging"),t._blockFrames(),t._trigger("dragStart",n,r(i))},drag:function(e,n){t._trigger("drag",e,r(n))},stop:function(i,s){var o=s.offset.left-t.document.scrollLeft(),u=s.offset.top-t.document.scrollTop();n.position={my:"left top",at:"left"+(o>=0?"+":"")+o+" "+"top"+(u>=0?"+":"")+u,of:t.window},e(this).removeClass("ui-dialog-dragging"),t._unblockFrames(),t._trigger("dragStop",i,r(s))}})},_makeResizable:function(){function o(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var t=this,n=this.options,r=n.resizable,i=this.uiDialog.css("position"),s=typeof r=="string"?r:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:n.maxWidth,maxHeight:n.maxHeight,minWidth:n.minWidth,minHeight:this._minHeight(),handles:s,start:function(n,r){e(this).addClass("ui-dialog-resizing"),t._blockFrames(),t._trigger("resizeStart",n,o(r))},resize:function(e,n){t._trigger("resize",e,o(n))},stop:function(r,i){var s=t.uiDialog.offset(),u=s.left-t.document.scrollLeft(),a=s.top-t.document.scrollTop();n.height=t.uiDialog.height(),n.width=t.uiDialog.width(),n.position={my:"left top",at:"left"+(u>=0?"+":"")+u+" "+"top"+(a>=0?"+":"")+a,of:t.window},e(this).removeClass("ui-dialog-resizing"),t._unblockFrames(),t._trigger("resizeStop",r,o(i))}}).css("position",i)},_trackFocus:function(){this._on(this.widget(),{focusin:function(t){this._makeFocusTarget(),this._focusedElement=e(t.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var t=this._trackingInstances(),n=e.inArray(this,t);n!==-1&&t.splice(n,1)},_trackingInstances:function(){var e=this.document.data("ui-dialog-instances");return e||(e=[],this.document.data("ui-dialog-instances",e)),e},_minHeight:function(){var e=this.options;return e.height==="auto"?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(t){var n=this,r=!1,i={};e.each(t,function(e,t){n._setOption(e,t),e in n.sizeRelatedOptions&&(r=!0),e in n.resizableRelatedOptions&&(i[e]=t)}),r&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",i)},_setOption:function(e,t){var n,r,i=this.uiDialog;e==="dialogClass"&&i.removeClass(this.options.dialogClass).addClass(t);if(e==="disabled")return;this._super(e,t),e==="appendTo"&&this.uiDialog.appendTo(this._appendTo()),e==="buttons"&&this._createButtons(),e==="closeText"&&this.uiDialogTitlebarClose.button({label:""+t}),e==="draggable"&&(n=i.is(":data(ui-draggable)"),n&&!t&&i.draggable("destroy"),!n&&t&&this._makeDraggable()),e==="position"&&this._position(),e==="resizable"&&(r=i.is(":data(ui-resizable)"),r&&!t&&i.resizable("destroy"),r&&typeof t=="string"&&i.resizable("option","handles",t),!r&&t!==!1&&this._makeResizable()),e==="title"&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title"))},_size:function(){var e,t,n,r=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),r.minWidth>r.width&&(r.width=r.minWidth),e=this.uiDialog.css({height:"auto",width:r.width}).outerHeight(),t=Math.max(0,r.minHeight-e),n=typeof r.maxHeight=="number"?Math.max(0,r.maxHeight-e):"none",r.height==="auto"?this.element.css({minHeight:t,maxHeight:n,height:"auto"}):this.element.height(Math.max(0,r.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=e(this);return e("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return e(t.target).closest(".ui-dialog").length?!0:!!e(t.target).closest(".ui-datepicker").length},_createOverlay:function(){if(!this.options.modal)return;var t=!0;this._delay(function(){t=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(e){if(t)return;this._allowInteraction(e)||(e.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=e("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)},_destroyOverlay:function(){if(!this.options.modal)return;if(this.overlay){var e=this.document.data("ui-dialog-overlays")-1;e?this.document.data("ui-dialog-overlays",e):this.document.unbind("focusin").removeData("ui-dialog-overlays"),this.overlay.remove(),this.overlay=null}}})});;
/**
* @file
* Dialog API inspired by HTML5 dialog element.
*
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#the-dialog-element
*/
(function ($, Drupal, drupalSettings) {
'use strict';
/**
* Default dialog options.
*
* @type {object}
*
* @prop {bool} [autoOpen=true]
* @prop {string} [dialogClass='']
* @prop {string} [buttonClass='button']
* @prop {string} [buttonPrimaryClass='button--primary']
* @prop {function} close
*/
drupalSettings.dialog = {
autoOpen: true,
dialogClass: '',
// Drupal-specific extensions: see dialog.jquery-ui.js.
buttonClass: 'button',
buttonPrimaryClass: 'button--primary',
// When using this API directly (when generating dialogs on the client
// side), you may want to override this method and do
// `jQuery(event.target).remove()` as well, to remove the dialog on
// closing.
close: function (event) {
Drupal.dialog(event.target).close();
Drupal.detachBehaviors(event.target, null, 'unload');
}
};
/**
* @typedef {object} Drupal.dialog~dialogDefinition
*
* @prop {boolean} open
* Is the dialog open or not.
* @prop {*} returnValue
* Return value of the dialog.
* @prop {function} show
* Method to display the dialog on the page.
* @prop {function} showModal
* Method to display the dialog as a modal on the page.
* @prop {function} close
* Method to hide the dialog from the page.
*/
/**
* Polyfill HTML5 dialog element with jQueryUI.
*
* @param {HTMLElement} element
* The element that holds the dialog.
* @param {object} options
* jQuery UI options to be passed to the dialog.
*
* @return {Drupal.dialog~dialogDefinition}
* The dialog instance.
*/
Drupal.dialog = function (element, options) {
var undef;
var $element = $(element);
var dialog = {
open: false,
returnValue: undef,
show: function () {
openDialog({modal: false});
},
showModal: function () {
openDialog({modal: true});
},
close: closeDialog
};
function openDialog(settings) {
settings = $.extend({}, drupalSettings.dialog, options, settings);
// Trigger a global event to allow scripts to bind events to the dialog.
$(window).trigger('dialog:beforecreate', [dialog, $element, settings]);
$element.dialog(settings);
dialog.open = true;
$(window).trigger('dialog:aftercreate', [dialog, $element, settings]);
}
function closeDialog(value) {
$(window).trigger('dialog:beforeclose', [dialog, $element]);
$element.dialog('close');
dialog.returnValue = value;
dialog.open = false;
$(window).trigger('dialog:afterclose', [dialog, $element]);
}
return dialog;
};
})(jQuery, Drupal, drupalSettings);
;
/**
* @file
* Positioning extensions for dialogs.
*/
/**
* Triggers when content inside a dialog changes.
*
* @event dialogContentResize
*/
(function ($, Drupal, drupalSettings, debounce, displace) {
'use strict';
// autoResize option will turn off resizable and draggable.
drupalSettings.dialog = $.extend({autoResize: true, maxHeight: '95%'}, drupalSettings.dialog);
/**
* Resets the current options for positioning.
*
* This is used as a window resize and scroll callback to reposition the
* jQuery UI dialog. Although not a built-in jQuery UI option, this can
* be disabled by setting autoResize: false in the options array when creating
* a new {@link Drupal.dialog}.
*
* @function Drupal.dialog~resetSize
*
* @param {jQuery.Event} event
* The event triggered.
*
* @fires event:dialogContentResize
*/
function resetSize(event) {
var positionOptions = ['width', 'height', 'minWidth', 'minHeight', 'maxHeight', 'maxWidth', 'position'];
var adjustedOptions = {};
var windowHeight = $(window).height();
var option;
var optionValue;
var adjustedValue;
for (var n = 0; n < positionOptions.length; n++) {
option = positionOptions[n];
optionValue = event.data.settings[option];
if (optionValue) {
// jQuery UI does not support percentages on heights, convert to pixels.
if (typeof optionValue === 'string' && /%$/.test(optionValue) && /height/i.test(option)) {
// Take offsets in account.
windowHeight -= displace.offsets.top + displace.offsets.bottom;
adjustedValue = parseInt(0.01 * parseInt(optionValue, 10) * windowHeight, 10);
// Don't force the dialog to be bigger vertically than needed.
if (option === 'height' && event.data.$element.parent().outerHeight() < adjustedValue) {
adjustedValue = 'auto';
}
adjustedOptions[option] = adjustedValue;
}
}
}
// Offset the dialog center to be at the center of Drupal.displace.offsets.
if (!event.data.settings.modal) {
adjustedOptions = resetPosition(adjustedOptions);
}
event.data.$element
.dialog('option', adjustedOptions)
.trigger('dialogContentResize');
}
/**
* Position the dialog's center at the center of displace.offsets boundaries.
*
* @function Drupal.dialog~resetPosition
*
* @param {object} options
* Options object.
*
* @return {object}
* Altered options object.
*/
function resetPosition(options) {
var offsets = displace.offsets;
var left = offsets.left - offsets.right;
var top = offsets.top - offsets.bottom;
var leftString = (left > 0 ? '+' : '-') + Math.abs(Math.round(left / 2)) + 'px';
var topString = (top > 0 ? '+' : '-') + Math.abs(Math.round(top / 2)) + 'px';
options.position = {
my: 'center' + (left !== 0 ? leftString : '') + ' center' + (top !== 0 ? topString : ''),
of: window
};
return options;
}
$(window).on({
'dialog:aftercreate': function (event, dialog, $element, settings) {
var autoResize = debounce(resetSize, 20);
var eventData = {settings: settings, $element: $element};
if (settings.autoResize === true || settings.autoResize === 'true') {
$element
.dialog('option', {resizable: false, draggable: false})
.dialog('widget').css('position', 'fixed');
$(window)
.on('resize.dialogResize scroll.dialogResize', eventData, autoResize)
.trigger('resize.dialogResize');
$(document).on('drupalViewportOffsetChange.dialogResize', eventData, autoResize);
}
},
'dialog:beforeclose': function (event, dialog, $element) {
$(window).off('.dialogResize');
$(document).off('.dialogResize');
}
});
})(jQuery, Drupal, drupalSettings, Drupal.debounce, Drupal.displace);
;
/**
* @file
* Adds default classes to buttons for styling purposes.
*/
(function ($) {
'use strict';
$.widget('ui.dialog', $.ui.dialog, {
options: {
buttonClass: 'button',
buttonPrimaryClass: 'button--primary'
},
_createButtons: function () {
var opts = this.options;
var primaryIndex;
var $buttons;
var index;
var il = opts.buttons.length;
for (index = 0; index < il; index++) {
if (opts.buttons[index].primary && opts.buttons[index].primary === true) {
primaryIndex = index;
delete opts.buttons[index].primary;
break;
}
}
this._super();
$buttons = this.uiButtonSet.children().addClass(opts.buttonClass);
if (typeof primaryIndex !== 'undefined') {
$buttons.eq(index).addClass(opts.buttonPrimaryClass);
}
}
});
})(jQuery);
;
/**
* @file
* Attaches behavior for the Quick Edit module.
*
* Everything happens asynchronously, to allow for:
* - dynamically rendered contextual links
* - asynchronously retrieved (and cached) per-field in-place editing metadata
* - asynchronous setup of in-place editable field and "Quick edit" link.
*
* To achieve this, there are several queues:
* - fieldsMetadataQueue: fields whose metadata still needs to be fetched.
* - fieldsAvailableQueue: queue of fields whose metadata is known, and for
* which it has been confirmed that the user has permission to edit them.
* However, FieldModels will only be created for them once there's a
* contextual link for their entity: when it's possible to initiate editing.
* - contextualLinksQueue: queue of contextual links on entities for which it
* is not yet known whether the user has permission to edit at >=1 of them.
*/
(function ($, _, Backbone, Drupal, drupalSettings, JSON, storage) {
'use strict';
var options = $.extend(drupalSettings.quickedit,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
quickEdit: Drupal.t('Quick edit')
}
}
);
/**
* Tracks fields without metadata. Contains objects with the following keys:
* - DOM el
* - String fieldID
* - String entityID
*/
var fieldsMetadataQueue = [];
/**
* Tracks fields ready for use. Contains objects with the following keys:
* - DOM el
* - String fieldID
* - String entityID
*/
var fieldsAvailableQueue = [];
/**
* Tracks contextual links on entities. Contains objects with the following
* keys:
* - String entityID
* - DOM el
* - DOM region
*/
var contextualLinksQueue = [];
/**
* Tracks how many instances exist for each unique entity. Contains key-value
* pairs:
* - String entityID
* - Number count
*/
var entityInstancesTracker = {};
/**
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.quickedit = {
attach: function (context) {
// Initialize the Quick Edit app once per page load.
$('body').once('quickedit-init').each(initQuickEdit);
// Find all in-place editable fields, if any.
var $fields = $(context).find('[data-quickedit-field-id]').once('quickedit');
if ($fields.length === 0) {
return;
}
// Process each entity element: identical entities that appear multiple
// times will get a numeric identifier, starting at 0.
$(context).find('[data-quickedit-entity-id]').once('quickedit').each(function (index, entityElement) {
processEntity(entityElement);
});
// Process each field element: queue to be used or to fetch metadata.
// When a field is being rerendered after editing, it will be processed
// immediately. New fields will be unable to be processed immediately,
// but will instead be queued to have their metadata fetched, which occurs
// below in fetchMissingMetaData().
$fields.each(function (index, fieldElement) {
processField(fieldElement);
});
// Entities and fields on the page have been detected, try to set up the
// contextual links for those entities that already have the necessary
// meta- data in the client-side cache.
contextualLinksQueue = _.filter(contextualLinksQueue, function (contextualLink) {
return !initializeEntityContextualLink(contextualLink);
});
// Fetch metadata for any fields that are queued to retrieve it.
fetchMissingMetadata(function (fieldElementsWithFreshMetadata) {
// Metadata has been fetched, reprocess fields whose metadata was
// missing.
_.each(fieldElementsWithFreshMetadata, processField);
// Metadata has been fetched, try to set up more contextual links now.
contextualLinksQueue = _.filter(contextualLinksQueue, function (contextualLink) {
return !initializeEntityContextualLink(contextualLink);
});
});
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
deleteContainedModelsAndQueues($(context));
}
}
};
/**
*
* @namespace
*/
Drupal.quickedit = {
/**
* A {@link Drupal.quickedit.AppView} instance.
*/
app: null,
/**
* @type {object}
*
* @prop {Array.<Drupal.quickedit.EntityModel>} entities
* @prop {Array.<Drupal.quickedit.FieldModel>} fields
*/
collections: {
// All in-place editable entities (Drupal.quickedit.EntityModel) on the
// page.
entities: null,
// All in-place editable fields (Drupal.quickedit.FieldModel) on the page.
fields: null
},
/**
* In-place editors will register themselves in this object.
*
* @namespace
*/
editors: {},
/**
* Per-field metadata that indicates whether in-place editing is allowed,
* which in-place editor should be used, etc.
*
* @namespace
*/
metadata: {
/**
* Check if a field exists in storage.
*
* @param {string} fieldID
* The field id to check.
*
* @return {bool}
* Whether it was found or not.
*/
has: function (fieldID) {
return storage.getItem(this._prefixFieldID(fieldID)) !== null;
},
/**
* Add metadata to a field id.
*
* @param {string} fieldID
* The field ID to add data to.
* @param {object} metadata
* Metadata to add.
*/
add: function (fieldID, metadata) {
storage.setItem(this._prefixFieldID(fieldID), JSON.stringify(metadata));
},
/**
* Get a key from a field id.
*
* @param {string} fieldID
* The field ID to check.
* @param {string} [key]
* The key to check. If empty, will return all metadata.
*
* @return {object|*}
* The value for the key, if defined. Otherwise will return all metadata
* for the specified field id.
*
*/
get: function (fieldID, key) {
var metadata = JSON.parse(storage.getItem(this._prefixFieldID(fieldID)));
return (typeof key === 'undefined') ? metadata : metadata[key];
},
/**
* Prefix the field id.
*
* @param {string} fieldID
* The field id to prefix.
*
* @return {string}
* A prefixed field id.
*/
_prefixFieldID: function (fieldID) {
return 'Drupal.quickedit.metadata.' + fieldID;
},
/**
* Unprefix the field id.
*
* @param {string} fieldID
* The field id to unprefix.
*
* @return {string}
* An unprefixed field id.
*/
_unprefixFieldID: function (fieldID) {
// Strip "Drupal.quickedit.metadata.", which is 26 characters long.
return fieldID.substring(26);
},
/**
* Intersection calculation.
*
* @param {Array} fieldIDs
* An array of field ids to compare to prefix field id.
*
* @return {Array}
* The intersection found.
*/
intersection: function (fieldIDs) {
var prefixedFieldIDs = _.map(fieldIDs, this._prefixFieldID);
var intersection = _.intersection(prefixedFieldIDs, _.keys(sessionStorage));
return _.map(intersection, this._unprefixFieldID);
}
}
};
// Clear the Quick Edit metadata cache whenever the current user's set of
// permissions changes.
var permissionsHashKey = Drupal.quickedit.metadata._prefixFieldID('permissionsHash');
var permissionsHashValue = storage.getItem(permissionsHashKey);
var permissionsHash = drupalSettings.user.permissionsHash;
if (permissionsHashValue !== permissionsHash) {
if (typeof permissionsHash === 'string') {
_.chain(storage).keys().each(function (key) {
if (key.substring(0, 26) === 'Drupal.quickedit.metadata.') {
storage.removeItem(key);
}
});
}
storage.setItem(permissionsHashKey, permissionsHash);
}
/**
* Detect contextual links on entities annotated by quickedit.
*
* Queue contextual links to be processed.
*
* @param {jQuery.Event} event
* The `drupalContextualLinkAdded` event.
* @param {object} data
* An object containing the data relevant to the event.
*
* @listens event:drupalContextualLinkAdded
*/
$(document).on('drupalContextualLinkAdded', function (event, data) {
if (data.$region.is('[data-quickedit-entity-id]')) {
// If the contextual link is cached on the client side, an entity instance
// will not yet have been assigned. So assign one.
if (!data.$region.is('[data-quickedit-entity-instance-id]')) {
data.$region.once('quickedit');
processEntity(data.$region.get(0));
}
var contextualLink = {
entityID: data.$region.attr('data-quickedit-entity-id'),
entityInstanceID: data.$region.attr('data-quickedit-entity-instance-id'),
el: data.$el[0],
region: data.$region[0]
};
// Set up contextual links for this, otherwise queue it to be set up
// later.
if (!initializeEntityContextualLink(contextualLink)) {
contextualLinksQueue.push(contextualLink);
}
}
});
/**
* Extracts the entity ID from a field ID.
*
* @param {string} fieldID
* A field ID: a string of the format
* `<entity type>/<id>/<field name>/<language>/<view mode>`.
*
* @return {string}
* An entity ID: a string of the format `<entity type>/<id>`.
*/
function extractEntityID(fieldID) {
return fieldID.split('/').slice(0, 2).join('/');
}
/**
* Initialize the Quick Edit app.
*
* @param {HTMLElement} bodyElement
* This document's body element.
*/
function initQuickEdit(bodyElement) {
Drupal.quickedit.collections.entities = new Drupal.quickedit.EntityCollection();
Drupal.quickedit.collections.fields = new Drupal.quickedit.FieldCollection();
// Instantiate AppModel (application state) and AppView, which is the
// controller of the whole in-place editing experience.
Drupal.quickedit.app = new Drupal.quickedit.AppView({
el: bodyElement,
model: new Drupal.quickedit.AppModel(),
entitiesCollection: Drupal.quickedit.collections.entities,
fieldsCollection: Drupal.quickedit.collections.fields
});
}
/**
* Assigns the entity an instance ID.
*
* @param {HTMLElement} entityElement
* A Drupal Entity API entity's DOM element with a data-quickedit-entity-id
* attribute.
*/
function processEntity(entityElement) {
var entityID = entityElement.getAttribute('data-quickedit-entity-id');
if (!entityInstancesTracker.hasOwnProperty(entityID)) {
entityInstancesTracker[entityID] = 0;
}
else {
entityInstancesTracker[entityID]++;
}
// Set the calculated entity instance ID for this element.
var entityInstanceID = entityInstancesTracker[entityID];
entityElement.setAttribute('data-quickedit-entity-instance-id', entityInstanceID);
}
/**
* Fetch the field's metadata; queue or initialize it (if EntityModel exists).
*
* @param {HTMLElement} fieldElement
* A Drupal Field API field's DOM element with a data-quickedit-field-id
* attribute.
*/
function processField(fieldElement) {
var metadata = Drupal.quickedit.metadata;
var fieldID = fieldElement.getAttribute('data-quickedit-field-id');
var entityID = extractEntityID(fieldID);
// Figure out the instance ID by looking at the ancestor
// [data-quickedit-entity-id] element's data-quickedit-entity-instance-id
// attribute.
var entityElementSelector = '[data-quickedit-entity-id="' + entityID + '"]';
var entityElement = $(fieldElement).closest(entityElementSelector);
// In the case of a full entity view page, the entity title is rendered
// outside of "the entity DOM node": it's rendered as the page title. So in
// this case, we find the lowest common parent element (deepest in the tree)
// and consider that the entity element.
if (entityElement.length === 0) {
var $lowestCommonParent = $(entityElementSelector).parents().has(fieldElement).first();
entityElement = $lowestCommonParent.find(entityElementSelector);
}
var entityInstanceID = entityElement
.get(0)
.getAttribute('data-quickedit-entity-instance-id');
// Early-return if metadata for this field is missing.
if (!metadata.has(fieldID)) {
fieldsMetadataQueue.push({
el: fieldElement,
fieldID: fieldID,
entityID: entityID,
entityInstanceID: entityInstanceID
});
return;
}
// Early-return if the user is not allowed to in-place edit this field.
if (metadata.get(fieldID, 'access') !== true) {
return;
}
// If an EntityModel for this field already exists (and hence also a "Quick
// edit" contextual link), then initialize it immediately.
if (Drupal.quickedit.collections.entities.findWhere({entityID: entityID, entityInstanceID: entityInstanceID})) {
initializeField(fieldElement, fieldID, entityID, entityInstanceID);
}
// Otherwise: queue the field. It is now available to be set up when its
// corresponding entity becomes in-place editable.
else {
fieldsAvailableQueue.push({el: fieldElement, fieldID: fieldID, entityID: entityID, entityInstanceID: entityInstanceID});
}
}
/**
* Initialize a field; create FieldModel.
*
* @param {HTMLElement} fieldElement
* The field's DOM element.
* @param {string} fieldID
* The field's ID.
* @param {string} entityID
* The field's entity's ID.
* @param {string} entityInstanceID
* The field's entity's instance ID.
*/
function initializeField(fieldElement, fieldID, entityID, entityInstanceID) {
var entity = Drupal.quickedit.collections.entities.findWhere({
entityID: entityID,
entityInstanceID: entityInstanceID
});
$(fieldElement).addClass('quickedit-field');
// The FieldModel stores the state of an in-place editable entity field.
var field = new Drupal.quickedit.FieldModel({
el: fieldElement,
fieldID: fieldID,
id: fieldID + '[' + entity.get('entityInstanceID') + ']',
entity: entity,
metadata: Drupal.quickedit.metadata.get(fieldID),
acceptStateChange: _.bind(Drupal.quickedit.app.acceptEditorStateChange, Drupal.quickedit.app)
});
// Track all fields on the page.
Drupal.quickedit.collections.fields.add(field);
}
/**
* Fetches metadata for fields whose metadata is missing.
*
* Fields whose metadata is missing are tracked at fieldsMetadataQueue.
*
* @param {function} callback
* A callback function that receives field elements whose metadata will just
* have been fetched.
*/
function fetchMissingMetadata(callback) {
if (fieldsMetadataQueue.length) {
var fieldIDs = _.pluck(fieldsMetadataQueue, 'fieldID');
var fieldElementsWithoutMetadata = _.pluck(fieldsMetadataQueue, 'el');
var entityIDs = _.uniq(_.pluck(fieldsMetadataQueue, 'entityID'), true);
// Ensure we only request entityIDs for which we don't have metadata yet.
entityIDs = _.difference(entityIDs, Drupal.quickedit.metadata.intersection(entityIDs));
fieldsMetadataQueue = [];
$.ajax({
url: Drupal.url('quickedit/metadata'),
type: 'POST',
data: {
'fields[]': fieldIDs,
'entities[]': entityIDs
},
dataType: 'json',
success: function (results) {
// Store the metadata.
_.each(results, function (fieldMetadata, fieldID) {
Drupal.quickedit.metadata.add(fieldID, fieldMetadata);
});
callback(fieldElementsWithoutMetadata);
}
});
}
}
/**
* Loads missing in-place editor's attachments (JavaScript and CSS files).
*
* Missing in-place editors are those whose fields are actively being used on
* the page but don't have.
*
* @param {function} callback
* Callback function to be called when the missing in-place editors (if any)
* have been inserted into the DOM. i.e. they may still be loading.
*/
function loadMissingEditors(callback) {
var loadedEditors = _.keys(Drupal.quickedit.editors);
var missingEditors = [];
Drupal.quickedit.collections.fields.each(function (fieldModel) {
var metadata = Drupal.quickedit.metadata.get(fieldModel.get('fieldID'));
if (metadata.access && _.indexOf(loadedEditors, metadata.editor) === -1) {
missingEditors.push(metadata.editor);
// Set a stub, to prevent subsequent calls to loadMissingEditors() from
// loading the same in-place editor again. Loading an in-place editor
// requires talking to a server, to download its JavaScript, then
// executing its JavaScript, and only then its Drupal.quickedit.editors
// entry will be set.
Drupal.quickedit.editors[metadata.editor] = false;
}
});
missingEditors = _.uniq(missingEditors);
if (missingEditors.length === 0) {
callback();
return;
}
// @see https://www.drupal.org/node/2029999.
// Create a Drupal.Ajax instance to load the form.
var loadEditorsAjax = Drupal.ajax({
url: Drupal.url('quickedit/attachments'),
submit: {'editors[]': missingEditors}
});
// Implement a scoped insert AJAX command: calls the callback after all AJAX
// command functions have been executed (hence the deferred calling).
var realInsert = Drupal.AjaxCommands.prototype.insert;
loadEditorsAjax.commands.insert = function (ajax, response, status) {
_.defer(callback);
realInsert(ajax, response, status);
};
// Trigger the AJAX request, which will should return AJAX commands to
// insert any missing attachments.
loadEditorsAjax.execute();
}
/**
* Attempts to set up a "Quick edit" link and corresponding EntityModel.
*
* @param {object} contextualLink
* An object with the following properties:
* - String entityID: a Quick Edit entity identifier, e.g. "node/1" or
* "block_content/5".
* - String entityInstanceID: a Quick Edit entity instance identifier,
* e.g. 0, 1 or n (depending on whether it's the first, second, or n+1st
* instance of this entity).
* - DOM el: element pointing to the contextual links placeholder for this
* entity.
* - DOM region: element pointing to the contextual region of this entity.
*
* @return {bool}
* Returns true when a contextual the given contextual link metadata can be
* removed from the queue (either because the contextual link has been set
* up or because it is certain that in-place editing is not allowed for any
* of its fields). Returns false otherwise.
*/
function initializeEntityContextualLink(contextualLink) {
var metadata = Drupal.quickedit.metadata;
// Check if the user has permission to edit at least one of them.
function hasFieldWithPermission(fieldIDs) {
for (var i = 0; i < fieldIDs.length; i++) {
var fieldID = fieldIDs[i];
if (metadata.get(fieldID, 'access') === true) {
return true;
}
}
return false;
}
// Checks if the metadata for all given field IDs exists.
function allMetadataExists(fieldIDs) {
return fieldIDs.length === metadata.intersection(fieldIDs).length;
}
// Find all fields for this entity instance and collect their field IDs.
var fields = _.where(fieldsAvailableQueue, {
entityID: contextualLink.entityID,
entityInstanceID: contextualLink.entityInstanceID
});
var fieldIDs = _.pluck(fields, 'fieldID');
// No fields found yet.
if (fieldIDs.length === 0) {
return false;
}
// The entity for the given contextual link contains at least one field that
// the current user may edit in-place; instantiate EntityModel,
// EntityDecorationView and ContextualLinkView.
else if (hasFieldWithPermission(fieldIDs)) {
var entityModel = new Drupal.quickedit.EntityModel({
el: contextualLink.region,
entityID: contextualLink.entityID,
entityInstanceID: contextualLink.entityInstanceID,
id: contextualLink.entityID + '[' + contextualLink.entityInstanceID + ']',
label: Drupal.quickedit.metadata.get(contextualLink.entityID, 'label')
});
Drupal.quickedit.collections.entities.add(entityModel);
// Create an EntityDecorationView associated with the root DOM node of the
// entity.
var entityDecorationView = new Drupal.quickedit.EntityDecorationView({
el: contextualLink.region,
model: entityModel
});
entityModel.set('entityDecorationView', entityDecorationView);
// Initialize all queued fields within this entity (creates FieldModels).
_.each(fields, function (field) {
initializeField(field.el, field.fieldID, contextualLink.entityID, contextualLink.entityInstanceID);
});
fieldsAvailableQueue = _.difference(fieldsAvailableQueue, fields);
// Initialization should only be called once. Use Underscore's once method
// to get a one-time use version of the function.
var initContextualLink = _.once(function () {
var $links = $(contextualLink.el).find('.contextual-links');
var contextualLinkView = new Drupal.quickedit.ContextualLinkView($.extend({
el: $('<li class="quickedit"><a href="" role="button" aria-pressed="false"></a></li>').prependTo($links),
model: entityModel,
appModel: Drupal.quickedit.app.model
}, options));
entityModel.set('contextualLinkView', contextualLinkView);
});
// Set up ContextualLinkView after loading any missing in-place editors.
loadMissingEditors(initContextualLink);
return true;
}
// There was not at least one field that the current user may edit in-place,
// even though the metadata for all fields within this entity is available.
else if (allMetadataExists(fieldIDs)) {
return true;
}
return false;
}
/**
* Delete models and queue items that are contained within a given context.
*
* Deletes any contained EntityModels (plus their associated FieldModels and
* ContextualLinkView) and FieldModels, as well as the corresponding queues.
*
* After EntityModels, FieldModels must also be deleted, because it is
* possible in Drupal for a field DOM element to exist outside of the entity
* DOM element, e.g. when viewing the full node, the title of the node is not
* rendered within the node (the entity) but as the page title.
*
* Note: this will not delete an entity that is actively being in-place
* edited.
*
* @param {jQuery} $context
* The context within which to delete.
*/
function deleteContainedModelsAndQueues($context) {
$context.find('[data-quickedit-entity-id]').addBack('[data-quickedit-entity-id]').each(function (index, entityElement) {
// Delete entity model.
var entityModel = Drupal.quickedit.collections.entities.findWhere({el: entityElement});
if (entityModel) {
var contextualLinkView = entityModel.get('contextualLinkView');
contextualLinkView.undelegateEvents();
contextualLinkView.remove();
// Remove the EntityDecorationView.
entityModel.get('entityDecorationView').remove();
// Destroy the EntityModel; this will also destroy its FieldModels.
entityModel.destroy();
}
// Filter queue.
function hasOtherRegion(contextualLink) {
return contextualLink.region !== entityElement;
}
contextualLinksQueue = _.filter(contextualLinksQueue, hasOtherRegion);
});
$context.find('[data-quickedit-field-id]').addBack('[data-quickedit-field-id]').each(function (index, fieldElement) {
// Delete field models.
Drupal.quickedit.collections.fields.chain()
.filter(function (fieldModel) { return fieldModel.get('el') === fieldElement; })
.invoke('destroy');
// Filter queues.
function hasOtherFieldElement(field) {
return field.el !== fieldElement;
}
fieldsMetadataQueue = _.filter(fieldsMetadataQueue, hasOtherFieldElement);
fieldsAvailableQueue = _.filter(fieldsAvailableQueue, hasOtherFieldElement);
});
}
})(jQuery, _, Backbone, Drupal, drupalSettings, window.JSON, window.sessionStorage);
;
/**
* @file
* Provides utility functions for Quick Edit.
*/
(function ($, Drupal) {
'use strict';
/**
* @namespace
*/
Drupal.quickedit.util = Drupal.quickedit.util || {};
/**
* @namespace
*/
Drupal.quickedit.util.constants = {};
/**
*
* @type {string}
*/
Drupal.quickedit.util.constants.transitionEnd = 'transitionEnd.quickedit webkitTransitionEnd.quickedit transitionend.quickedit msTransitionEnd.quickedit oTransitionEnd.quickedit';
/**
* Converts a field id into a formatted url path.
*
* @example
* Drupal.quickedit.util.buildUrl(
* 'node/1/body/und/full',
* '/quickedit/form/!entity_type/!id/!field_name/!langcode/!view_mode'
* );
*
* @param {string} id
* The id of an editable field.
* @param {string} urlFormat
* The Controller route for field processing.
*
* @return {string}
* The formatted URL.
*/
Drupal.quickedit.util.buildUrl = function (id, urlFormat) {
var parts = id.split('/');
return Drupal.formatString(decodeURIComponent(urlFormat), {
'!entity_type': parts[0],
'!id': parts[1],
'!field_name': parts[2],
'!langcode': parts[3],
'!view_mode': parts[4]
});
};
/**
* Shows a network error modal dialog.
*
* @param {string} title
* The title to use in the modal dialog.
* @param {string} message
* The message to use in the modal dialog.
*/
Drupal.quickedit.util.networkErrorModal = function (title, message) {
var $message = $('<div>' + message + '</div>');
var networkErrorModal = Drupal.dialog($message.get(0), {
title: title,
dialogClass: 'quickedit-network-error',
buttons: [
{
text: Drupal.t('OK'),
click: function () {
networkErrorModal.close();
},
primary: true
}
],
create: function () {
$(this).parent().find('.ui-dialog-titlebar-close').remove();
},
close: function (event) {
// Automatically destroy the DOM element that was used for the dialog.
$(event.target).remove();
}
});
networkErrorModal.showModal();
};
/**
* @namespace
*/
Drupal.quickedit.util.form = {
/**
* Loads a form, calls a callback to insert.
*
* Leverages {@link Drupal.Ajax}' ability to have scoped (per-instance)
* command implementations to be able to call a callback.
*
* @param {object} options
* An object with the following keys:
* @param {string} options.fieldID
* The field ID that uniquely identifies the field for which this form
* will be loaded.
* @param {bool} options.nocssjs
* Boolean indicating whether no CSS and JS should be returned (necessary
* when the form is invisible to the user).
* @param {bool} options.reset
* Boolean indicating whether the data stored for this field's entity in
* PrivateTempStore should be used or reset.
* @param {function} callback
* A callback function that will receive the form to be inserted, as well
* as the ajax object, necessary if the callback wants to perform other
* Ajax commands.
*/
load: function (options, callback) {
var fieldID = options.fieldID;
// Create a Drupal.ajax instance to load the form.
var formLoaderAjax = Drupal.ajax({
url: Drupal.quickedit.util.buildUrl(fieldID, Drupal.url('quickedit/form/!entity_type/!id/!field_name/!langcode/!view_mode')),
submit: {
nocssjs: options.nocssjs,
reset: options.reset
},
error: function (xhr, url) {
// Show a modal to inform the user of the network error.
var fieldLabel = Drupal.quickedit.metadata.get(fieldID, 'label');
var message = Drupal.t('Could not load the form for <q>@field-label</q>, either due to a website problem or a network connection problem.<br>Please try again.', {'@field-label': fieldLabel});
Drupal.quickedit.util.networkErrorModal(Drupal.t('Network problem!'), message);
// Change the state back to "candidate", to allow the user to start
// in-place editing of the field again.
var fieldModel = Drupal.quickedit.app.model.get('activeField');
fieldModel.set('state', 'candidate');
}
});
// Implement a scoped quickeditFieldForm AJAX command: calls the callback.
formLoaderAjax.commands.quickeditFieldForm = function (ajax, response, status) {
callback(response.data, ajax);
Drupal.ajax.instances[this.instanceIndex] = null;
};
// This will ensure our scoped quickeditFieldForm AJAX command gets
// called.
formLoaderAjax.execute();
},
/**
* Creates a {@link Drupal.Ajax} instance that is used to save a form.
*
* @param {object} options
* Submit options to the form.
* @param {bool} options.nocssjs
* Boolean indicating whether no CSS and JS should be returned (necessary
* when the form is invisible to the user).
* @param {Array.<string>} options.other_view_modes
* Array containing view mode IDs (of other instances of this field on the
* page).
* @param {jQuery} $submit
* The submit element.
*
* @return {Drupal.Ajax}
* A {@link Drupal.Ajax} instance.
*/
ajaxifySaving: function (options, $submit) {
// Re-wire the form to handle submit.
var settings = {
url: $submit.closest('form').attr('action'),
setClick: true,
event: 'click.quickedit',
progress: false,
submit: {
nocssjs: options.nocssjs,
other_view_modes: options.other_view_modes
},
/**
* Reimplement the success handler.
*
* Ensure {@link Drupal.attachBehaviors} does not get called on the
* form.
*
* @param {Drupal.AjaxCommands~commandDefinition} response
* The Drupal AJAX response.
* @param {number} [status]
* The HTTP status code.
*/
success: function (response, status) {
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
}
}
},
base: $submit.attr('id'),
element: $submit[0]
};
return Drupal.ajax(settings);
},
/**
* Cleans up the {@link Drupal.Ajax} instance that is used to save the form.
*
* @param {Drupal.Ajax} ajax
* A {@link Drupal.Ajax} instance that was returned by
* {@link Drupal.quickedit.form.ajaxifySaving}.
*/
unajaxifySaving: function (ajax) {
$(ajax.element).off('click.quickedit');
}
};
})(jQuery, Drupal);
;
/**
* @file
* A Backbone Model subclass that enforces validation when calling set().
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.quickedit.BaseModel = Backbone.Model.extend(/** @lends Drupal.quickedit.BaseModel# */{
/**
* @constructs
*
* @augments Backbone.Model
*
* @param {object} options
* Options for the base model-
*
* @return {Drupal.quickedit.BaseModel}
* A quickedit base model.
*/
initialize: function (options) {
this.__initialized = true;
return Backbone.Model.prototype.initialize.call(this, options);
},
/**
* Set a value on the model
*
* @param {object|string} key
* The key to set a value for.
* @param {*} val
* The value to set.
* @param {object} [options]
* Options for the model.
*
* @return {*}
* The result of `Backbone.Model.prototype.set` with the specified
* parameters.
*/
set: function (key, val, options) {
if (this.__initialized) {
// Deal with both the "key", value and {key:value}-style arguments.
if (typeof key === 'object') {
key.validate = true;
}
else {
if (!options) {
options = {};
}
options.validate = true;
}
}
return Backbone.Model.prototype.set.call(this, key, val, options);
}
});
}(Drupal, Backbone));
;
/**
* @file
* A Backbone Model for the state of the in-place editing application.
*
* @see Drupal.quickedit.AppView
*/
(function (Backbone, Drupal) {
'use strict';
/**
* @constructor
*
* @augments Backbone.Model
*/
Drupal.quickedit.AppModel = Backbone.Model.extend(/** @lends Drupal.quickedit.AppModel# */{
/**
* @type {object}
*
* @prop {Drupal.quickedit.FieldModel} highlightedField
* @prop {Drupal.quickedit.FieldModel} activeField
* @prop {Drupal.dialog~dialogDefinition} activeModal
*/
defaults: /** @lends Drupal.quickedit.AppModel# */{
/**
* The currently state='highlighted' Drupal.quickedit.FieldModel, if any.
*
* @type {Drupal.quickedit.FieldModel}
*
* @see Drupal.quickedit.FieldModel.states
*/
highlightedField: null,
/**
* The currently state = 'active' Drupal.quickedit.FieldModel, if any.
*
* @type {Drupal.quickedit.FieldModel}
*
* @see Drupal.quickedit.FieldModel.states
*/
activeField: null,
/**
* Reference to a {@link Drupal.dialog} instance if a state change
* requires confirmation.
*
* @type {Drupal.dialog~dialogDefinition}
*/
activeModal: null
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the state of an in-place editable entity in the DOM.
*/
(function (_, $, Backbone, Drupal) {
'use strict';
Drupal.quickedit.EntityModel = Drupal.quickedit.BaseModel.extend(/** @lends Drupal.quickedit.EntityModel# */{
/**
* @type {object}
*/
defaults: /** @lends Drupal.quickedit.EntityModel# */{
/**
* The DOM element that represents this entity.
*
* It may seem bizarre to have a DOM element in a Backbone Model, but we
* need to be able to map entities in the DOM to EntityModels in memory.
*
* @type {HTMLElement}
*/
el: null,
/**
* An entity ID, of the form `<entity type>/<entity ID>`
*
* @example
* "node/1"
*
* @type {string}
*/
entityID: null,
/**
* An entity instance ID.
*
* The first instance of a specific entity (i.e. with a given entity ID)
* is assigned 0, the second 1, and so on.
*
* @type {number}
*/
entityInstanceID: null,
/**
* The unique ID of this entity instance on the page, of the form
* `<entity type>/<entity ID>[entity instance ID]`
*
* @example
* "node/1[0]"
*
* @type {string}
*/
id: null,
/**
* The label of the entity.
*
* @type {string}
*/
label: null,
/**
* A FieldCollection for all fields of the entity.
*
* @type {Drupal.quickedit.FieldCollection}
*
* @see Drupal.quickedit.FieldCollection
*/
fields: null,
// The attributes below are stateful. The ones above will never change
// during the life of a EntityModel instance.
/**
* Indicates whether this entity is currently being edited in-place.
*
* @type {bool}
*/
isActive: false,
/**
* Whether one or more fields are already been stored in PrivateTempStore.
*
* @type {bool}
*/
inTempStore: false,
/**
* Indicates whether a "Save" button is necessary or not.
*
* Whether one or more fields have already been stored in PrivateTempStore
* *or* the field that's currently being edited is in the 'changed' or a
* later state.
*
* @type {bool}
*/
isDirty: false,
/**
* Whether the request to the server has been made to commit this entity.
*
* Used to prevent multiple such requests.
*
* @type {bool}
*/
isCommitting: false,
/**
* The current processing state of an entity.
*
* @type {string}
*/
state: 'closed',
/**
* IDs of fields whose new values have been stored in PrivateTempStore.
*
* We must store this on the EntityModel as well (even though it already
* is on the FieldModel) because when a field is rerendered, its
* FieldModel is destroyed and this allows us to transition it back to
* the proper state.
*
* @type {Array.<string>}
*/
fieldsInTempStore: [],
/**
* A flag the tells the application that this EntityModel must be reloaded
* in order to restore the original values to its fields in the client.
*
* @type {bool}
*/
reload: false
},
/**
* @constructs
*
* @augments Drupal.quickedit.BaseModel
*/
initialize: function () {
this.set('fields', new Drupal.quickedit.FieldCollection());
// Respond to entity state changes.
this.listenTo(this, 'change:state', this.stateChange);
// The state of the entity is largely dependent on the state of its
// fields.
this.listenTo(this.get('fields'), 'change:state', this.fieldStateChange);
// Call Drupal.quickedit.BaseModel's initialize() method.
Drupal.quickedit.BaseModel.prototype.initialize.call(this);
},
/**
* Updates FieldModels' states when an EntityModel change occurs.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* The entity model
* @param {string} state
* The state of the associated entity. One of
* {@link Drupal.quickedit.EntityModel.states}.
* @param {object} options
* Options for the entity model.
*/
stateChange: function (entityModel, state, options) {
var to = state;
switch (to) {
case 'closed':
this.set({
isActive: false,
inTempStore: false,
isDirty: false
});
break;
case 'launching':
break;
case 'opening':
// Set the fields to candidate state.
entityModel.get('fields').each(function (fieldModel) {
fieldModel.set('state', 'candidate', options);
});
break;
case 'opened':
// The entity is now ready for editing!
this.set('isActive', true);
break;
case 'committing':
// The user indicated they want to save the entity.
var fields = this.get('fields');
// For fields that are in an active state, transition them to
// candidate.
fields.chain()
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['active']).length;
})
.each(function (fieldModel) {
fieldModel.set('state', 'candidate');
});
// For fields that are in a changed state, field values must first be
// stored in PrivateTempStore.
fields.chain()
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], Drupal.quickedit.app.changedFieldStates).length;
})
.each(function (fieldModel) {
fieldModel.set('state', 'saving');
});
break;
case 'deactivating':
var changedFields = this.get('fields')
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['changed', 'invalid']).length;
});
// If the entity contains unconfirmed or unsaved changes, return the
// entity to an opened state and ask the user if they would like to
// save the changes or discard the changes.
// 1. One of the fields is in a changed state. The changed field
// might just be a change in the client or it might have been saved
// to tempstore.
// 2. The saved flag is empty and the confirmed flag is empty. If
// the entity has been saved to the server, the fields changed in
// the client are irrelevant. If the changes are confirmed, then
// proceed to set the fields to candidate state.
if ((changedFields.length || this.get('fieldsInTempStore').length) && (!options.saved && !options.confirmed)) {
// Cancel deactivation until the user confirms save or discard.
this.set('state', 'opened', {confirming: true});
// An action in reaction to state change must be deferred.
_.defer(function () {
Drupal.quickedit.app.confirmEntityDeactivation(entityModel);
});
}
else {
var invalidFields = this.get('fields')
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['invalid']).length;
});
// Indicate if this EntityModel needs to be reloaded in order to
// restore the original values of its fields.
entityModel.set('reload', (this.get('fieldsInTempStore').length || invalidFields.length));
// Set all fields to the 'candidate' state. A changed field may have
// to go through confirmation first.
entityModel.get('fields').each(function (fieldModel) {
// If the field is already in the candidate state, trigger a
// change event so that the entityModel can move to the next state
// in deactivation.
if (_.intersection([fieldModel.get('state')], ['candidate', 'highlighted']).length) {
fieldModel.trigger('change:state', fieldModel, fieldModel.get('state'), options);
}
else {
fieldModel.set('state', 'candidate', options);
}
});
}
break;
case 'closing':
// Set all fields to the 'inactive' state.
options.reason = 'stop';
this.get('fields').each(function (fieldModel) {
fieldModel.set({
inTempStore: false,
state: 'inactive'
}, options);
});
break;
}
},
/**
* Updates a Field and Entity model's "inTempStore" when appropriate.
*
* Helper function.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* The model of the entity for which a field's state attribute has
* changed.
* @param {Drupal.quickedit.FieldModel} fieldModel
* The model of the field whose state attribute has changed.
*
* @see Drupal.quickedit.EntityModel#fieldStateChange
*/
_updateInTempStoreAttributes: function (entityModel, fieldModel) {
var current = fieldModel.get('state');
var previous = fieldModel.previous('state');
var fieldsInTempStore = entityModel.get('fieldsInTempStore');
// If the fieldModel changed to the 'saved' state: remember that this
// field was saved to PrivateTempStore.
if (current === 'saved') {
// Mark the entity as saved in PrivateTempStore, so that we can pass the
// proper "reset PrivateTempStore" boolean value when communicating with
// the server.
entityModel.set('inTempStore', true);
// Mark the field as saved in PrivateTempStore, so that visual
// indicators signifying just that may be rendered.
fieldModel.set('inTempStore', true);
// Remember that this field is in PrivateTempStore, restore when
// rerendered.
fieldsInTempStore.push(fieldModel.get('fieldID'));
fieldsInTempStore = _.uniq(fieldsInTempStore);
entityModel.set('fieldsInTempStore', fieldsInTempStore);
}
// If the fieldModel changed to the 'candidate' state from the
// 'inactive' state, then this is a field for this entity that got
// rerendered. Restore its previous 'inTempStore' attribute value.
else if (current === 'candidate' && previous === 'inactive') {
fieldModel.set('inTempStore', _.intersection([fieldModel.get('fieldID')], fieldsInTempStore).length > 0);
}
},
/**
* Reacts to state changes in this entity's fields.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The model of the field whose state attribute changed.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
fieldStateChange: function (fieldModel, state) {
var entityModel = this;
var fieldState = state;
// Switch on the entityModel state.
// The EntityModel responds to FieldModel state changes as a function of
// its state. For example, a field switching back to 'candidate' state
// when its entity is in the 'opened' state has no effect on the entity.
// But that same switch back to 'candidate' state of a field when the
// entity is in the 'committing' state might allow the entity to proceed
// with the commit flow.
switch (this.get('state')) {
case 'closed':
case 'launching':
// It should be impossible to reach these: fields can't change state
// while the entity is closed or still launching.
break;
case 'opening':
// We must change the entity to the 'opened' state, but it must first
// be confirmed that all of its fieldModels have transitioned to the
// 'candidate' state.
// We do this here, because this is called every time a fieldModel
// changes state, hence each time this is called, we get closer to the
// goal of having all fieldModels in the 'candidate' state.
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'opened', {
'accept-field-states': Drupal.quickedit.app.readyFieldStates
});
});
break;
case 'opened':
// Set the isDirty attribute when appropriate so that it is known when
// to display the "Save" button in the entity toolbar.
// Note that once a field has been changed, there's no way to discard
// that change, hence it will have to be saved into PrivateTempStore,
// or the in-place editing of this field will have to be stopped
// completely. In other words: once any field enters the 'changed'
// field, then for the remainder of the in-place editing session, the
// entity is by definition dirty.
if (fieldState === 'changed') {
entityModel.set('isDirty', true);
}
else {
this._updateInTempStoreAttributes(entityModel, fieldModel);
}
break;
case 'committing':
// If the field save returned a validation error, set the state of the
// entity back to 'opened'.
if (fieldState === 'invalid') {
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'opened', {reason: 'invalid'});
});
}
else {
this._updateInTempStoreAttributes(entityModel, fieldModel);
}
// Attempt to save the entity. If the entity's fields are not yet all
// in a ready state, the save will not be processed.
var options = {
'accept-field-states': Drupal.quickedit.app.readyFieldStates
};
if (entityModel.set('isCommitting', true, options)) {
entityModel.save({
success: function () {
entityModel.set({
state: 'deactivating',
isCommitting: false
}, {saved: true});
},
error: function () {
// Reset the "isCommitting" mutex.
entityModel.set('isCommitting', false);
// Change the state back to "opened", to allow the user to hit
// the "Save" button again.
entityModel.set('state', 'opened', {reason: 'networkerror'});
// Show a modal to inform the user of the network error.
var message = Drupal.t('Your changes to <q>@entity-title</q> could not be saved, either due to a website problem or a network connection problem.<br>Please try again.', {'@entity-title': entityModel.get('label')});
Drupal.quickedit.util.networkErrorModal(Drupal.t('Network problem!'), message);
}
});
}
break;
case 'deactivating':
// When setting the entity to 'closing', require that all fieldModels
// are in either the 'candidate' or 'highlighted' state.
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'closing', {
'accept-field-states': Drupal.quickedit.app.readyFieldStates
});
});
break;
case 'closing':
// When setting the entity to 'closed', require that all fieldModels
// are in the 'inactive' state.
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'closed', {
'accept-field-states': ['inactive']
});
});
break;
}
},
/**
* Fires an AJAX request to the REST save URL for an entity.
*
* @param {object} options
* An object of options that contains:
* @param {function} [options.success]
* A function to invoke if the entity is successfully saved.
*/
save: function (options) {
var entityModel = this;
// Create a Drupal.ajax instance to save the entity.
var entitySaverAjax = Drupal.ajax({
url: Drupal.url('quickedit/entity/' + entityModel.get('entityID')),
error: function () {
// Let the Drupal.quickedit.EntityModel Backbone model's error()
// method handle errors.
options.error.call(entityModel);
}
});
// Entity saved successfully.
entitySaverAjax.commands.quickeditEntitySaved = function (ajax, response, status) {
// All fields have been moved from PrivateTempStore to permanent
// storage, update the "inTempStore" attribute on FieldModels, on the
// EntityModel and clear EntityModel's "fieldInTempStore" attribute.
entityModel.get('fields').each(function (fieldModel) {
fieldModel.set('inTempStore', false);
});
entityModel.set('inTempStore', false);
entityModel.set('fieldsInTempStore', []);
// Invoke the optional success callback.
if (options.success) {
options.success.call(entityModel);
}
};
// Trigger the AJAX request, which will will return the
// quickeditEntitySaved AJAX command to which we then react.
entitySaverAjax.execute();
},
/**
* Validate the entity model.
*
* @param {object} attrs
* The attributes changes in the save or set call.
* @param {object} options
* An object with the following option:
* @param {string} [options.reason]
* A string that conveys a particular reason to allow for an exceptional
* state change.
* @param {Array} options.accept-field-states
* An array of strings that represent field states that the entities must
* be in to validate. For example, if `accept-field-states` is
* `['candidate', 'highlighted']`, then all the fields of the entity must
* be in either of these two states for the save or set call to
* validate and proceed.
*
* @return {string}
* A string to say something about the state of the entity model.
*/
validate: function (attrs, options) {
var acceptedFieldStates = options['accept-field-states'] || [];
// Validate state change.
var currentState = this.get('state');
var nextState = attrs.state;
if (currentState !== nextState) {
// Ensure it's a valid state.
if (_.indexOf(this.constructor.states, nextState) === -1) {
return '"' + nextState + '" is an invalid state';
}
// Ensure it's a state change that is allowed.
// Check if the acceptStateChange function accepts it.
if (!this._acceptStateChange(currentState, nextState, options)) {
return 'state change not accepted';
}
// If that function accepts it, then ensure all fields are also in an
// acceptable state.
else if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) {
return 'state change not accepted because fields are not in acceptable state';
}
}
// Validate setting isCommitting = true.
var currentIsCommitting = this.get('isCommitting');
var nextIsCommitting = attrs.isCommitting;
if (currentIsCommitting === false && nextIsCommitting === true) {
if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) {
return 'isCommitting change not accepted because fields are not in acceptable state';
}
}
else if (currentIsCommitting === true && nextIsCommitting === true) {
return 'isCommitting is a mutex, hence only changes are allowed';
}
},
/**
* Checks if a state change can be accepted.
*
* @param {string} from
* From state.
* @param {string} to
* To state.
* @param {object} context
* Context for the check.
* @param {string} context.reason
* The reason for the state change.
* @param {bool} context.confirming
* Whether context is confirming or not.
*
* @return {bool}
* Whether the state change is accepted or not.
*
* @see Drupal.quickedit.AppView#acceptEditorStateChange
*/
_acceptStateChange: function (from, to, context) {
var accept = true;
// In general, enforce the states sequence. Disallow going back from a
// "later" state to an "earlier" state, except in explicitly allowed
// cases.
if (!this.constructor.followsStateSequence(from, to)) {
accept = false;
// Allow: closing -> closed.
// Necessary to stop editing an entity.
if (from === 'closing' && to === 'closed') {
accept = true;
}
// Allow: committing -> opened.
// Necessary to be able to correct an invalid field, or to hit the
// "Save" button again after a server/network error.
else if (from === 'committing' && to === 'opened' && context.reason && (context.reason === 'invalid' || context.reason === 'networkerror')) {
accept = true;
}
// Allow: deactivating -> opened.
// Necessary to be able to confirm changes with the user.
else if (from === 'deactivating' && to === 'opened' && context.confirming) {
accept = true;
}
// Allow: opened -> deactivating.
// Necessary to be able to stop editing.
else if (from === 'opened' && to === 'deactivating' && context.confirmed) {
accept = true;
}
}
return accept;
},
/**
* Checks if fields have acceptable states.
*
* @param {Array} acceptedFieldStates
* An array of acceptable field states to check for.
*
* @return {bool}
* Whether the fields have an acceptable state.
*
* @see Drupal.quickedit.EntityModel#validate
*/
_fieldsHaveAcceptableStates: function (acceptedFieldStates) {
var accept = true;
// If no acceptable field states are provided, assume all field states are
// acceptable. We want to let validation pass as a default and only
// check validity on calls to set that explicitly request it.
if (acceptedFieldStates.length > 0) {
var fieldStates = this.get('fields').pluck('state') || [];
// If not all fields are in one of the accepted field states, then we
// still can't allow this state change.
if (_.difference(fieldStates, acceptedFieldStates).length) {
accept = false;
}
}
return accept;
},
/**
* Destroys the entity model.
*
* @param {object} options
* Options for the entity model.
*/
destroy: function (options) {
Drupal.quickedit.BaseModel.prototype.destroy.call(this, options);
this.stopListening();
// Destroy all fields of this entity.
this.get('fields').reset();
},
/**
* @inheritdoc
*/
sync: function () {
// We don't use REST updates to sync.
return;
}
}, /** @lends Drupal.quickedit.EntityModel */{
/**
* Sequence of all possible states an entity can be in during quickediting.
*
* @type {Array.<string>}
*/
states: [
// Initial state, like field's 'inactive' OR the user has just finished
// in-place editing this entity.
// - Trigger: none (initial) or EntityModel (finished).
// - Expected behavior: (when not initial state): tear down
// EntityToolbarView, in-place editors and related views.
'closed',
// User has activated in-place editing of this entity.
// - Trigger: user.
// - Expected behavior: the EntityToolbarView is gets set up, in-place
// editors (EditorViews) and related views for this entity's fields are
// set up. Upon completion of those, the state is changed to 'opening'.
'launching',
// Launching has finished.
// - Trigger: application.
// - Guarantees: in-place editors ready for use, all entity and field
// views have been set up, all fields are in the 'inactive' state.
// - Expected behavior: all fields are changed to the 'candidate' state
// and once this is completed, the entity state will be changed to
// 'opened'.
'opening',
// Opening has finished.
// - Trigger: EntityModel.
// - Guarantees: see 'opening', all fields are in the 'candidate' state.
// - Expected behavior: the user is able to actually use in-place editing.
'opened',
// User has clicked the 'Save' button (and has thus changed at least one
// field).
// - Trigger: user.
// - Guarantees: see 'opened', plus: either a changed field is in
// PrivateTempStore, or the user has just modified a field without
// activating (switching to) another field.
// - Expected behavior: 1) if any of the fields are not yet in
// PrivateTempStore, save them to PrivateTempStore, 2) if then any of
// the fields has the 'invalid' state, then change the entity state back
// to 'opened', otherwise: save the entity by committing it from
// PrivateTempStore into permanent storage.
'committing',
// User has clicked the 'Close' button, or has clicked the 'Save' button
// and that was successfully completed.
// - Trigger: user or EntityModel.
// - Guarantees: when having clicked 'Close' hardly any: fields may be in
// a variety of states; when having clicked 'Save': all fields are in
// the 'candidate' state.
// - Expected behavior: transition all fields to the 'candidate' state,
// possibly requiring confirmation in the case of having clicked
// 'Close'.
'deactivating',
// Deactivation has been completed.
// - Trigger: EntityModel.
// - Guarantees: all fields are in the 'candidate' state.
// - Expected behavior: change all fields to the 'inactive' state.
'closing'
],
/**
* Indicates whether the 'from' state comes before the 'to' state.
*
* @param {string} from
* One of {@link Drupal.quickedit.EntityModel.states}.
* @param {string} to
* One of {@link Drupal.quickedit.EntityModel.states}.
*
* @return {bool}
* Whether the 'from' state comes before the 'to' state.
*/
followsStateSequence: function (from, to) {
return _.indexOf(this.states, from) < _.indexOf(this.states, to);
}
});
/**
* @constructor
*
* @augments Backbone.Collection
*/
Drupal.quickedit.EntityCollection = Backbone.Collection.extend(/** @lends Drupal.quickedit.EntityCollection# */{
/**
* @type {Drupal.quickedit.EntityModel}
*/
model: Drupal.quickedit.EntityModel
});
}(_, jQuery, Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the state of an in-place editable field in the DOM.
*/
(function (_, Backbone, Drupal) {
'use strict';
Drupal.quickedit.FieldModel = Drupal.quickedit.BaseModel.extend(/** @lends Drupal.quickedit.FieldModel# */{
/**
* @type {object}
*/
defaults: /** @lends Drupal.quickedit.FieldModel# */{
/**
* The DOM element that represents this field. It may seem bizarre to have
* a DOM element in a Backbone Model, but we need to be able to map fields
* in the DOM to FieldModels in memory.
*/
el: null,
/**
* A field ID, of the form
* `<entity type>/<id>/<field name>/<language>/<view mode>`
*
* @example
* "node/1/field_tags/und/full"
*/
fieldID: null,
/**
* The unique ID of this field within its entity instance on the page, of
* the form `<entity type>/<id>/<field name>/<language>/<view
* mode>[entity instance ID]`.
*
* @example
* "node/1/field_tags/und/full[0]"
*/
id: null,
/**
* A {@link Drupal.quickedit.EntityModel}. Its "fields" attribute, which
* is a FieldCollection, is automatically updated to include this
* FieldModel.
*/
entity: null,
/**
* This field's metadata as returned by the
* QuickEditController::metadata().
*/
metadata: null,
/**
* Callback function for validating changes between states. Receives the
* previous state, new state, context, and a callback.
*/
acceptStateChange: null,
/**
* A logical field ID, of the form
* `<entity type>/<id>/<field name>/<language>`, i.e. the fieldID without
* the view mode, to be able to identify other instances of the same
* field on the page but rendered in a different view mode.
*
* @example
* "node/1/field_tags/und".
*/
logicalFieldID: null,
// The attributes below are stateful. The ones above will never change
// during the life of a FieldModel instance.
/**
* In-place editing state of this field. Defaults to the initial state.
* Possible values: {@link Drupal.quickedit.FieldModel.states}.
*/
state: 'inactive',
/**
* The field is currently in the 'changed' state or one of the following
* states in which the field is still changed.
*/
isChanged: false,
/**
* Is tracked by the EntityModel, is mirrored here solely for decorative
* purposes: so that FieldDecorationView.renderChanged() can react to it.
*/
inTempStore: false,
/**
* The full HTML representation of this field (with the element that has
* the data-quickedit-field-id as the outer element). Used to propagate
* changes from this field to other instances of the same field storage.
*/
html: null,
/**
* An object containing the full HTML representations (values) of other
* view modes (keys) of this field, for other instances of this field
* displayed in a different view mode.
*/
htmlForOtherViewModes: null
},
/**
* State of an in-place editable field in the DOM.
*
* @constructs
*
* @augments Drupal.quickedit.BaseModel
*
* @param {object} options
* Options for the field model.
*/
initialize: function (options) {
// Store the original full HTML representation of this field.
this.set('html', options.el.outerHTML);
// Enlist field automatically in the associated entity's field collection.
this.get('entity').get('fields').add(this);
// Automatically generate the logical field ID.
this.set('logicalFieldID', this.get('fieldID').split('/').slice(0, 4).join('/'));
// Call Drupal.quickedit.BaseModel's initialize() method.
Drupal.quickedit.BaseModel.prototype.initialize.call(this, options);
},
/**
* Destroys the field model.
*
* @param {object} options
* Options for the field model.
*/
destroy: function (options) {
if (this.get('state') !== 'inactive') {
throw new Error('FieldModel cannot be destroyed if it is not inactive state.');
}
Drupal.quickedit.BaseModel.prototype.destroy.call(this, options);
},
/**
* @inheritdoc
*/
sync: function () {
// We don't use REST updates to sync.
return;
},
/**
* Validate function for the field model.
*
* @param {object} attrs
* The attributes changes in the save or set call.
* @param {object} options
* An object with the following option:
* @param {string} [options.reason]
* A string that conveys a particular reason to allow for an exceptional
* state change.
* @param {Array} options.accept-field-states
* An array of strings that represent field states that the entities must
* be in to validate. For example, if `accept-field-states` is
* `['candidate', 'highlighted']`, then all the fields of the entity must
* be in either of these two states for the save or set call to
* validate and proceed.
*
* @return {string}
* A string to say something about the state of the field model.
*/
validate: function (attrs, options) {
var current = this.get('state');
var next = attrs.state;
if (current !== next) {
// Ensure it's a valid state.
if (_.indexOf(this.constructor.states, next) === -1) {
return '"' + next + '" is an invalid state';
}
// Check if the acceptStateChange callback accepts it.
if (!this.get('acceptStateChange')(current, next, options, this)) {
return 'state change not accepted';
}
}
},
/**
* Extracts the entity ID from this field's ID.
*
* @return {string}
* An entity ID: a string of the format `<entity type>/<id>`.
*/
getEntityID: function () {
return this.get('fieldID').split('/').slice(0, 2).join('/');
},
/**
* Extracts the view mode ID from this field's ID.
*
* @return {string}
* A view mode ID.
*/
getViewMode: function () {
return this.get('fieldID').split('/').pop();
},
/**
* Find other instances of this field with different view modes.
*
* @return {Array}
* An array containing view mode IDs.
*/
findOtherViewModes: function () {
var currentField = this;
var otherViewModes = [];
Drupal.quickedit.collections.fields
// Find all instances of fields that display the same logical field
// (same entity, same field, just a different instance and maybe a
// different view mode).
.where({logicalFieldID: currentField.get('logicalFieldID')})
.forEach(function (field) {
// Ignore the current field.
if (field === currentField) {
return;
}
// Also ignore other fields with the same view mode.
else if (field.get('fieldID') === currentField.get('fieldID')) {
return;
}
else {
otherViewModes.push(field.getViewMode());
}
});
return otherViewModes;
}
}, /** @lends Drupal.quickedit.FieldModel */{
/**
* Sequence of all possible states a field can be in during quickediting.
*
* @type {Array.<string>}
*/
states: [
// The field associated with this FieldModel is linked to an EntityModel;
// the user can choose to start in-place editing that entity (and
// consequently this field). No in-place editor (EditorView) is associated
// with this field, because this field is not being in-place edited.
// This is both the initial (not yet in-place editing) and the end state
// (finished in-place editing).
'inactive',
// The user is in-place editing this entity, and this field is a
// candidate
// for in-place editing. In-place editor should not
// - Trigger: user.
// - Guarantees: entity is ready, in-place editor (EditorView) is
// associated with the field.
// - Expected behavior: visual indicators
// around the field indicate it is available for in-place editing, no
// in-place editor presented yet.
'candidate',
// User is highlighting this field.
// - Trigger: user.
// - Guarantees: see 'candidate'.
// - Expected behavior: visual indicators to convey highlighting, in-place
// editing toolbar shows field's label.
'highlighted',
// User has activated the in-place editing of this field; in-place editor
// is activating.
// - Trigger: user.
// - Guarantees: see 'candidate'.
// - Expected behavior: loading indicator, in-place editor is loading
// remote data (e.g. retrieve form from back-end). Upon retrieval of
// remote data, the in-place editor transitions the field's state to
// 'active'.
'activating',
// In-place editor has finished loading remote data; ready for use.
// - Trigger: in-place editor.
// - Guarantees: see 'candidate'.
// - Expected behavior: in-place editor for the field is ready for use.
'active',
// User has modified values in the in-place editor.
// - Trigger: user.
// - Guarantees: see 'candidate', plus in-place editor is ready for use.
// - Expected behavior: visual indicator of change.
'changed',
// User is saving changed field data in in-place editor to
// PrivateTempStore. The save mechanism of the in-place editor is called.
// - Trigger: user.
// - Guarantees: see 'candidate' and 'active'.
// - Expected behavior: saving indicator, in-place editor is saving field
// data into PrivateTempStore. Upon successful saving (without
// validation errors), the in-place editor transitions the field's state
// to 'saved', but to 'invalid' upon failed saving (with validation
// errors).
'saving',
// In-place editor has successfully saved the changed field.
// - Trigger: in-place editor.
// - Guarantees: see 'candidate' and 'active'.
// - Expected behavior: transition back to 'candidate' state because the
// deed is done. Then: 1) transition to 'inactive' to allow the field
// to be rerendered, 2) destroy the FieldModel (which also destroys
// attached views like the EditorView), 3) replace the existing field
// HTML with the existing HTML and 4) attach behaviors again so that the
// field becomes available again for in-place editing.
'saved',
// In-place editor has failed to saved the changed field: there were
// validation errors.
// - Trigger: in-place editor.
// - Guarantees: see 'candidate' and 'active'.
// - Expected behavior: remain in 'invalid' state, let the user make more
// changes so that he can save it again, without validation errors.
'invalid'
],
/**
* Indicates whether the 'from' state comes before the 'to' state.
*
* @param {string} from
* One of {@link Drupal.quickedit.FieldModel.states}.
* @param {string} to
* One of {@link Drupal.quickedit.FieldModel.states}.
*
* @return {bool}
* Whether the 'from' state comes before the 'to' state.
*/
followsStateSequence: function (from, to) {
return _.indexOf(this.states, from) < _.indexOf(this.states, to);
}
});
/**
* @constructor
*
* @augments Backbone.Collection
*/
Drupal.quickedit.FieldCollection = Backbone.Collection.extend(/** @lends Drupal.quickedit.FieldCollection */{
/**
* @type {Drupal.quickedit.FieldModel}
*/
model: Drupal.quickedit.FieldModel
});
}(_, Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the state of an in-place editor.
*
* @see Drupal.quickedit.EditorView
*/
(function (Backbone, Drupal) {
'use strict';
/**
* @constructor
*
* @augments Backbone.Model
*/
Drupal.quickedit.EditorModel = Backbone.Model.extend(/** @lends Drupal.quickedit.EditorModel# */{
/**
* @type {object}
*
* @prop {string} originalValue
* @prop {string} currentValue
* @prop {Array} validationErrors
*/
defaults: /** @lends Drupal.quickedit.EditorModel# */{
/**
* Not the full HTML representation of this field, but the "actual"
* original value of the field, stored by the used in-place editor, and
* in a representation that can be chosen by the in-place editor.
*
* @type {string}
*/
originalValue: null,
/**
* Analogous to originalValue, but the current value.
*
* @type {string}
*/
currentValue: null,
/**
* Stores any validation errors to be rendered.
*
* @type {Array}
*/
validationErrors: null
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone View that controls the overall "in-place editing application".
*
* @see Drupal.quickedit.AppModel
*/
(function ($, _, Backbone, Drupal) {
'use strict';
// Indicates whether the page should be reloaded after in-place editing has
// shut down. A page reload is necessary to re-instate the original HTML of
// the edited fields if in-place editing has been canceled and one or more of
// the entity's fields were saved to PrivateTempStore: one of them may have
// been changed to the empty value and hence may have been rerendered as the
// empty string, which makes it impossible for Quick Edit to know where to
// restore the original HTML.
var reload = false;
Drupal.quickedit.AppView = Backbone.View.extend(/** @lends Drupal.quickedit.AppView# */{
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.AppModel} options.model
* The application state model.
* @param {Drupal.quickedit.EntityCollection} options.entitiesCollection
* All on-page entities.
* @param {Drupal.quickedit.FieldCollection} options.fieldsCollection
* All on-page fields
*/
initialize: function (options) {
// AppView's configuration for handling states.
// @see Drupal.quickedit.FieldModel.states
this.activeFieldStates = ['activating', 'active'];
this.singleFieldStates = ['highlighted', 'activating', 'active'];
this.changedFieldStates = ['changed', 'saving', 'saved', 'invalid'];
this.readyFieldStates = ['candidate', 'highlighted'];
// Track app state.
this.listenTo(options.entitiesCollection, 'change:state', this.appStateChange);
this.listenTo(options.entitiesCollection, 'change:isActive', this.enforceSingleActiveEntity);
// Track app state.
this.listenTo(options.fieldsCollection, 'change:state', this.editorStateChange);
// Respond to field model HTML representation change events.
this.listenTo(options.fieldsCollection, 'change:html', this.renderUpdatedField);
this.listenTo(options.fieldsCollection, 'change:html', this.propagateUpdatedField);
// Respond to addition.
this.listenTo(options.fieldsCollection, 'add', this.rerenderedFieldToCandidate);
// Respond to destruction.
this.listenTo(options.fieldsCollection, 'destroy', this.teardownEditor);
},
/**
* Handles setup/teardown and state changes when the active entity changes.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* An instance of the EntityModel class.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.EntityModel.states}.
*/
appStateChange: function (entityModel, state) {
var app = this;
var entityToolbarView;
switch (state) {
case 'launching':
reload = false;
// First, create an entity toolbar view.
entityToolbarView = new Drupal.quickedit.EntityToolbarView({
model: entityModel,
appModel: this.model
});
entityModel.toolbarView = entityToolbarView;
// Second, set up in-place editors.
// They must be notified of state changes, hence this must happen
// while the associated fields are still in the 'inactive' state.
entityModel.get('fields').each(function (fieldModel) {
app.setupEditor(fieldModel);
});
// Third, transition the entity to the 'opening' state, which will
// transition all fields from 'inactive' to 'candidate'.
_.defer(function () {
entityModel.set('state', 'opening');
});
break;
case 'closed':
entityToolbarView = entityModel.toolbarView;
// First, tear down the in-place editors.
entityModel.get('fields').each(function (fieldModel) {
app.teardownEditor(fieldModel);
});
// Second, tear down the entity toolbar view.
if (entityToolbarView) {
entityToolbarView.remove();
delete entityModel.toolbarView;
}
// A page reload may be necessary to re-instate the original HTML of
// the edited fields.
if (reload) {
reload = false;
location.reload();
}
break;
}
},
/**
* Accepts or reject editor (Editor) state changes.
*
* This is what ensures that the app is in control of what happens.
*
* @param {string} from
* The previous state.
* @param {string} to
* The new state.
* @param {null|object} context
* The context that is trying to trigger the state change.
* @param {Drupal.quickedit.FieldModel} fieldModel
* The fieldModel to which this change applies.
*
* @return {bool}
* Whether the editor change was accepted or rejected.
*/
acceptEditorStateChange: function (from, to, context, fieldModel) {
var accept = true;
// If the app is in view mode, then reject all state changes except for
// those to 'inactive'.
if (context && (context.reason === 'stop' || context.reason === 'rerender')) {
if (from === 'candidate' && to === 'inactive') {
accept = true;
}
}
// Handling of edit mode state changes is more granular.
else {
// In general, enforce the states sequence. Disallow going back from a
// "later" state to an "earlier" state, except in explicitly allowed
// cases.
if (!Drupal.quickedit.FieldModel.followsStateSequence(from, to)) {
accept = false;
// Allow: activating/active -> candidate.
// Necessary to stop editing a field.
if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
accept = true;
}
// Allow: changed/invalid -> candidate.
// Necessary to stop editing a field when it is changed or invalid.
else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
accept = true;
}
// Allow: highlighted -> candidate.
// Necessary to stop highlighting a field.
else if (from === 'highlighted' && to === 'candidate') {
accept = true;
}
// Allow: saved -> candidate.
// Necessary when successfully saved a field.
else if (from === 'saved' && to === 'candidate') {
accept = true;
}
// Allow: invalid -> saving.
// Necessary to be able to save a corrected, invalid field.
else if (from === 'invalid' && to === 'saving') {
accept = true;
}
// Allow: invalid -> activating.
// Necessary to be able to correct a field that turned out to be
// invalid after the user already had moved on to the next field
// (which we explicitly allow to have a fluent UX).
else if (from === 'invalid' && to === 'activating') {
accept = true;
}
}
// If it's not against the general principle, then here are more
// disallowed cases to check.
if (accept) {
var activeField;
var activeFieldState;
// Ensure only one field (editor) at a time is active … but allow a
// user to hop from one field to the next, even if we still have to
// start saving the field that is currently active: assume it will be
// valid, to allow for a fluent UX. (If it turns out to be invalid,
// this block of code also handles that.)
if ((this.readyFieldStates.indexOf(from) !== -1 || from === 'invalid') && this.activeFieldStates.indexOf(to) !== -1) {
activeField = this.model.get('activeField');
if (activeField && activeField !== fieldModel) {
activeFieldState = activeField.get('state');
// Allow the state change. If the state of the active field is:
// - 'activating' or 'active': change it to 'candidate'
// - 'changed' or 'invalid': change it to 'saving'
// - 'saving' or 'saved': don't do anything.
if (this.activeFieldStates.indexOf(activeFieldState) !== -1) {
activeField.set('state', 'candidate');
}
else if (activeFieldState === 'changed' || activeFieldState === 'invalid') {
activeField.set('state', 'saving');
}
// If the field that's being activated is in fact already in the
// invalid state (which can only happen because above we allowed
// the user to move on to another field to allow for a fluent UX;
// we assumed it would be saved successfully), then we shouldn't
// allow the field to enter the 'activating' state, instead, we
// simply change the active editor. All guarantees and
// assumptions for this field still hold!
if (from === 'invalid') {
this.model.set('activeField', fieldModel);
accept = false;
}
// Do not reject: the field is either in the 'candidate' or
// 'highlighted' state and we allow it to enter the 'activating'
// state!
}
}
// Reject going from activating/active to candidate because of a
// mouseleave.
else if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
if (context && context.reason === 'mouseleave') {
accept = false;
}
}
// When attempting to stop editing a changed/invalid property, ask for
// confirmation.
else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
if (context && context.reason === 'mouseleave') {
accept = false;
}
else {
// Check whether the transition has been confirmed?
if (context && context.confirmed) {
accept = true;
}
}
}
}
}
return accept;
},
/**
* Sets up the in-place editor for the given field.
*
* Must happen before the fieldModel's state is changed to 'candidate'.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The field for which an in-place editor must be set up.
*/
setupEditor: function (fieldModel) {
// Get the corresponding entity toolbar.
var entityModel = fieldModel.get('entity');
var entityToolbarView = entityModel.toolbarView;
// Get the field toolbar DOM root from the entity toolbar.
var fieldToolbarRoot = entityToolbarView.getToolbarRoot();
// Create in-place editor.
var editorName = fieldModel.get('metadata').editor;
var editorModel = new Drupal.quickedit.EditorModel();
var editorView = new Drupal.quickedit.editors[editorName]({
el: $(fieldModel.get('el')),
model: editorModel,
fieldModel: fieldModel
});
// Create in-place editor's toolbar for this field — stored inside the
// entity toolbar, the entity toolbar will position itself appropriately
// above (or below) the edited element.
var toolbarView = new Drupal.quickedit.FieldToolbarView({
el: fieldToolbarRoot,
model: fieldModel,
$editedElement: $(editorView.getEditedElement()),
editorView: editorView,
entityModel: entityModel
});
// Create decoration for edited element: padding if necessary, sets
// classes on the element to style it according to the current state.
var decorationView = new Drupal.quickedit.FieldDecorationView({
el: $(editorView.getEditedElement()),
model: fieldModel,
editorView: editorView
});
// Track these three views in FieldModel so that we can tear them down
// correctly.
fieldModel.editorView = editorView;
fieldModel.toolbarView = toolbarView;
fieldModel.decorationView = decorationView;
},
/**
* Tears down the in-place editor for the given field.
*
* Must happen after the fieldModel's state is changed to 'inactive'.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The field for which an in-place editor must be torn down.
*/
teardownEditor: function (fieldModel) {
// Early-return if this field was not yet decorated.
if (typeof fieldModel.editorView === 'undefined') {
return;
}
// Unbind event handlers; remove toolbar element; delete toolbar view.
fieldModel.toolbarView.remove();
delete fieldModel.toolbarView;
// Unbind event handlers; delete decoration view. Don't remove the element
// because that would remove the field itself.
fieldModel.decorationView.remove();
delete fieldModel.decorationView;
// Unbind event handlers; delete editor view. Don't remove the element
// because that would remove the field itself.
fieldModel.editorView.remove();
delete fieldModel.editorView;
},
/**
* Asks the user to confirm whether he wants to stop editing via a modal.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* An instance of the EntityModel class.
*
* @see Drupal.quickedit.AppView#acceptEditorStateChange
*/
confirmEntityDeactivation: function (entityModel) {
var that = this;
var discardDialog;
function closeDiscardDialog(action) {
discardDialog.close(action);
// The active modal has been removed.
that.model.set('activeModal', null);
// If the targetState is saving, the field must be saved, then the
// entity must be saved.
if (action === 'save') {
entityModel.set('state', 'committing', {confirmed: true});
}
else {
entityModel.set('state', 'deactivating', {confirmed: true});
// Editing has been canceled and the changes will not be saved. Mark
// the page for reload if the entityModel declares that it requires
// a reload.
if (entityModel.get('reload')) {
reload = true;
entityModel.set('reload', false);
}
}
}
// Only instantiate if there isn't a modal instance visible yet.
if (!this.model.get('activeModal')) {
var $unsavedChanges = $('<div>' + Drupal.t('You have unsaved changes') + '</div>');
discardDialog = Drupal.dialog($unsavedChanges.get(0), {
title: Drupal.t('Discard changes?'),
dialogClass: 'quickedit-discard-modal',
resizable: false,
buttons: [
{
text: Drupal.t('Save'),
click: function () {
closeDiscardDialog('save');
},
primary: true
},
{
text: Drupal.t('Discard changes'),
click: function () {
closeDiscardDialog('discard');
}
}
],
// Prevent this modal from being closed without the user making a
// choice as per http://stackoverflow.com/a/5438771.
closeOnEscape: false,
create: function () {
$(this).parent().find('.ui-dialog-titlebar-close').remove();
},
beforeClose: false,
close: function (event) {
// Automatically destroy the DOM element that was used for the
// dialog.
$(event.target).remove();
}
});
this.model.set('activeModal', discardDialog);
discardDialog.showModal();
}
},
/**
* Reacts to field state changes; tracks global state.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The `fieldModel` holding the state.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
editorStateChange: function (fieldModel, state) {
var from = fieldModel.previous('state');
var to = state;
// Keep track of the highlighted field in the global state.
if (_.indexOf(this.singleFieldStates, to) !== -1 && this.model.get('highlightedField') !== fieldModel) {
this.model.set('highlightedField', fieldModel);
}
else if (this.model.get('highlightedField') === fieldModel && to === 'candidate') {
this.model.set('highlightedField', null);
}
// Keep track of the active field in the global state.
if (_.indexOf(this.activeFieldStates, to) !== -1 && this.model.get('activeField') !== fieldModel) {
this.model.set('activeField', fieldModel);
}
else if (this.model.get('activeField') === fieldModel && to === 'candidate') {
// Discarded if it transitions from a changed state to 'candidate'.
if (from === 'changed' || from === 'invalid') {
fieldModel.editorView.revert();
}
this.model.set('activeField', null);
}
},
/**
* Render an updated field (a field whose 'html' attribute changed).
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The FieldModel whose 'html' attribute changed.
* @param {string} html
* The updated 'html' attribute.
* @param {object} options
* An object with the following keys:
* @param {bool} options.propagation
* Whether this change to the 'html' attribute occurred because of the
* propagation of changes to another instance of this field.
*/
renderUpdatedField: function (fieldModel, html, options) {
// Get data necessary to rerender property before it is unavailable.
var $fieldWrapper = $(fieldModel.get('el'));
var $context = $fieldWrapper.parent();
var renderField = function () {
// Destroy the field model; this will cause all attached views to be
// destroyed too, and removal from all collections in which it exists.
fieldModel.destroy();
// Replace the old content with the new content.
$fieldWrapper.replaceWith(html);
// Attach behaviors again to the modified piece of HTML; this will
// create a new field model and call rerenderedFieldToCandidate() with
// it.
Drupal.attachBehaviors($context.get(0));
};
// When propagating the changes of another instance of this field, this
// field is not being actively edited and hence no state changes are
// necessary. So: only update the state of this field when the rerendering
// of this field happens not because of propagation, but because it is
// being edited itself.
if (!options.propagation) {
// Deferred because renderUpdatedField is reacting to a field model
// change event, and we want to make sure that event fully propagates
// before making another change to the same model.
_.defer(function () {
// First set the state to 'candidate', to allow all attached views to
// clean up all their "active state"-related changes.
fieldModel.set('state', 'candidate');
// Similarly, the above .set() call's change event must fully
// propagate before calling it again.
_.defer(function () {
// Set the field's state to 'inactive', to enable the updating of
// its DOM value.
fieldModel.set('state', 'inactive', {reason: 'rerender'});
renderField();
});
});
}
else {
renderField();
}
},
/**
* Propagates changes to an updated field to all instances of that field.
*
* @param {Drupal.quickedit.FieldModel} updatedField
* The FieldModel whose 'html' attribute changed.
* @param {string} html
* The updated 'html' attribute.
* @param {object} options
* An object with the following keys:
* @param {bool} options.propagation
* Whether this change to the 'html' attribute occurred because of the
* propagation of changes to another instance of this field.
*
* @see Drupal.quickedit.AppView#renderUpdatedField
*/
propagateUpdatedField: function (updatedField, html, options) {
// Don't propagate field updates that themselves were caused by
// propagation.
if (options.propagation) {
return;
}
var htmlForOtherViewModes = updatedField.get('htmlForOtherViewModes');
Drupal.quickedit.collections.fields
// Find all instances of fields that display the same logical field
// (same entity, same field, just a different instance and maybe a
// different view mode).
.where({logicalFieldID: updatedField.get('logicalFieldID')})
.forEach(function (field) {
// Ignore the field that was already updated.
if (field === updatedField) {
return;
}
// If this other instance of the field has the same view mode, we can
// update it easily.
else if (field.getViewMode() === updatedField.getViewMode()) {
field.set('html', updatedField.get('html'));
}
// If this other instance of the field has a different view mode, and
// that is one of the view modes for which a re-rendered version is
// available (and that should be the case unless this field was only
// added to the page after editing of the updated field began), then
// use that view mode's re-rendered version.
else {
if (field.getViewMode() in htmlForOtherViewModes) {
field.set('html', htmlForOtherViewModes[field.getViewMode()], {propagation: true});
}
}
});
},
/**
* If the new in-place editable field is for the entity that's currently
* being edited, then transition it to the 'candidate' state.
*
* This happens when a field was modified, saved and hence rerendered.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* A field that was just added to the collection of fields.
*/
rerenderedFieldToCandidate: function (fieldModel) {
var activeEntity = Drupal.quickedit.collections.entities.findWhere({isActive: true});
// Early-return if there is no active entity.
if (!activeEntity) {
return;
}
// If the field's entity is the active entity, make it a candidate.
if (fieldModel.get('entity') === activeEntity) {
this.setupEditor(fieldModel);
fieldModel.set('state', 'candidate');
}
},
/**
* EntityModel Collection change handler.
*
* Handler is called `change:isActive` and enforces a single active entity.
*
* @param {Drupal.quickedit.EntityModel} changedEntityModel
* The entityModel instance whose active state has changed.
*/
enforceSingleActiveEntity: function (changedEntityModel) {
// When an entity is deactivated, we don't need to enforce anything.
if (changedEntityModel.get('isActive') === false) {
return;
}
// This entity was activated; deactivate all other entities.
changedEntityModel.collection.chain()
.filter(function (entityModel) {
return entityModel.get('isActive') === true && entityModel !== changedEntityModel;
})
.each(function (entityModel) {
entityModel.set('state', 'deactivating');
});
}
});
}(jQuery, _, Backbone, Drupal));
;
/**
* @file
* A Backbone View that decorates the in-place edited element.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.quickedit.FieldDecorationView = Backbone.View.extend(/** @lends Drupal.quickedit.FieldDecorationView# */{
/**
* @type {null}
*/
_widthAttributeIsEmpty: null,
/**
* @type {object}
*/
events: {
'mouseenter.quickedit': 'onMouseEnter',
'mouseleave.quickedit': 'onMouseLeave',
'click': 'onClick',
'tabIn.quickedit': 'onMouseEnter',
'tabOut.quickedit': 'onMouseLeave'
},
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.EditorView} options.editorView
* The editor object view.
*/
initialize: function (options) {
this.editorView = options.editorView;
this.listenTo(this.model, 'change:state', this.stateChange);
this.listenTo(this.model, 'change:isChanged change:inTempStore', this.renderChanged);
},
/**
* @inheritdoc
*/
remove: function () {
// The el property is the field, which should not be removed. Remove the
// pointer to it, then call Backbone.View.prototype.remove().
this.setElement();
Backbone.View.prototype.remove.call(this);
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} model
* The `FieldModel` model.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
stateChange: function (model, state) {
var from = model.previous('state');
var to = state;
switch (to) {
case 'inactive':
this.undecorate();
break;
case 'candidate':
this.decorate();
if (from !== 'inactive') {
this.stopHighlight();
if (from !== 'highlighted') {
this.model.set('isChanged', false);
this.stopEdit();
}
}
this._unpad();
break;
case 'highlighted':
this.startHighlight();
break;
case 'activating':
// NOTE: this state is not used by every editor! It's only used by
// those that need to interact with the server.
this.prepareEdit();
break;
case 'active':
if (from !== 'activating') {
this.prepareEdit();
}
if (this.editorView.getQuickEditUISettings().padding) {
this._pad();
}
break;
case 'changed':
this.model.set('isChanged', true);
break;
case 'saving':
break;
case 'saved':
break;
case 'invalid':
break;
}
},
/**
* Adds a class to the edited element that indicates whether the field has
* been changed by the user (i.e. locally) or the field has already been
* changed and stored before by the user (i.e. remotely, stored in
* PrivateTempStore).
*/
renderChanged: function () {
this.$el.toggleClass('quickedit-changed', this.model.get('isChanged') || this.model.get('inTempStore'));
},
/**
* Starts hover; transitions to 'highlight' state.
*
* @param {jQuery.Event} event
* The mouse event.
*/
onMouseEnter: function (event) {
var that = this;
that.model.set('state', 'highlighted');
event.stopPropagation();
},
/**
* Stops hover; transitions to 'candidate' state.
*
* @param {jQuery.Event} event
* The mouse event.
*/
onMouseLeave: function (event) {
var that = this;
that.model.set('state', 'candidate', {reason: 'mouseleave'});
event.stopPropagation();
},
/**
* Transition to 'activating' stage.
*
* @param {jQuery.Event} event
* The click event.
*/
onClick: function (event) {
this.model.set('state', 'activating');
event.preventDefault();
event.stopPropagation();
},
/**
* Adds classes used to indicate an elements editable state.
*/
decorate: function () {
this.$el.addClass('quickedit-candidate quickedit-editable');
},
/**
* Removes classes used to indicate an elements editable state.
*/
undecorate: function () {
this.$el.removeClass('quickedit-candidate quickedit-editable quickedit-highlighted quickedit-editing');
},
/**
* Adds that class that indicates that an element is highlighted.
*/
startHighlight: function () {
// Animations.
var that = this;
// Use a timeout to grab the next available animation frame.
that.$el.addClass('quickedit-highlighted');
},
/**
* Removes the class that indicates that an element is highlighted.
*/
stopHighlight: function () {
this.$el.removeClass('quickedit-highlighted');
},
/**
* Removes the class that indicates that an element as editable.
*/
prepareEdit: function () {
this.$el.addClass('quickedit-editing');
// Allow the field to be styled differently while editing in a pop-up
// in-place editor.
if (this.editorView.getQuickEditUISettings().popup) {
this.$el.addClass('quickedit-editor-is-popup');
}
},
/**
* Removes the class that indicates that an element is being edited.
*
* Reapplies the class that indicates that a candidate editable element is
* again available to be edited.
*/
stopEdit: function () {
this.$el.removeClass('quickedit-highlighted quickedit-editing');
// Done editing in a pop-up in-place editor; remove the class.
if (this.editorView.getQuickEditUISettings().popup) {
this.$el.removeClass('quickedit-editor-is-popup');
}
// Make the other editors show up again.
$('.quickedit-candidate').addClass('quickedit-editable');
},
/**
* Adds padding around the editable element to make it pop visually.
*/
_pad: function () {
// Early return if the element has already been padded.
if (this.$el.data('quickedit-padded')) {
return;
}
var self = this;
// Add 5px padding for readability. This means we'll freeze the current
// width and *then* add 5px padding, hence ensuring the padding is added
// "on the outside".
// 1) Freeze the width (if it's not already set); don't use animations.
if (this.$el[0].style.width === '') {
this._widthAttributeIsEmpty = true;
this.$el
.addClass('quickedit-animate-disable-width')
.css('width', this.$el.width());
}
// 2) Add padding; use animations.
var posProp = this._getPositionProperties(this.$el);
setTimeout(function () {
// Re-enable width animations (padding changes affect width too!).
self.$el.removeClass('quickedit-animate-disable-width');
// Pad the editable.
self.$el
.css({
'position': 'relative',
'top': posProp.top - 5 + 'px',
'left': posProp.left - 5 + 'px',
'padding-top': posProp['padding-top'] + 5 + 'px',
'padding-left': posProp['padding-left'] + 5 + 'px',
'padding-right': posProp['padding-right'] + 5 + 'px',
'padding-bottom': posProp['padding-bottom'] + 5 + 'px',
'margin-bottom': posProp['margin-bottom'] - 10 + 'px'
})
.data('quickedit-padded', true);
}, 0);
},
/**
* Removes the padding around the element being edited when editing ceases.
*/
_unpad: function () {
// Early return if the element has not been padded.
if (!this.$el.data('quickedit-padded')) {
return;
}
var self = this;
// 1) Set the empty width again.
if (this._widthAttributeIsEmpty) {
this.$el
.addClass('quickedit-animate-disable-width')
.css('width', '');
}
// 2) Remove padding; use animations (these will run simultaneously with)
// the fading out of the toolbar as its gets removed).
var posProp = this._getPositionProperties(this.$el);
setTimeout(function () {
// Re-enable width animations (padding changes affect width too!).
self.$el.removeClass('quickedit-animate-disable-width');
// Unpad the editable.
self.$el
.css({
'position': 'relative',
'top': posProp.top + 5 + 'px',
'left': posProp.left + 5 + 'px',
'padding-top': posProp['padding-top'] - 5 + 'px',
'padding-left': posProp['padding-left'] - 5 + 'px',
'padding-right': posProp['padding-right'] - 5 + 'px',
'padding-bottom': posProp['padding-bottom'] - 5 + 'px',
'margin-bottom': posProp['margin-bottom'] + 10 + 'px'
});
}, 0);
// Remove the marker that indicates that this field has padding. This is
// done outside the timed out function above so that we don't get numerous
// queued functions that will remove padding before the data marker has
// been removed.
this.$el.removeData('quickedit-padded');
},
/**
* Gets the top and left properties of an element.
*
* Convert extraneous values and information into numbers ready for
* subtraction.
*
* @param {jQuery} $e
* The element to get position properties from.
*
* @return {object}
* An object containing css values for the needed properties.
*/
_getPositionProperties: function ($e) {
var p;
var r = {};
var props = [
'top', 'left', 'bottom', 'right',
'padding-top', 'padding-left', 'padding-right', 'padding-bottom',
'margin-bottom'
];
var propCount = props.length;
for (var i = 0; i < propCount; i++) {
p = props[i];
r[p] = parseInt(this._replaceBlankPosition($e.css(p)), 10);
}
return r;
},
/**
* Replaces blank or 'auto' CSS `position: <value>` values with "0px".
*
* @param {string} [pos]
* The value for a CSS position declaration.
*
* @return {string}
* A CSS value that is valid for `position`.
*/
_replaceBlankPosition: function (pos) {
if (pos === 'auto' || !pos) {
pos = '0px';
}
return pos;
}
});
})(jQuery, Backbone, Drupal);
;
/**
* @file
* A Backbone view that decorates the in-place editable entity.
*/
(function (Drupal, $, Backbone) {
'use strict';
Drupal.quickedit.EntityDecorationView = Backbone.View.extend(/** @lends Drupal.quickedit.EntityDecorationView# */{
/**
* Associated with the DOM root node of an editable entity.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
/**
* @inheritdoc
*/
render: function () {
this.$el.toggleClass('quickedit-entity-active', this.model.get('isActive'));
},
/**
* @inheritdoc
*/
remove: function () {
this.setElement(null);
Backbone.View.prototype.remove.call(this);
}
});
}(Drupal, jQuery, Backbone));
;
/**
* @file
* A Backbone View that provides an entity level toolbar.
*/
(function ($, _, Backbone, Drupal, debounce) {
'use strict';
Drupal.quickedit.EntityToolbarView = Backbone.View.extend(/** @lends Drupal.quickedit.EntityToolbarView# */{
/**
* @type {jQuery}
*/
_fieldToolbarRoot: null,
/**
* @return {object}
* A map of events.
*/
events: function () {
var map = {
'click button.action-save': 'onClickSave',
'click button.action-cancel': 'onClickCancel',
'mouseenter': 'onMouseenter'
};
return map;
},
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options to construct the view.
* @param {Drupal.quickedit.AppModel} options.appModel
* A quickedit `AppModel` to use in the view.
*/
initialize: function (options) {
var that = this;
this.appModel = options.appModel;
this.$entity = $(this.model.get('el'));
// Rerender whenever the entity state changes.
this.listenTo(this.model, 'change:isActive change:isDirty change:state', this.render);
// Also rerender whenever a different field is highlighted or activated.
this.listenTo(this.appModel, 'change:highlightedField change:activeField', this.render);
// Rerender when a field of the entity changes state.
this.listenTo(this.model.get('fields'), 'change:state', this.fieldStateChange);
// Reposition the entity toolbar as the viewport and the position within
// the viewport changes.
$(window).on('resize.quickedit scroll.quickedit drupalViewportOffsetChange.quickedit', debounce($.proxy(this.windowChangeHandler, this), 150));
// Adjust the fence placement within which the entity toolbar may be
// positioned.
$(document).on('drupalViewportOffsetChange.quickedit', function (event, offsets) {
if (that.$fence) {
that.$fence.css(offsets);
}
});
// Set the entity toolbar DOM element as the el for this view.
var $toolbar = this.buildToolbarEl();
this.setElement($toolbar);
this._fieldToolbarRoot = $toolbar.find('.quickedit-toolbar-field').get(0);
// Initial render.
this.render();
},
/**
* @inheritdoc
*
* @return {Drupal.quickedit.EntityToolbarView}
* The entity toolbar view.
*/
render: function () {
if (this.model.get('isActive')) {
// If the toolbar container doesn't exist, create it.
var $body = $('body');
if ($body.children('#quickedit-entity-toolbar').length === 0) {
$body.append(this.$el);
}
// The fence will define a area on the screen that the entity toolbar
// will be position within.
if ($body.children('#quickedit-toolbar-fence').length === 0) {
this.$fence = $(Drupal.theme('quickeditEntityToolbarFence'))
.css(Drupal.displace())
.appendTo($body);
}
// Adds the entity title to the toolbar.
this.label();
// Show the save and cancel buttons.
this.show('ops');
// If render is being called and the toolbar is already visible, just
// reposition it.
this.position();
}
// The save button text and state varies with the state of the entity
// model.
var $button = this.$el.find('.quickedit-button.action-save');
var isDirty = this.model.get('isDirty');
// Adjust the save button according to the state of the model.
switch (this.model.get('state')) {
// Quick editing is active, but no field is being edited.
case 'opened':
// The saving throbber is not managed by AJAX system. The
// EntityToolbarView manages this visual element.
$button
.removeClass('action-saving icon-throbber icon-end')
.text(Drupal.t('Save'))
.removeAttr('disabled')
.attr('aria-hidden', !isDirty);
break;
// The changes to the fields of the entity are being committed.
case 'committing':
$button
.addClass('action-saving icon-throbber icon-end')
.text(Drupal.t('Saving'))
.attr('disabled', 'disabled');
break;
default:
$button.attr('aria-hidden', true);
break;
}
return this;
},
/**
* @inheritdoc
*/
remove: function () {
// Remove additional DOM elements controlled by this View.
this.$fence.remove();
// Stop listening to additional events.
$(window).off('resize.quickedit scroll.quickedit drupalViewportOffsetChange.quickedit');
$(document).off('drupalViewportOffsetChange.quickedit');
Backbone.View.prototype.remove.call(this);
},
/**
* Repositions the entity toolbar on window scroll and resize.
*
* @param {jQuery.Event} event
* The scroll or resize event.
*/
windowChangeHandler: function (event) {
this.position();
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} model
* The `FieldModel` model.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
fieldStateChange: function (model, state) {
switch (state) {
case 'active':
this.render();
break;
case 'invalid':
this.render();
break;
}
},
/**
* Uses the jQuery.ui.position() method to position the entity toolbar.
*
* @param {HTMLElement} [element]
* The element against which the entity toolbar is positioned.
*/
position: function (element) {
clearTimeout(this.timer);
var that = this;
// Vary the edge of the positioning according to the direction of language
// in the document.
var edge = (document.documentElement.dir === 'rtl') ? 'right' : 'left';
// A time unit to wait until the entity toolbar is repositioned.
var delay = 0;
// Determines what check in the series of checks below should be
// evaluated.
var check = 0;
// When positioned against an active field that has padding, we should
// ignore that padding when positioning the toolbar, to not unnecessarily
// move the toolbar horizontally, which feels annoying.
var horizontalPadding = 0;
var of;
var activeField;
var highlightedField;
// There are several elements in the page that the entity toolbar might be
// positioned against. They are considered below in a priority order.
do {
switch (check) {
case 0:
// Position against a specific element.
of = element;
break;
case 1:
// Position against a form container.
activeField = Drupal.quickedit.app.model.get('activeField');
of = activeField && activeField.editorView && activeField.editorView.$formContainer && activeField.editorView.$formContainer.find('.quickedit-form');
break;
case 2:
// Position against an active field.
of = activeField && activeField.editorView && activeField.editorView.getEditedElement();
if (activeField && activeField.editorView && activeField.editorView.getQuickEditUISettings().padding) {
horizontalPadding = 5;
}
break;
case 3:
// Position against a highlighted field.
highlightedField = Drupal.quickedit.app.model.get('highlightedField');
of = highlightedField && highlightedField.editorView && highlightedField.editorView.getEditedElement();
delay = 250;
break;
default:
var fieldModels = this.model.get('fields').models;
var topMostPosition = 1000000;
var topMostField = null;
// Position against the topmost field.
for (var i = 0; i < fieldModels.length; i++) {
var pos = fieldModels[i].get('el').getBoundingClientRect().top;
if (pos < topMostPosition) {
topMostPosition = pos;
topMostField = fieldModels[i];
}
}
of = topMostField.get('el');
delay = 50;
break;
}
// Prepare to check the next possible element to position against.
check++;
} while (!of);
/**
* Refines the positioning algorithm of jquery.ui.position().
*
* Invoked as the 'using' callback of jquery.ui.position() in
* positionToolbar().
*
* @param {*} view
* The view the positions will be calculated from.
* @param {object} suggested
* A hash of top and left values for the position that should be set. It
* can be forwarded to .css() or .animate().
* @param {object} info
* The position and dimensions of both the 'my' element and the 'of'
* elements, as well as calculations to their relative position. This
* object contains the following properties:
* @param {object} info.element
* A hash that contains information about the HTML element that will be
* positioned. Also known as the 'my' element.
* @param {object} info.target
* A hash that contains information about the HTML element that the
* 'my' element will be positioned against. Also known as the 'of'
* element.
*/
function refinePosition(view, suggested, info) {
// Determine if the pointer should be on the top or bottom.
var isBelow = suggested.top > info.target.top;
info.element.element.toggleClass('quickedit-toolbar-pointer-top', isBelow);
// Don't position the toolbar past the first or last editable field if
// the entity is the target.
if (view.$entity[0] === info.target.element[0]) {
// Get the first or last field according to whether the toolbar is
// above or below the entity.
var $field = view.$entity.find('.quickedit-editable').eq((isBelow) ? -1 : 0);
if ($field.length > 0) {
suggested.top = (isBelow) ? ($field.offset().top + $field.outerHeight(true)) : $field.offset().top - info.element.element.outerHeight(true);
}
}
// Don't let the toolbar go outside the fence.
var fenceTop = view.$fence.offset().top;
var fenceHeight = view.$fence.height();
var toolbarHeight = info.element.element.outerHeight(true);
if (suggested.top < fenceTop) {
suggested.top = fenceTop;
}
else if ((suggested.top + toolbarHeight) > (fenceTop + fenceHeight)) {
suggested.top = fenceTop + fenceHeight - toolbarHeight;
}
// Position the toolbar.
info.element.element.css({
left: Math.floor(suggested.left),
top: Math.floor(suggested.top)
});
}
/**
* Calls the jquery.ui.position() method on the $el of this view.
*/
function positionToolbar() {
that.$el
.position({
my: edge + ' bottom',
// Move the toolbar 1px towards the start edge of the 'of' element,
// plus any horizontal padding that may have been added to the
// element that is being added, to prevent unwanted horizontal
// movement.
at: edge + '+' + (1 + horizontalPadding) + ' top',
of: of,
collision: 'flipfit',
using: refinePosition.bind(null, that),
within: that.$fence
})
// Resize the toolbar to match the dimensions of the field, up to a
// maximum width that is equal to 90% of the field's width.
.css({
'max-width': (document.documentElement.clientWidth < 450) ? document.documentElement.clientWidth : 450,
// Set a minimum width of 240px for the entity toolbar, or the width
// of the client if it is less than 240px, so that the toolbar
// never folds up into a squashed and jumbled mess.
'min-width': (document.documentElement.clientWidth < 240) ? document.documentElement.clientWidth : 240,
'width': '100%'
});
}
// Uses the jQuery.ui.position() method. Use a timeout to move the toolbar
// only after the user has focused on an editable for 250ms. This prevents
// the toolbar from jumping around the screen.
this.timer = setTimeout(function () {
// Render the position in the next execution cycle, so that animations
// on the field have time to process. This is not strictly speaking, a
// guarantee that all animations will be finished, but it's a simple
// way to get better positioning without too much additional code.
_.defer(positionToolbar);
}, delay);
},
/**
* Set the model state to 'saving' when the save button is clicked.
*
* @param {jQuery.Event} event
* The click event.
*/
onClickSave: function (event) {
event.stopPropagation();
event.preventDefault();
// Save the model.
this.model.set('state', 'committing');
},
/**
* Sets the model state to candidate when the cancel button is clicked.
*
* @param {jQuery.Event} event
* The click event.
*/
onClickCancel: function (event) {
event.preventDefault();
this.model.set('state', 'deactivating');
},
/**
* Clears the timeout that will eventually reposition the entity toolbar.
*
* Without this, it may reposition itself, away from the user's cursor!
*
* @param {jQuery.Event} event
* The mouse event.
*/
onMouseenter: function (event) {
clearTimeout(this.timer);
},
/**
* Builds the entity toolbar HTML; attaches to DOM; sets starting position.
*
* @return {jQuery}
* The toolbar element.
*/
buildToolbarEl: function () {
var $toolbar = $(Drupal.theme('quickeditEntityToolbar', {
id: 'quickedit-entity-toolbar'
}));
$toolbar
.find('.quickedit-toolbar-entity')
// Append the "ops" toolgroup into the toolbar.
.prepend(Drupal.theme('quickeditToolgroup', {
classes: ['ops'],
buttons: [
{
label: Drupal.t('Save'),
type: 'submit',
classes: 'action-save quickedit-button icon',
attributes: {
'aria-hidden': true
}
},
{
label: Drupal.t('Close'),
classes: 'action-cancel quickedit-button icon icon-close icon-only'
}
]
}));
// Give the toolbar a sensible starting position so that it doesn't
// animate on to the screen from a far off corner.
$toolbar
.css({
left: this.$entity.offset().left,
top: this.$entity.offset().top
});
return $toolbar;
},
/**
* Returns the DOM element that fields will attach their toolbars to.
*
* @return {jQuery}
* The DOM element that fields will attach their toolbars to.
*/
getToolbarRoot: function () {
return this._fieldToolbarRoot;
},
/**
* Generates a state-dependent label for the entity toolbar.
*/
label: function () {
// The entity label.
var label = '';
var entityLabel = this.model.get('label');
// Label of an active field, if it exists.
var activeField = Drupal.quickedit.app.model.get('activeField');
var activeFieldLabel = activeField && activeField.get('metadata').label;
// Label of a highlighted field, if it exists.
var highlightedField = Drupal.quickedit.app.model.get('highlightedField');
var highlightedFieldLabel = highlightedField && highlightedField.get('metadata').label;
// The label is constructed in a priority order.
if (activeFieldLabel) {
label = Drupal.theme('quickeditEntityToolbarLabel', {
entityLabel: entityLabel,
fieldLabel: activeFieldLabel
});
}
else if (highlightedFieldLabel) {
label = Drupal.theme('quickeditEntityToolbarLabel', {
entityLabel: entityLabel,
fieldLabel: highlightedFieldLabel
});
}
else {
// @todo Add XSS regression test coverage in https://www.drupal.org/node/2547437
label = Drupal.checkPlain(entityLabel);
}
this.$el
.find('.quickedit-toolbar-label')
.html(label);
},
/**
* Adds classes to a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
* @param {string} classes
* A string of space-delimited class names that will be applied to the
* wrapping element of the toolbar group.
*/
addClass: function (toolgroup, classes) {
this._find(toolgroup).addClass(classes);
},
/**
* Removes classes from a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
* @param {string} classes
* A string of space-delimited class names that will be removed from the
* wrapping element of the toolbar group.
*/
removeClass: function (toolgroup, classes) {
this._find(toolgroup).removeClass(classes);
},
/**
* Finds a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*
* @return {jQuery}
* The toolgroup DOM element.
*/
_find: function (toolgroup) {
return this.$el.find('.quickedit-toolbar .quickedit-toolgroup.' + toolgroup);
},
/**
* Shows a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*/
show: function (toolgroup) {
this.$el.removeClass('quickedit-animate-invisible');
}
});
})(jQuery, _, Backbone, Drupal, Drupal.debounce);
;
/**
* @file
* A Backbone View that provides a dynamic contextual link.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.quickedit.ContextualLinkView = Backbone.View.extend(/** @lends Drupal.quickedit.ContextualLinkView# */{
/**
* Define all events to listen to.
*
* @return {object}
* A map of events.
*/
events: function () {
// Prevents delay and simulated mouse events.
function touchEndToClick(event) {
event.preventDefault();
event.target.click();
}
return {
'click a': function (event) {
event.preventDefault();
this.model.set('state', 'launching');
},
'touchEnd a': touchEndToClick
};
},
/**
* Create a new contextual link view.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.EntityModel} options.model
* The associated entity's model.
* @param {Drupal.quickedit.AppModel} options.appModel
* The application state model.
* @param {object} options.strings
* The strings for the "Quick edit" link.
*/
initialize: function (options) {
// Insert the text of the quick edit toggle.
this.$el.find('a').text(options.strings.quickEdit);
// Initial render.
this.render();
// Re-render whenever this entity's isActive attribute changes.
this.listenTo(this.model, 'change:isActive', this.render);
},
/**
* Render function for the contextual link view.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* The associated `EntityModel`.
* @param {bool} isActive
* Whether the in-place editor is active or not.
*
* @return {Drupal.quickedit.ContextualLinkView}
* The `ContextualLinkView` in question.
*/
render: function (entityModel, isActive) {
this.$el.find('a').attr('aria-pressed', isActive);
// Hides the contextual links if an in-place editor is active.
this.$el.closest('.contextual').toggle(!isActive);
return this;
}
});
})(jQuery, Backbone, Drupal);
;
/**
* @file
* A Backbone View that provides an interactive toolbar (1 per in-place editor).
*/
(function ($, _, Backbone, Drupal) {
'use strict';
Drupal.quickedit.FieldToolbarView = Backbone.View.extend(/** @lends Drupal.quickedit.FieldToolbarView# */{
/**
* The edited element, as indicated by EditorView.getEditedElement.
*
* @type {jQuery}
*/
$editedElement: null,
/**
* A reference to the in-place editor.
*
* @type {Drupal.quickedit.EditorView}
*/
editorView: null,
/**
* @type {string}
*/
_id: null,
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options object to construct the field toolbar.
* @param {jQuery} options.$editedElement
* The element being edited.
* @param {Drupal.quickedit.EditorView} options.editorView
* The EditorView the toolbar belongs to.
*/
initialize: function (options) {
this.$editedElement = options.$editedElement;
this.editorView = options.editorView;
/**
* @type {jQuery}
*/
this.$root = this.$el;
// Generate a DOM-compatible ID for the form container DOM element.
this._id = 'quickedit-toolbar-for-' + this.model.id.replace(/[\/\[\]]/g, '_');
this.listenTo(this.model, 'change:state', this.stateChange);
},
/**
* @inheritdoc
*
* @return {Drupal.quickedit.FieldToolbarView}
* The current FieldToolbarView.
*/
render: function () {
// Render toolbar and set it as the view's element.
this.setElement($(Drupal.theme('quickeditFieldToolbar', {
id: this._id
})));
// Attach to the field toolbar $root element in the entity toolbar.
this.$el.prependTo(this.$root);
return this;
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} model
* The quickedit FieldModel
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
stateChange: function (model, state) {
var from = model.previous('state');
var to = state;
switch (to) {
case 'inactive':
break;
case 'candidate':
// Remove the view's existing element if we went to the 'activating'
// state or later, because it will be recreated. Not doing this would
// result in memory leaks.
if (from !== 'inactive' && from !== 'highlighted') {
this.$el.remove();
this.setElement();
}
break;
case 'highlighted':
break;
case 'activating':
this.render();
if (this.editorView.getQuickEditUISettings().fullWidthToolbar) {
this.$el.addClass('quickedit-toolbar-fullwidth');
}
if (this.editorView.getQuickEditUISettings().unifiedToolbar) {
this.insertWYSIWYGToolGroups();
}
break;
case 'active':
break;
case 'changed':
break;
case 'saving':
break;
case 'saved':
break;
case 'invalid':
break;
}
},
/**
* Insert WYSIWYG markup into the associated toolbar.
*/
insertWYSIWYGToolGroups: function () {
this.$el
.append(Drupal.theme('quickeditToolgroup', {
id: this.getFloatedWysiwygToolgroupId(),
classes: ['wysiwyg-floated', 'quickedit-animate-slow', 'quickedit-animate-invisible', 'quickedit-animate-delay-veryfast'],
buttons: []
}))
.append(Drupal.theme('quickeditToolgroup', {
id: this.getMainWysiwygToolgroupId(),
classes: ['wysiwyg-main', 'quickedit-animate-slow', 'quickedit-animate-invisible', 'quickedit-animate-delay-veryfast'],
buttons: []
}));
// Animate the toolgroups into visibility.
this.show('wysiwyg-floated');
this.show('wysiwyg-main');
},
/**
* Retrieves the ID for this toolbar's container.
*
* Only used to make sane hovering behavior possible.
*
* @return {string}
* A string that can be used as the ID for this toolbar's container.
*/
getId: function () {
return 'quickedit-toolbar-for-' + this._id;
},
/**
* Retrieves the ID for this toolbar's floating WYSIWYG toolgroup.
*
* Used to provide an abstraction for any WYSIWYG editor to plug in.
*
* @return {string}
* A string that can be used as the ID.
*/
getFloatedWysiwygToolgroupId: function () {
return 'quickedit-wysiwyg-floated-toolgroup-for-' + this._id;
},
/**
* Retrieves the ID for this toolbar's main WYSIWYG toolgroup.
*
* Used to provide an abstraction for any WYSIWYG editor to plug in.
*
* @return {string}
* A string that can be used as the ID.
*/
getMainWysiwygToolgroupId: function () {
return 'quickedit-wysiwyg-main-toolgroup-for-' + this._id;
},
/**
* Finds a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*
* @return {jQuery}
* The toolgroup element.
*/
_find: function (toolgroup) {
return this.$el.find('.quickedit-toolgroup.' + toolgroup);
},
/**
* Shows a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*/
show: function (toolgroup) {
var $group = this._find(toolgroup);
// Attach a transitionEnd event handler to the toolbar group so that
// update events can be triggered after the animations have ended.
$group.on(Drupal.quickedit.util.constants.transitionEnd, function (event) {
$group.off(Drupal.quickedit.util.constants.transitionEnd);
});
// The call to remove the class and start the animation must be started in
// the next animation frame or the event handler attached above won't be
// triggered.
window.setTimeout(function () {
$group.removeClass('quickedit-animate-invisible');
}, 0);
}
});
})(jQuery, _, Backbone, Drupal);
;
/**
* @file
* An abstract Backbone View that controls an in-place editor.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.quickedit.EditorView = Backbone.View.extend(/** @lends Drupal.quickedit.EditorView# */{
/**
* A base implementation that outlines the structure for in-place editors.
*
* Specific in-place editor implementations should subclass (extend) this
* View and override whichever method they deem necessary to override.
*
* Typically you would want to override this method to set the
* originalValue attribute in the FieldModel to such a value that your
* in-place editor can revert to the original value when necessary.
*
* @example
* <caption>If you override this method, you should call this
* method (the parent class' initialize()) first.</caption>
* Drupal.quickedit.EditorView.prototype.initialize.call(this, options);
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.EditorModel} options.model
* The in-place editor state model.
* @param {Drupal.quickedit.FieldModel} options.fieldModel
* The field model.
*
* @see Drupal.quickedit.EditorModel
* @see Drupal.quickedit.editors.plain_text
*/
initialize: function (options) {
this.fieldModel = options.fieldModel;
this.listenTo(this.fieldModel, 'change:state', this.stateChange);
},
/**
* @inheritdoc
*/
remove: function () {
// The el property is the field, which should not be removed. Remove the
// pointer to it, then call Backbone.View.prototype.remove().
this.setElement();
Backbone.View.prototype.remove.call(this);
},
/**
* Returns the edited element.
*
* For some single cardinality fields, it may be necessary or useful to
* not in-place edit (and hence decorate) the DOM element with the
* data-quickedit-field-id attribute (which is the field's wrapper), but a
* specific element within the field's wrapper.
* e.g. using a WYSIWYG editor on a body field should happen on the DOM
* element containing the text itself, not on the field wrapper.
*
* @return {jQuery}
* A jQuery-wrapped DOM element.
*
* @see Drupal.quickedit.editors.plain_text
*/
getEditedElement: function () {
return this.$el;
},
/**
*
* @return {object}
* Returns 3 Quick Edit UI settings that depend on the in-place editor:
* - Boolean padding: indicates whether padding should be applied to the
* edited element, to guarantee legibility of text.
* - Boolean unifiedToolbar: provides the in-place editor with the ability
* to insert its own toolbar UI into Quick Edit's tightly integrated
* toolbar.
* - Boolean fullWidthToolbar: indicates whether Quick Edit's tightly
* integrated toolbar should consume the full width of the element,
* rather than being just long enough to accommodate a label.
*/
getQuickEditUISettings: function () {
return {padding: false, unifiedToolbar: false, fullWidthToolbar: false, popup: false};
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The quickedit `FieldModel` that holds the state.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
stateChange: function (fieldModel, state) {
var from = fieldModel.previous('state');
var to = state;
switch (to) {
case 'inactive':
// An in-place editor view will not yet exist in this state, hence
// this will never be reached. Listed for sake of completeness.
break;
case 'candidate':
// Nothing to do for the typical in-place editor: it should not be
// visible yet. Except when we come from the 'invalid' state, then we
// clean up.
if (from === 'invalid') {
this.removeValidationErrors();
}
break;
case 'highlighted':
// Nothing to do for the typical in-place editor: it should not be
// visible yet.
break;
case 'activating':
// The user has indicated he wants to do in-place editing: if
// something needs to be loaded (CSS/JavaScript/server data/…), then
// do so at this stage, and once the in-place editor is ready,
// set the 'active' state. A "loading" indicator will be shown in the
// UI for as long as the field remains in this state.
var loadDependencies = function (callback) {
// Do the loading here.
callback();
};
loadDependencies(function () {
fieldModel.set('state', 'active');
});
break;
case 'active':
// The user can now actually use the in-place editor.
break;
case 'changed':
// Nothing to do for the typical in-place editor. The UI will show an
// indicator that the field has changed.
break;
case 'saving':
// When the user has indicated he wants to save his changes to this
// field, this state will be entered. If the previous saving attempt
// resulted in validation errors, the previous state will be
// 'invalid'. Clean up those validation errors while the user is
// saving.
if (from === 'invalid') {
this.removeValidationErrors();
}
this.save();
break;
case 'saved':
// Nothing to do for the typical in-place editor. Immediately after
// being saved, a field will go to the 'candidate' state, where it
// should no longer be visible (after all, the field will then again
// just be a *candidate* to be in-place edited).
break;
case 'invalid':
// The modified field value was attempted to be saved, but there were
// validation errors.
this.showValidationErrors();
break;
}
},
/**
* Reverts the modified value to the original, before editing started.
*/
revert: function () {
// A no-op by default; each editor should implement reverting itself.
// Note that if the in-place editor does not cause the FieldModel's
// element to be modified, then nothing needs to happen.
},
/**
* Saves the modified value in the in-place editor for this field.
*/
save: function () {
var fieldModel = this.fieldModel;
var editorModel = this.model;
var backstageId = 'quickedit_backstage-' + this.fieldModel.id.replace(/[\/\[\]\_\s]/g, '-');
function fillAndSubmitForm(value) {
var $form = $('#' + backstageId).find('form');
// Fill in the value in any <input> that isn't hidden or a submit
// button.
$form.find(':input[type!="hidden"][type!="submit"]:not(select)')
// Don't mess with the node summary.
.not('[name$="\\[summary\\]"]').val(value);
// Submit the form.
$form.find('.quickedit-form-submit').trigger('click.quickedit');
}
var formOptions = {
fieldID: this.fieldModel.get('fieldID'),
$el: this.$el,
nocssjs: true,
other_view_modes: fieldModel.findOtherViewModes(),
// Reset an existing entry for this entity in the PrivateTempStore (if
// any) when saving the field. Logically speaking, this should happen in
// a separate request because this is an entity-level operation, not a
// field-level operation. But that would require an additional request,
// that might not even be necessary: it is only when a user saves a
// first changed field for an entity that this needs to happen:
// precisely now!
reset: !this.fieldModel.get('entity').get('inTempStore')
};
var self = this;
Drupal.quickedit.util.form.load(formOptions, function (form, ajax) {
// Create a backstage area for storing forms that are hidden from view
// (hence "backstage" — since the editing doesn't happen in the form, it
// happens "directly" in the content, the form is only used for saving).
var $backstage = $(Drupal.theme('quickeditBackstage', {id: backstageId})).appendTo('body');
// Hidden forms are stuffed into the backstage container for this field.
var $form = $(form).appendTo($backstage);
// Disable the browser's HTML5 validation; we only care about server-
// side validation. (Not disabling this will actually cause problems
// because browsers don't like to set HTML5 validation errors on hidden
// forms.)
$form.prop('novalidate', true);
var $submit = $form.find('.quickedit-form-submit');
self.formSaveAjax = Drupal.quickedit.util.form.ajaxifySaving(formOptions, $submit);
function removeHiddenForm() {
Drupal.quickedit.util.form.unajaxifySaving(self.formSaveAjax);
delete self.formSaveAjax;
$backstage.remove();
}
// Successfully saved.
self.formSaveAjax.commands.quickeditFieldFormSaved = function (ajax, response, status) {
removeHiddenForm();
// First, transition the state to 'saved'.
fieldModel.set('state', 'saved');
// Second, set the 'htmlForOtherViewModes' attribute, so that when
// this field is rerendered, the change can be propagated to other
// instances of this field, which may be displayed in different view
// modes.
fieldModel.set('htmlForOtherViewModes', response.other_view_modes);
// Finally, set the 'html' attribute on the field model. This will
// cause the field to be rerendered.
fieldModel.set('html', response.data);
};
// Unsuccessfully saved; validation errors.
self.formSaveAjax.commands.quickeditFieldFormValidationErrors = function (ajax, response, status) {
removeHiddenForm();
editorModel.set('validationErrors', response.data);
fieldModel.set('state', 'invalid');
};
// The quickeditFieldForm AJAX command is only called upon loading the
// form for the first time, and when there are validation errors in the
// form; Form API then marks which form items have errors. This is
// useful for the form-based in-place editor, but pointless for any
// other: the form itself won't be visible at all anyway! So, we just
// ignore it.
self.formSaveAjax.commands.quickeditFieldForm = function () {};
fillAndSubmitForm(editorModel.get('currentValue'));
});
},
/**
* Shows validation error messages.
*
* Should be called when the state is changed to 'invalid'.
*/
showValidationErrors: function () {
var $errors = $('<div class="quickedit-validation-errors"></div>')
.append(this.model.get('validationErrors'));
this.getEditedElement()
.addClass('quickedit-validation-error')
.after($errors);
},
/**
* Cleans up validation error messages.
*
* Should be called when the state is changed to 'candidate' or 'saving'. In
* the case of the latter: the user has modified the value in the in-place
* editor again to attempt to save again. In the case of the latter: the
* invalid value was discarded.
*/
removeValidationErrors: function () {
this.getEditedElement()
.removeClass('quickedit-validation-error')
.next('.quickedit-validation-errors')
.remove();
}
});
}(jQuery, Backbone, Drupal));
;
/**
* @file
* Provides theme functions for all of Quick Edit's client-side HTML.
*/
(function ($, Drupal) {
'use strict';
/**
* Theme function for a "backstage" for the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* The id to apply to the backstage.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditBackstage = function (settings) {
var html = '';
html += '<div id="' + settings.id + '" />';
return html;
};
/**
* Theme function for a toolbar container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* the id to apply to the backstage.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditEntityToolbar = function (settings) {
var html = '';
html += '<div id="' + settings.id + '" class="quickedit quickedit-toolbar-container clearfix">';
html += '<i class="quickedit-toolbar-pointer"></i>';
html += '<div class="quickedit-toolbar-content">';
html += '<div class="quickedit-toolbar quickedit-toolbar-entity clearfix icon icon-pencil">';
html += '<div class="quickedit-toolbar-label" />';
html += '</div>';
html += '<div class="quickedit-toolbar quickedit-toolbar-field clearfix" />';
html += '</div><div class="quickedit-toolbar-lining"></div></div>';
return html;
};
/**
* Theme function for a toolbar container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.entityLabel
* The title of the active entity.
* @param {string} settings.fieldLabel
* The label of the highlighted or active field.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditEntityToolbarLabel = function (settings) {
// @todo Add XSS regression test coverage in https://www.drupal.org/node/2547437
return '<span class="field">' + Drupal.checkPlain(settings.fieldLabel) + '</span>' + Drupal.checkPlain(settings.entityLabel);
};
/**
* Element defining a containing box for the placement of the entity toolbar.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditEntityToolbarFence = function () {
return '<div id="quickedit-toolbar-fence" />';
};
/**
* Theme function for a toolbar container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* The id to apply to the toolbar container.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditFieldToolbar = function (settings) {
return '<div id="' + settings.id + '" />';
};
/**
* Theme function for a toolbar toolgroup of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} [settings.id]
* The id of the toolgroup.
* @param {string} settings.classes
* The class of the toolgroup.
* @param {Array} settings.buttons
* See {@link Drupal.theme.quickeditButtons}.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditToolgroup = function (settings) {
// Classes.
var classes = (settings.classes || []);
classes.unshift('quickedit-toolgroup');
var html = '';
html += '<div class="' + classes.join(' ') + '"';
if (settings.id) {
html += ' id="' + settings.id + '"';
}
html += '>';
html += Drupal.theme('quickeditButtons', {buttons: settings.buttons});
html += '</div>';
return html;
};
/**
* Theme function for buttons of the Quick Edit module.
*
* Can be used for the buttons both in the toolbar toolgroups and in the
* modal.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {Array} settings.buttons
* - String type: the type of the button (defaults to 'button')
* - Array classes: the classes of the button.
* - String label: the label of the button.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditButtons = function (settings) {
var html = '';
for (var i = 0; i < settings.buttons.length; i++) {
var button = settings.buttons[i];
if (!button.hasOwnProperty('type')) {
button.type = 'button';
}
// Attributes.
var attributes = [];
var attrMap = settings.buttons[i].attributes || {};
for (var attr in attrMap) {
if (attrMap.hasOwnProperty(attr)) {
attributes.push(attr + ((attrMap[attr]) ? '="' + attrMap[attr] + '"' : ''));
}
}
html += '<button type="' + button.type + '" class="' + button.classes + '"' + ' ' + attributes.join(' ') + '>';
html += button.label;
html += '</button>';
}
return html;
};
/**
* Theme function for a form container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* The id to apply to the toolbar container.
* @param {string} settings.loadingMsg
* The message to show while loading.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditFormContainer = function (settings) {
var html = '';
html += '<div id="' + settings.id + '" class="quickedit-form-container">';
html += ' <div class="quickedit-form">';
html += ' <div class="placeholder">';
html += settings.loadingMsg;
html += ' </div>';
html += ' </div>';
html += '</div>';
return html;
};
})(jQuery, Drupal);
;
|
packages/material-ui-icons/src/SettingsInputHdmi.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M18 7V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3H5v6l3 6v3h8v-3l3-6V7h-1zM8 4h8v3h-2V5h-1v2h-2V5h-1v2H8V4z" /></React.Fragment>
, 'SettingsInputHdmi');
|
codes/chapter05/react-router-v4/basic/demo06/app/components/NoMatch.js | atlantis1024/react-step-by-step | import React from 'react';
class NoMatch extends React.PureComponent {
render() {
return (
<div>
<h2>无法匹配 <code>{this.props.location.pathname}</code></h2>
</div>
)
}
}
export default NoMatch;
|
sagewui/themes/newUI/static/mathjax/unpacked/extensions/TeX/mhchem.js | damahou/sagewui | /* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/extensions/TeX/mhchem.js
*
* Implements the \ce command for handling chemical formulas
* from the mhchem LaTeX package.
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2011-2013 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/mhchem"] = {
version: "2.2"
};
MathJax.Hub.Register.StartupHook("TeX Jax Ready",function () {
var TEX = MathJax.InputJax.TeX;
/*
* This is the main class for handing the \ce and related commands.
* Its main method is Parse() which takes the argument to \ce and
* returns the corresponding TeX string.
*/
var CE = MathJax.Object.Subclass({
string: "", // the \ce string being parsed
i: 0, // the current position in the string
tex: "", // the processed TeX result
atom: false, // last processed token is an atom
sup: "", // pending superscript
sub: "", // pending subscript
//
// Store the string when a CE object is created
//
Init: function (string) {this.string = string},
//
// These are the special characters and the methods that
// handle them. All others are passed through verbatim.
//
ParseTable: {
'-': "Minus",
'+': "Plus",
'(': "Open",
')': "Close",
'[': "Open",
']': "Close",
'<': "Less",
'^': "Superscript",
'_': "Subscript",
'*': "Dot",
'.': "Dot",
'=': "Equal",
'#': "Pound",
'$': "Math",
'\\': "Macro",
' ': "Space"
},
//
// Basic arrow names for reactions
//
Arrows: {
'->': "rightarrow",
'<-': "leftarrow",
'<->': "leftrightarrow",
'<=>': "rightleftharpoons",
'<=>>': "Rightleftharpoons",
'<<=>': "Leftrightharpoons",
'^': "uparrow",
'v': "downarrow"
},
//
// Implementations for the various bonds
// (the ~ ones are hacks that don't work well in NativeMML)
//
Bonds: {
'-': "-",
'=': "=",
'#': "\\equiv",
'~': "\\tripledash",
'~-': "\\begin{CEstack}{}\\tripledash\\\\-\\end{CEstack}",
'~=': "\\raise2mu{\\begin{CEstack}{}\\tripledash\\\\-\\\\-\\end{CEstack}}",
'~--': "\\raise2mu{\\begin{CEstack}{}\\tripledash\\\\-\\\\-\\end{CEstack}}",
'-~-': "\\raise2mu{\\begin{CEstack}{}-\\\\\\tripledash\\\\-\\end{CEstack}}",
'...': "{\\cdot}{\\cdot}{\\cdot}",
'....': "{\\cdot}{\\cdot}{\\cdot}{\\cdot}",
'->': "\\rightarrow",
'<-': "\\leftarrow",
'??': "\\text{??}" // unknown bond
},
//
// This converts the CE string to a TeX string.
// It loops through the string and calls the proper
// method depending on the ccurrent character.
//
Parse: function () {
this.tex = ""; this.atom = false;
while (this.i < this.string.length) {
var c = this.string.charAt(this.i);
if (c.match(/[a-z]/i)) {this.ParseLetter()}
else if (c.match(/[0-9]/)) {this.ParseNumber()}
else {this["Parse"+(this.ParseTable[c]||"Other")](c)}
}
this.FinishAtom();
return this.tex;
},
//
// Make an atom name or a down arrow
//
ParseLetter: function () {
this.FinishAtom();
if (this.Match(/^v( |$)/)) {
this.tex += "{\\"+this.Arrows["v"]+"}";
} else {
this.tex += "\\text{"+this.Match(/^[a-z]+/i)+"}";
this.atom = true;
}
},
//
// Make a number or fraction preceeding an atom,
// or a subscript for an atom.
//
ParseNumber: function () {
var n = this.Match(/^\d+/);
if (this.atom && !this.sub) {
this.sub = n;
} else {
this.FinishAtom();
var match = this.Match(/^\/\d+/);
if (match) {
var frac = "\\frac{"+n+"}{"+match.substr(1)+"}";
this.tex += "\\mathchoice{\\textstyle"+frac+"}{"+frac+"}{"+frac+"}{"+frac+"}";
} else {
this.tex += n;
if (this.i < this.string.length) {this.tex += "\\,"}
}
}
},
//
// Make a superscript minus, or an arrow, or a single bond.
//
ParseMinus: function (c) {
if (this.atom && (this.i === this.string.length-1 || this.string.charAt(this.i+1) === " ")) {
this.sup += c;
} else {
this.FinishAtom();
if (this.string.substr(this.i,2) === "->") {this.i += 2; this.AddArrow("->"); return}
else {this.tex += "{-}"}
}
this.i++;
},
//
// Make a superscript plus, or pass it through
//
ParsePlus: function (c) {
if (this.atom) {this.sup += c} else {this.FinishAtom(); this.tex += c}
this.i++;
},
//
// Handle dots and double or triple bonds
//
ParseDot: function (c) {this.FinishAtom(); this.tex += "\\cdot "; this.i++},
ParseEqual: function (c) {this.FinishAtom(); this.tex += "{=}"; this.i++},
ParsePound: function (c) {this.FinishAtom(); this.tex += "{\\equiv}"; this.i++},
//
// Look for (v) or (^), or pass it through
//
ParseOpen: function (c) {
this.FinishAtom();
var match = this.Match(/^\([v^]\)/);
if (match) {this.tex += "{\\"+this.Arrows[match.charAt(1)]+"}"}
else {this.tex += "{"+c; this.i++}
},
//
// Allow ) and ] to get super- and subscripts
//
ParseClose: function (c) {this.FinishAtom(); this.atom = true; this.tex += c+"}"; this.i++},
//
// Make the proper arrow
//
ParseLess: function (c) {
this.FinishAtom();
var arrow = this.Match(/^(<->?|<=>>?|<<=>)/);
if (!arrow) {this.tex += c; this.i++} else {this.AddArrow(arrow)}
},
//
// Look for a superscript, or an up arrow
//
ParseSuperscript: function (c) {
c = this.string.charAt(++this.i);
if (c === "{") {
this.i++; var m = this.Find("}");
if (m === "-.") {this.sup += "{-}{\\cdot}"}
else if (m) {this.sup += CE(m).Parse().replace(/^\{-\}/,"-")}
} else if (c === " " || c === "") {
this.tex += "{\\"+this.Arrows["^"]+"}"; this.i++;
} else {
var n = this.Match(/^(\d+|-\.)/);
if (n) {this.sup += n}
}
},
//
// Look for subscripts
//
ParseSubscript: function (c) {
if (this.string.charAt(++this.i) == "{") {
this.i++; this.sub += CE(this.Find("}")).Parse().replace(/^\{-\}/,"-");
} else {
var n = this.Match(/^\d+/);
if (n) {this.sub += n}
}
},
//
// Look for raw TeX code to include
//
ParseMath: function (c) {
this.FinishAtom();
this.i++; this.tex += this.Find(c);
},
//
// Look for specific macros for bonds
// and allow \} to have subscripts
//
ParseMacro: function (c) {
this.FinishAtom();
this.i++; var match = this.Match(/^([a-z]+|.)/i)||" ";
if (match === "sbond") {this.tex += "{-}"}
else if (match === "dbond") {this.tex += "{=}"}
else if (match === "tbond") {this.tex += "{\\equiv}"}
else if (match === "bond") {
var bond = (this.Match(/^\{.*?\}/)||"");
bond = bond.substr(1,bond.length-2);
this.tex += "{"+(this.Bonds[bond]||"\\text{??}")+"}";
}
else if (match === "{") {this.tex += "{\\{"}
else if (match === "}") {this.tex += "\\}}"; this.atom = true}
else {this.tex += c+match}
},
//
// Ignore spaces
//
ParseSpace: function (c) {this.FinishAtom(); this.i++},
//
// Pass anything else on verbatim
//
ParseOther: function (c) {this.FinishAtom(); this.tex += c; this.i++},
//
// Process an arrow (looking for brackets for above and below)
//
AddArrow: function (arrow) {
var c = this.Match(/^[CT]\[/);
if (c) {this.i--; c = c.charAt(0)}
var above = this.GetBracket(c), below = this.GetBracket(c);
arrow = this.Arrows[arrow];
if (above || below) {
if (below) {arrow += "["+below+"]"}
arrow += "{"+above+"}";
arrow = "\\mathrel{\\x"+arrow+"}";
} else {
arrow = "\\long"+arrow+" ";
}
this.tex += arrow;
},
//
// Handle the super and subscripts for an atom
//
FinishAtom: function () {
if (this.sup || this.sub) {
if (this.sup && this.sub && !this.atom) {
//
// right-justify super- and subscripts when they are before the atom
//
var sup = this.sup, sub = this.sub;
if (!sup.match(/\d/)) {sup += "\\vphantom{0}"} // force common heights
if (!sub.match(/\d/)) {sub += "\\vphantom{0}"}
this.tex += "\\raise 1pt{\\scriptstyle\\begin{CEscriptstack}"+sup+"\\\\"+
sub+"\\end{CEscriptstack}}\\kern-.125em ";
} else {
if (!this.sup) {this.sup = "\\Space{0pt}{0pt}{.2em}"} // forces subscripts to align properly
this.tex += "^{"+this.sup+"}_{"+this.sub+"}";
}
this.sup = this.sub = "";
}
this.atom = false;
},
//
// Find a bracket group and handle C and T prefixes
//
GetBracket: function (c) {
if (this.string.charAt(this.i) !== "[") {return ""}
this.i++; var bracket = this.Find("]");
if (c === "C") {bracket = "\\ce{"+bracket+"}"} else
if (c === "T") {
if (!bracket.match(/^\{.*\}$/)) {bracket = "{"+bracket+"}"}
bracket = "\\text"+bracket;
};
return bracket;
},
//
// Check if the string matches a regular expression
// and move past it if so, returning the match
//
Match: function (regex) {
var match = regex.exec(this.string.substr(this.i));
if (match) {match = match[0]; this.i += match.length}
return match;
},
//
// Find a particular character, skipping over braced groups
//
Find: function (c) {
var m = this.string.length, i = this.i, braces = 0;
while (this.i < m) {
var C = this.string.charAt(this.i++);
if (C === c && braces === 0) {return this.string.substr(i,this.i-i-1)}
if (C === "{") {braces++} else
if (C === "}") {
if (braces) {braces--}
else {
TEX.Error(["ExtraCloseMissingOpen","Extra close brace or missing open brace"])
}
}
}
if (braces) {TEX.Error(["MissingCloseBrace","Missing close brace"])}
TEX.Error(["NoClosingChar","Can't find closing %1",c]);
}
});
MathJax.Extension["TeX/mhchem"].CE = CE;
/***************************************************************************/
TEX.Definitions.Add({
macros: {
//
// Set up the macros for chemistry
//
ce: 'CE',
cf: 'CE',
cee: 'CE',
//
// Make these load AMSmath package (redefined below when loaded)
//
xleftrightarrow: ['Extension','AMSmath'],
xrightleftharpoons: ['Extension','AMSmath'],
xRightleftharpoons: ['Extension','AMSmath'],
xLeftrightharpoons: ['Extension','AMSmath'],
// FIXME: These don't work well in FF NativeMML mode
longrightleftharpoons: ["Macro","\\stackrel{\\textstyle{{-}\\!\\!{\\rightharpoonup}}}{\\smash{{\\leftharpoondown}\\!\\!{-}}}"],
longRightleftharpoons: ["Macro","\\stackrel{\\textstyle{-}\\!\\!{\\rightharpoonup}}{\\small\\smash\\leftharpoondown}"],
longLeftrightharpoons: ["Macro","\\stackrel{\\rightharpoonup}{{{\\leftharpoondown}\\!\\!\\textstyle{-}}}"],
//
// Add \hyphen used in some mhchem examples
//
hyphen: ["Macro","\\text{-}"],
//
// Needed for \bond for the ~ forms
//
tripledash: ["Macro","\\raise3mu{\\tiny\\text{-}\\kern2mu\\text{-}\\kern2mu\\text{-}}"]
},
//
// Needed for \bond for the ~ forms
//
environment: {
CEstack: ['Array',null,null,null,'r',null,"0.001em",'T',1],
CEscriptstack: ['Array',null,null,null,'r',null,"0.2em",'S',1]
}
},null,true);
if (!MathJax.Extension["TeX/AMSmath"]) {
TEX.Definitions.Add({
macros: {
xrightarrow: ['Extension','AMSmath'],
xleftarrow: ['Extension','AMSmath']
}
},null,true);
}
//
// These arrows need to wait until AMSmath is loaded
//
MathJax.Hub.Register.StartupHook("TeX AMSmath Ready",function () {
TEX.Definitions.Add({
macros: {
//
// Some of these are hacks for now
//
xleftrightarrow: ['xArrow',0x2194,6,6],
xrightleftharpoons: ['xArrow',0x21CC,5,7], // FIXME: doesn't stretch in HTML-CSS output
xRightleftharpoons: ['xArrow',0x21CC,5,7], // FIXME: how should this be handled?
xLeftrightharpoons: ['xArrow',0x21CC,5,7]
}
},null,true);
});
TEX.Parse.Augment({
//
// Implements \ce and friends
//
CE: function (name) {
var arg = this.GetArgument(name);
var tex = CE(arg).Parse();
this.string = tex + this.string.substr(this.i); this.i = 0;
}
});
//
// Indicate that the extension is ready
//
MathJax.Hub.Startup.signal.Post("TeX mhchem Ready");
});
MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/mhchem.js");
|
src/svg-icons/editor/border-top.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderTop = (props) => (
<SvgIcon {...props}>
<path d="M7 21h2v-2H7v2zm0-8h2v-2H7v2zm4 0h2v-2h-2v2zm0 8h2v-2h-2v2zm-8-4h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2v-2H3v2zm0-4h2V7H3v2zm8 8h2v-2h-2v2zm8-8h2V7h-2v2zm0 4h2v-2h-2v2zM3 3v2h18V3H3zm16 14h2v-2h-2v2zm-4 4h2v-2h-2v2zM11 9h2V7h-2v2zm8 12h2v-2h-2v2zm-4-8h2v-2h-2v2z"/>
</SvgIcon>
);
EditorBorderTop = pure(EditorBorderTop);
EditorBorderTop.displayName = 'EditorBorderTop';
EditorBorderTop.muiName = 'SvgIcon';
export default EditorBorderTop;
|
src/pages/moduleHomePage/recentReply/RecentReply.js | HeliumLau/Hoop-react | import React from 'react';
import ArticleList from 'components/ArticleList.js';
export default class RecentReply extends React.Component {
constructor(props) {
super(props);
this.state = {
articlelist: [
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
},
{
title: '惊!安东尼签约火箭竟只为他!',
author: 'Helium',
time: '刚刚',
recommend: 1,
like: 100,
comment: 1221
}
]
}
}
render() {
return (
<ArticleList list={this.state.articlelist} />
)
}
} |
App.js | jstrimpel/redux-react-router | import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
static willTransitionTo() {
console.log('willTransitionTo in App component');
}
render() {
let { fname, lname } = this.props;
return (
<div>Hello {fname} {lname}!</div>
);
}
}
function select(state) {
return state;
}
export default connect(select)(App) |
tests/routes/Counter/components/Counter.spec.js | Picta-it/Jammy | import React from 'react'
import { bindActionCreators } from 'redux'
import { Counter } from 'routes/Counter/components/Counter'
import { shallow } from 'enzyme'
describe('(Component) Counter', () => {
let _props, _spies, _wrapper
beforeEach(() => {
_spies = {}
_props = {
counter : 5,
...bindActionCreators({
doubleAsync : (_spies.doubleAsync = sinon.spy()),
increment : (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
}
_wrapper = shallow(<Counter {..._props} />)
})
it('Should render as a <div>.', () => {
expect(_wrapper.is('div')).to.equal(true)
})
it('Should render with an <h2> that includes Sample Counter text.', () => {
expect(_wrapper.find('h2').text()).to.match(/Counter:/)
})
it('Should render props.counter at the end of the sample counter <h2>.', () => {
expect(_wrapper.find('h2').text()).to.match(/5$/)
_wrapper.setProps({ counter: 8 })
expect(_wrapper.find('h2').text()).to.match(/8$/)
})
it('Should render exactly two buttons.', () => {
expect(_wrapper.find('button')).to.have.length(2)
})
describe('An increment button...', () => {
let _button
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment')
})
it('has bootstrap classes', () => {
expect(_button.hasClass('btn btn-default')).to.be.true
})
it('Should dispatch a `increment` action when clicked', () => {
_spies.dispatch.should.have.not.been.called
_button.simulate('click')
_spies.dispatch.should.have.been.called
_spies.increment.should.have.been.called
})
})
describe('A Double (Async) button...', () => {
let _button
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)')
})
it('has bootstrap classes', () => {
expect(_button.hasClass('btn btn-default')).to.be.true
})
it('Should dispatch a `doubleAsync` action when clicked', () => {
_spies.dispatch.should.have.not.been.called
_button.simulate('click')
_spies.dispatch.should.have.been.called
_spies.doubleAsync.should.have.been.called
})
})
})
|
src/higherOrders/Pagination.js | lenxeon/react-ui | import React from 'react'
import { objectAssign } from '../utils/objects'
import PropTypes from '../utils/proptypes'
import PureRender from '../mixins/PureRender'
export default function (Component) {
class Pagination extends React.Component {
constructor (props) {
super(props)
this.state = { page: 1 }
this.handleChange = this.handleChange.bind(this)
}
getData (pagination) {
let data = this.props.data
if (pagination) {
const { page, size } = pagination
data = data.slice((page - 1) * size, page * size)
}
return data
}
handleChange (page) {
const { onChange } = this.props.pagination
if (typeof onChange === 'function') {
onChange(page)
} else {
this.setState({ page })
}
}
getPagination (pagination) {
if (!pagination || !Array.isArray(this.props.data)) return
let props = objectAssign(
{
page: this.state.page,
size: 20,
position: 'center',
total: this.props.data.length
},
pagination.props || pagination
)
props.onChange = this.handleChange
return props
}
render () {
const { pagination, ...props } = this.props
let pagi = this.getPagination(pagination)
return (
<Component {...props}
data={this.getData(pagi)}
pagination={pagi}
/>
)
}
}
Pagination.propTypes = {
data: PropTypes.array_element_string,
pagination: PropTypes.element_object
}
Pagination.defaultProps = {
data: []
}
return PureRender()(Pagination)
}
|
pathfinder/vtables/appmap2cim/webpack.config.js | leanix/leanix-custom-reports | var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'report.[chunkhash].js'
},
module: {
rules: [
/**
* Bundle JavaScript (ES6)
*/
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
},
/**
* Bundle CSS, images and fonts
*/
{
test: /\.css$/,
use: [
require.resolve('style-loader'), {
loader: require.resolve('css-loader')
}
]
}, {
test: /\.(otf|ttf|woff|woff2)$/,
use: {
loader: 'url-loader?limit=10000'
}
}, {
test: /\.(jpg|png|gif)$/,
use: {
loader: 'url-loader?limit=10000'
}
}, {
test: /\.(eot|svg)$/,
use: {
loader: 'file-loader'
}
}
]
},
plugins: [
/**
* Make jquery and lodash globally available
* (dependencies of @leanix/reporting library)
*/
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'_': 'lodash'
}),
/**
* Copy assets into dist folder.
*/
new CopyWebpackPlugin([{
from: 'src/assets',
to: 'assets'
}
]),
/**
* Insert created bundles as script tags at the end
* of the body tag in index.html
*/
new HtmlWebpackPlugin({
inject: true,
template: 'src/index.html'
})
],
devServer: {
headers: {
'Access-Control-Allow-Origin': '*'
}
}
}
|
admin/client/App/shared/Popout/PopoutFooter.js | rafmsou/keystone | /**
* Render a footer for a popout
*/
import React from 'react';
const BUTTON_BASE_CLASSNAME = 'Popout__footer__button Popout__footer__button--';
const PopoutFooter = React.createClass({
displayName: 'PopoutFooter',
propTypes: {
children: React.PropTypes.node,
primaryButtonAction: React.PropTypes.func,
primaryButtonIsSubmit: React.PropTypes.bool,
primaryButtonLabel: React.PropTypes.string,
secondaryButtonAction: React.PropTypes.func,
secondaryButtonLabel: React.PropTypes.string,
},
// Render a primary button
renderPrimaryButton () {
if (!this.props.primaryButtonLabel) return null;
return (
<button
type={this.props.primaryButtonIsSubmit ? 'submit' : 'button'}
className={BUTTON_BASE_CLASSNAME + 'primary'}
onClick={this.props.primaryButtonAction}
>
{this.props.primaryButtonLabel}
</button>
);
},
// Render a secondary button
renderSecondaryButton () {
if (!this.props.secondaryButtonAction || !this.props.secondaryButtonLabel) return null;
return (
<button
type="button"
className={BUTTON_BASE_CLASSNAME + 'secondary'}
onClick={this.props.secondaryButtonAction}
>
{this.props.secondaryButtonLabel}
</button>
);
},
render () {
return (
<div className="Popout__footer">
{this.renderPrimaryButton()}
{this.renderSecondaryButton()}
{this.props.children}
</div>
);
},
});
module.exports = PopoutFooter;
|
src/index.js | ETBlue/jrpilot | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
assets/javascripts/kitten/components/graphics/icons/title-1-icon/index.js | KissKissBankBank/kitten | import React from 'react'
import PropTypes from 'prop-types'
export const Title1Icon = ({ color, title, ...props }) => (
<svg
width="14"
height="12"
viewBox="0 0 14 12"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
{title && <title>{title}</title>}
<path
d="M9.008 0v2.56h-3.04v8.64H3.04V2.56H0V0h9.008zm3.442 4.2v5.4h1.53v1.6H9V9.6h1.62V6.24l-.122.08c-.17.102-.369.184-.598.245a3.469 3.469 0 01-.9.115V5.16l.21-.016c.277-.031.544-.104.8-.219a1.47 1.47 0 00.73-.725h1.71z"
fill={color}
/>
</svg>
)
Title1Icon.propTypes = {
color: PropTypes.string,
title: PropTypes.string,
}
Title1Icon.defaultProps = {
color: '#222',
title: '',
}
|
renderer/components/Channels/ChannelCloseDialog.js | LN-Zap/zap-desktop | import React from 'react'
import PropTypes from 'prop-types'
import { Flex, Box } from 'rebass/styled-components'
import { FormattedMessage, injectIntl } from 'react-intl'
import { withFieldState } from 'informed'
import { intlShape } from '@zap/i18n'
import Delete from 'components/Icon/Delete'
import { Dialog, Text, Heading, Button, DialogOverlay } from 'components/UI'
import { Checkbox, Form, TransactionFeeInput } from 'components/Form'
import messages from './messages'
import {
TRANSACTION_SPEED_SLOW,
TRANSACTION_SPEED_MEDIUM,
TRANSACTION_SPEED_FAST,
} from './constants'
const DialogWrapper = ({
intl,
isForceClose,
isOpen,
lndTargetConfirmations,
onClose,
onCancel,
csvDelay,
}) => {
if (!isOpen) {
return null
}
const checkboxFieldName = 'actionACK'
// bind button disabled state to a form field
const CloseChannelButton = withFieldState(checkboxFieldName)(({ fieldState, ...rest }) => (
<Button isDisabled={isForceClose && !fieldState.value} {...rest} />
))
const buttons = (
<>
<CloseChannelButton type="submit" variant="danger">
<FormattedMessage
{...(isForceClose
? messages.close_channel_dialog_force_close_text
: messages.close_channel_dialog_close_text)}
/>
</CloseChannelButton>
<Button onClick={onCancel} type="button" variant="secondary">
<FormattedMessage {...messages.close_channel_dialog_cancel_text} />
</Button>
</>
)
const header = (
<Flex alignItems="center" flexDirection="column" mb={4}>
<Box color="superRed" mb={2}>
<Delete height={72} width={72} />
</Box>
<Heading.H1 textAlign="center">
<FormattedMessage {...messages.close_channel_dialog_header} />
</Heading.H1>
</Flex>
)
const handleSubmit = ({ speed }) => {
const speedMap = {
[TRANSACTION_SPEED_SLOW]: 'slow',
[TRANSACTION_SPEED_MEDIUM]: 'medium',
[TRANSACTION_SPEED_FAST]: 'fast',
}
const speedKey = speedMap[speed]
const targetConf = lndTargetConfirmations[speedKey]
onClose(targetConf, intl.formatMessage({ ...messages.close_channel_notification }))
}
return (
<DialogOverlay alignItems="center" justifyContent="center">
<Form onSubmit={handleSubmit}>
<Dialog buttons={buttons} header={header} onClose={onCancel} width={640}>
<Flex alignItems="center" flexDirection="column">
<Text color="gray" mb={2} textAlign={isForceClose ? 'left' : 'center'}>
<FormattedMessage
{...(isForceClose
? messages.close_channel_dialog_force_warning
: messages.close_channel_dialog_warning)}
values={{ csvDelay }}
/>
</Text>
<TransactionFeeInput
field="speed"
hasFee={false}
isQueryingFees={false}
label={intl.formatMessage({ ...messages.fee })}
lndTargetConfirmations={lndTargetConfirmations}
required
/>
{isForceClose && (
<Checkbox
field={checkboxFieldName}
label={intl.formatMessage({ ...messages.close_channel_dialog_acknowledgement })}
mt={4}
/>
)}
</Flex>
</Dialog>
</Form>
</DialogOverlay>
)
}
DialogWrapper.propTypes = {
csvDelay: PropTypes.number.isRequired,
intl: intlShape.isRequired,
isForceClose: PropTypes.bool.isRequired,
isOpen: PropTypes.bool.isRequired,
lndTargetConfirmations: PropTypes.shape({
fast: PropTypes.number.isRequired,
medium: PropTypes.number.isRequired,
slow: PropTypes.number.isRequired,
}).isRequired,
onCancel: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
}
export default injectIntl(DialogWrapper)
|
app/src/FlashcardExplorer.js | subnotes/gemini | /**
* Page Component for Flashcard Manager
*/
// import node packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// import local components
import FlashcardContainer from './containers/FlashcardContainer';
import FlashcardHelper from './helpers/FlashcardHelper';
import PageDiv from './presenters/PageDiv';
// Component Metadata
const propTypes = {
library: PropTypes.object.isRequired,
};
const defaultProps = {
library: {},
};
// Component Class for Explorer View
class FlashcardExplorer extends Component {
constructor (props) {
super(props);
// Member Variables
this.state = {
flashcards: FlashcardHelper.getAllCards(this.props.library),
};
// Function Bindings
this.handleDeleteCard = this.handleDeleteCard.bind(this);
this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this);
this.render = this.render.bind(this);
} // end constructor
// Class Functions
handleDeleteCard (idx) {
alert("Delete from flashcard manager not yet implemented.");
} // end handleDeleteCard
componentWillReceiveProps(nextProps) {
if (nextProps !== this.props) {
var newCards = FlashcardHelper.getAllCards(nextProps.library);
this.setState({ flashcards: newCards });
}
} // end componentWillReceiveProps
render () {
if (this.state.flashcards.length > 0) {
return (
<PageDiv width='60%'>
{this.state.flashcards.map(card => (
<FlashcardContainer
flashcard={card}
viewType="li"
readOnly={true} />
))}
</PageDiv>
);
} else {
return (
<PageDiv>
There don't appear to be any flashcards in this notebook yet.
</PageDiv>
);
}
} // end render
}
FlashcardExplorer.propTypes = propTypes;
FlashcardExplorer.defaultProps = defaultProps;
export default FlashcardExplorer;
|
ajax/libs/raven.js/[email protected]/angular,require,vue/raven.js | cdnjs/cdnjs | /*! Raven.js 3.27.0 (200cffcc) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright (c) 2018 Sentry (https://sentry.io) and individual contributors.
* All rights reserved.
* https://github.com/getsentry/sentry-javascript/blob/master/packages/raven-js/LICENSE
*
*/
(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.Raven = 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(_dereq_,module,exports){
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(8).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
_dereq_(7).addPlugin(module.exports);
},{"7":7,"8":8}],2:[function(_dereq_,module,exports){
/*global define*/
/**
* require.js plugin
*
* Automatically wrap define/require callbacks. (Experimental)
*/
function requirePlugin(Raven) {
if (typeof define === 'function' && define.amd) {
window.define = Raven.wrap({deep: false}, define);
window.require = Raven.wrap({deep: false}, _dereq_);
}
}
module.exports = requirePlugin;
_dereq_(7).addPlugin(module.exports);
},{"7":7}],3:[function(_dereq_,module,exports){
/**
* Vue.js 2.0 plugin
*
*/
function formatComponentName(vm) {
if (vm.$root === vm) {
return 'root instance';
}
var name = vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name;
return (
(name ? 'component <' + name + '>' : 'anonymous component') +
(vm._isVue && vm.$options.__file ? ' at ' + vm.$options.__file : '')
);
}
function vuePlugin(Raven, Vue) {
Vue = Vue || window.Vue;
// quit if Vue isn't on the page
if (!Vue || !Vue.config) return;
var _oldOnError = Vue.config.errorHandler;
Vue.config.errorHandler = function VueErrorHandler(error, vm, info) {
var metaData = {};
// vm and lifecycleHook are not always available
if (Object.prototype.toString.call(vm) === '[object Object]') {
metaData.componentName = formatComponentName(vm);
metaData.propsData = vm.$options.propsData;
}
if (typeof info !== 'undefined') {
metaData.lifecycleHook = info;
}
Raven.captureException(error, {
extra: metaData
});
if (typeof _oldOnError === 'function') {
_oldOnError.call(this, error, vm, info);
}
};
}
module.exports = vuePlugin;
_dereq_(7).addPlugin(module.exports);
},{"7":7}],4:[function(_dereq_,module,exports){
function RavenConfigError(message) {
this.name = 'RavenConfigError';
this.message = message;
}
RavenConfigError.prototype = new Error();
RavenConfigError.prototype.constructor = RavenConfigError;
module.exports = RavenConfigError;
},{}],5:[function(_dereq_,module,exports){
var utils = _dereq_(8);
var wrapMethod = function(console, level, callback) {
var originalConsoleLevel = console[level];
var originalConsole = console;
if (!(level in console)) {
return;
}
var sentryLevel = level === 'warn' ? 'warning' : level;
console[level] = function() {
var args = [].slice.call(arguments);
var msg = utils.safeJoin(args, ' ');
var data = {level: sentryLevel, logger: 'console', extra: {arguments: args}};
if (level === 'assert') {
if (args[0] === false) {
// Default browsers message
msg =
'Assertion failed: ' + (utils.safeJoin(args.slice(1), ' ') || 'console.assert');
data.extra.arguments = args.slice(1);
callback && callback(msg, data);
}
} else {
callback && callback(msg, data);
}
// this fails for some browsers. :(
if (originalConsoleLevel) {
// IE9 doesn't allow calling apply on console functions directly
// See: https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function#answer-5473193
Function.prototype.apply.call(originalConsoleLevel, originalConsole, args);
}
};
};
module.exports = {
wrapMethod: wrapMethod
};
},{"8":8}],6:[function(_dereq_,module,exports){
(function (global){
/*global XDomainRequest:false */
var TraceKit = _dereq_(9);
var stringify = _dereq_(10);
var md5 = _dereq_(11);
var RavenConfigError = _dereq_(4);
var utils = _dereq_(8);
var isErrorEvent = utils.isErrorEvent;
var isDOMError = utils.isDOMError;
var isDOMException = utils.isDOMException;
var isError = utils.isError;
var isObject = utils.isObject;
var isPlainObject = utils.isPlainObject;
var isUndefined = utils.isUndefined;
var isFunction = utils.isFunction;
var isString = utils.isString;
var isArray = utils.isArray;
var isEmptyObject = utils.isEmptyObject;
var each = utils.each;
var objectMerge = utils.objectMerge;
var truncate = utils.truncate;
var objectFrozen = utils.objectFrozen;
var hasKey = utils.hasKey;
var joinRegExp = utils.joinRegExp;
var urlencode = utils.urlencode;
var uuid4 = utils.uuid4;
var htmlTreeAsString = utils.htmlTreeAsString;
var isSameException = utils.isSameException;
var isSameStacktrace = utils.isSameStacktrace;
var parseUrl = utils.parseUrl;
var fill = utils.fill;
var supportsFetch = utils.supportsFetch;
var supportsReferrerPolicy = utils.supportsReferrerPolicy;
var serializeKeysForMessage = utils.serializeKeysForMessage;
var serializeException = utils.serializeException;
var sanitize = utils.sanitize;
var wrapConsoleMethod = _dereq_(5).wrapMethod;
var dsnKeys = 'source protocol user pass host port path'.split(' '),
dsnPattern = /^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/;
function now() {
return +new Date();
}
// This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var _document = _window.document;
var _navigator = _window.navigator;
function keepOriginalCallback(original, callback) {
return isFunction(callback)
? function(data) {
return callback(data, original);
}
: callback;
}
// First, check for JSON support
// If there is no JSON, we no-op the core features of Raven
// since JSON is required to encode the payload
function Raven() {
this._hasJSON = !!(typeof JSON === 'object' && JSON.stringify);
// Raven can run in contexts where there's no document (react-native)
this._hasDocument = !isUndefined(_document);
this._hasNavigator = !isUndefined(_navigator);
this._lastCapturedException = null;
this._lastData = null;
this._lastEventId = null;
this._globalServer = null;
this._globalKey = null;
this._globalProject = null;
this._globalContext = {};
this._globalOptions = {
// SENTRY_RELEASE can be injected by https://github.com/getsentry/sentry-webpack-plugin
release: _window.SENTRY_RELEASE && _window.SENTRY_RELEASE.id,
logger: 'javascript',
ignoreErrors: [],
ignoreUrls: [],
whitelistUrls: [],
includePaths: [],
headers: null,
collectWindowErrors: true,
captureUnhandledRejections: true,
maxMessageLength: 0,
// By default, truncates URL values to 250 chars
maxUrlLength: 250,
stackTraceLimit: 50,
autoBreadcrumbs: true,
instrument: true,
sampleRate: 1,
sanitizeKeys: []
};
this._fetchDefaults = {
method: 'POST',
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
referrerPolicy: supportsReferrerPolicy() ? 'origin' : ''
};
this._ignoreOnError = 0;
this._isRavenInstalled = false;
this._originalErrorStackTraceLimit = Error.stackTraceLimit;
// capture references to window.console *and* all its methods first
// before the console plugin has a chance to monkey patch
this._originalConsole = _window.console || {};
this._originalConsoleMethods = {};
this._plugins = [];
this._startTime = now();
this._wrappedBuiltIns = [];
this._breadcrumbs = [];
this._lastCapturedEvent = null;
this._keypressTimeout;
this._location = _window.location;
this._lastHref = this._location && this._location.href;
this._resetBackoff();
// eslint-disable-next-line guard-for-in
for (var method in this._originalConsole) {
this._originalConsoleMethods[method] = this._originalConsole[method];
}
}
/*
* The core Raven singleton
*
* @this {Raven}
*/
Raven.prototype = {
// Hardcode version string so that raven source can be loaded directly via
// webpack (using a build step causes webpack #1617). Grunt verifies that
// this value matches package.json during build.
// See: https://github.com/getsentry/raven-js/issues/465
VERSION: '3.27.0',
debug: false,
TraceKit: TraceKit, // alias to TraceKit
/*
* Configure Raven with a DSN and extra options
*
* @param {string} dsn The public Sentry DSN
* @param {object} options Set of global options [optional]
* @return {Raven}
*/
config: function(dsn, options) {
var self = this;
if (self._globalServer) {
this._logDebug('error', 'Error: Raven has already been configured');
return self;
}
if (!dsn) return self;
var globalOptions = self._globalOptions;
// merge in options
if (options) {
each(options, function(key, value) {
// tags and extra are special and need to be put into context
if (key === 'tags' || key === 'extra' || key === 'user') {
self._globalContext[key] = value;
} else {
globalOptions[key] = value;
}
});
}
self.setDSN(dsn);
// "Script error." is hard coded into browsers for errors that it can't read.
// this is the result of a script being pulled in from an external domain and CORS.
globalOptions.ignoreErrors.push(/^Script error\.?$/);
globalOptions.ignoreErrors.push(/^Javascript error: Script error\.? on line 0$/);
// join regexp rules into one big rule
globalOptions.ignoreErrors = joinRegExp(globalOptions.ignoreErrors);
globalOptions.ignoreUrls = globalOptions.ignoreUrls.length
? joinRegExp(globalOptions.ignoreUrls)
: false;
globalOptions.whitelistUrls = globalOptions.whitelistUrls.length
? joinRegExp(globalOptions.whitelistUrls)
: false;
globalOptions.includePaths = joinRegExp(globalOptions.includePaths);
globalOptions.maxBreadcrumbs = Math.max(
0,
Math.min(globalOptions.maxBreadcrumbs || 100, 100)
); // default and hard limit is 100
var autoBreadcrumbDefaults = {
xhr: true,
console: true,
dom: true,
location: true,
sentry: true
};
var autoBreadcrumbs = globalOptions.autoBreadcrumbs;
if ({}.toString.call(autoBreadcrumbs) === '[object Object]') {
autoBreadcrumbs = objectMerge(autoBreadcrumbDefaults, autoBreadcrumbs);
} else if (autoBreadcrumbs !== false) {
autoBreadcrumbs = autoBreadcrumbDefaults;
}
globalOptions.autoBreadcrumbs = autoBreadcrumbs;
var instrumentDefaults = {
tryCatch: true
};
var instrument = globalOptions.instrument;
if ({}.toString.call(instrument) === '[object Object]') {
instrument = objectMerge(instrumentDefaults, instrument);
} else if (instrument !== false) {
instrument = instrumentDefaults;
}
globalOptions.instrument = instrument;
TraceKit.collectWindowErrors = !!globalOptions.collectWindowErrors;
// return for chaining
return self;
},
/*
* Installs a global window.onerror error handler
* to capture and report uncaught exceptions.
* At this point, install() is required to be called due
* to the way TraceKit is set up.
*
* @return {Raven}
*/
install: function() {
var self = this;
if (self.isSetup() && !self._isRavenInstalled) {
TraceKit.report.subscribe(function() {
self._handleOnErrorStackInfo.apply(self, arguments);
});
if (self._globalOptions.captureUnhandledRejections) {
self._attachPromiseRejectionHandler();
}
self._patchFunctionToString();
if (self._globalOptions.instrument && self._globalOptions.instrument.tryCatch) {
self._instrumentTryCatch();
}
if (self._globalOptions.autoBreadcrumbs) self._instrumentBreadcrumbs();
// Install all of the plugins
self._drainPlugins();
self._isRavenInstalled = true;
}
Error.stackTraceLimit = self._globalOptions.stackTraceLimit;
return this;
},
/*
* Set the DSN (can be called multiple time unlike config)
*
* @param {string} dsn The public Sentry DSN
*/
setDSN: function(dsn) {
var self = this,
uri = self._parseDSN(dsn),
lastSlash = uri.path.lastIndexOf('/'),
path = uri.path.substr(1, lastSlash);
self._dsn = dsn;
self._globalKey = uri.user;
self._globalSecret = uri.pass && uri.pass.substr(1);
self._globalProject = uri.path.substr(lastSlash + 1);
self._globalServer = self._getGlobalServer(uri);
self._globalEndpoint =
self._globalServer + '/' + path + 'api/' + self._globalProject + '/store/';
// Reset backoff state since we may be pointing at a
// new project/server
this._resetBackoff();
},
/*
* Wrap code within a context so Raven can capture errors
* reliably across domains that is executed immediately.
*
* @param {object} options A specific set of options for this context [optional]
* @param {function} func The callback to be immediately executed within the context
* @param {array} args An array of arguments to be called with the callback [optional]
*/
context: function(options, func, args) {
if (isFunction(options)) {
args = func || [];
func = options;
options = {};
}
return this.wrap(options, func).apply(this, args);
},
/*
* Wrap code within a context and returns back a new function to be executed
*
* @param {object} options A specific set of options for this context [optional]
* @param {function} func The function to be wrapped in a new context
* @param {function} _before A function to call before the try/catch wrapper [optional, private]
* @return {function} The newly wrapped functions with a context
*/
wrap: function(options, func, _before) {
var self = this;
// 1 argument has been passed, and it's not a function
// so just return it
if (isUndefined(func) && !isFunction(options)) {
return options;
}
// options is optional
if (isFunction(options)) {
func = options;
options = undefined;
}
// At this point, we've passed along 2 arguments, and the second one
// is not a function either, so we'll just return the second argument.
if (!isFunction(func)) {
return func;
}
// We don't wanna wrap it twice!
try {
if (func.__raven__) {
return func;
}
// If this has already been wrapped in the past, return that
if (func.__raven_wrapper__) {
return func.__raven_wrapper__;
}
} catch (e) {
// Just accessing custom props in some Selenium environments
// can cause a "Permission denied" exception (see raven-js#495).
// Bail on wrapping and return the function as-is (defers to window.onerror).
return func;
}
function wrapped() {
var args = [],
i = arguments.length,
deep = !options || (options && options.deep !== false);
if (_before && isFunction(_before)) {
_before.apply(this, arguments);
}
// Recursively wrap all of a function's arguments that are
// functions themselves.
while (i--) args[i] = deep ? self.wrap(options, arguments[i]) : arguments[i];
try {
// Attempt to invoke user-land function
// NOTE: If you are a Sentry user, and you are seeing this stack frame, it
// means Raven caught an error invoking your application code. This is
// expected behavior and NOT indicative of a bug with Raven.js.
return func.apply(this, args);
} catch (e) {
self._ignoreNextOnError();
self.captureException(e, options);
throw e;
}
}
// copy over properties of the old function
for (var property in func) {
if (hasKey(func, property)) {
wrapped[property] = func[property];
}
}
wrapped.prototype = func.prototype;
func.__raven_wrapper__ = wrapped;
// Signal that this function has been wrapped/filled already
// for both debugging and to prevent it to being wrapped/filled twice
wrapped.__raven__ = true;
wrapped.__orig__ = func;
return wrapped;
},
/**
* Uninstalls the global error handler.
*
* @return {Raven}
*/
uninstall: function() {
TraceKit.report.uninstall();
this._detachPromiseRejectionHandler();
this._unpatchFunctionToString();
this._restoreBuiltIns();
this._restoreConsole();
Error.stackTraceLimit = this._originalErrorStackTraceLimit;
this._isRavenInstalled = false;
return this;
},
/**
* Callback used for `unhandledrejection` event
*
* @param {PromiseRejectionEvent} event An object containing
* promise: the Promise that was rejected
* reason: the value with which the Promise was rejected
* @return void
*/
_promiseRejectionHandler: function(event) {
this._logDebug('debug', 'Raven caught unhandled promise rejection:', event);
this.captureException(event.reason, {
mechanism: {
type: 'onunhandledrejection',
handled: false
}
});
},
/**
* Installs the global promise rejection handler.
*
* @return {raven}
*/
_attachPromiseRejectionHandler: function() {
this._promiseRejectionHandler = this._promiseRejectionHandler.bind(this);
_window.addEventListener &&
_window.addEventListener('unhandledrejection', this._promiseRejectionHandler);
return this;
},
/**
* Uninstalls the global promise rejection handler.
*
* @return {raven}
*/
_detachPromiseRejectionHandler: function() {
_window.removeEventListener &&
_window.removeEventListener('unhandledrejection', this._promiseRejectionHandler);
return this;
},
/**
* Manually capture an exception and send it over to Sentry
*
* @param {error} ex An exception to be logged
* @param {object} options A specific set of options for this error [optional]
* @return {Raven}
*/
captureException: function(ex, options) {
options = objectMerge({trimHeadFrames: 0}, options ? options : {});
if (isErrorEvent(ex) && ex.error) {
// If it is an ErrorEvent with `error` property, extract it to get actual Error
ex = ex.error;
} else if (isDOMError(ex) || isDOMException(ex)) {
// If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers)
// then we just extract the name and message, as they don't provide anything else
// https://developer.mozilla.org/en-US/docs/Web/API/DOMError
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException
var name = ex.name || (isDOMError(ex) ? 'DOMError' : 'DOMException');
var message = ex.message ? name + ': ' + ex.message : name;
return this.captureMessage(
message,
objectMerge(options, {
// neither DOMError or DOMException provide stack trace and we most likely wont get it this way as well
// but it's barely any overhead so we may at least try
stacktrace: true,
trimHeadFrames: options.trimHeadFrames + 1
})
);
} else if (isError(ex)) {
// we have a real Error object
ex = ex;
} else if (isPlainObject(ex)) {
// If it is plain Object, serialize it manually and extract options
// This will allow us to group events based on top-level keys
// which is much better than creating new group when any key/value change
options = this._getCaptureExceptionOptionsFromPlainObject(options, ex);
ex = new Error(options.message);
} else {
// If none of previous checks were valid, then it means that
// it's not a DOMError/DOMException
// it's not a plain Object
// it's not a valid ErrorEvent (one with an error property)
// it's not an Error
// So bail out and capture it as a simple message:
return this.captureMessage(
ex,
objectMerge(options, {
stacktrace: true, // if we fall back to captureMessage, default to attempting a new trace
trimHeadFrames: options.trimHeadFrames + 1
})
);
}
// Store the raw exception object for potential debugging and introspection
this._lastCapturedException = ex;
// TraceKit.report will re-raise any exception passed to it,
// which means you have to wrap it in try/catch. Instead, we
// can wrap it here and only re-raise if TraceKit.report
// raises an exception different from the one we asked to
// report on.
try {
var stack = TraceKit.computeStackTrace(ex);
this._handleStackInfo(stack, options);
} catch (ex1) {
if (ex !== ex1) {
throw ex1;
}
}
return this;
},
_getCaptureExceptionOptionsFromPlainObject: function(currentOptions, ex) {
var exKeys = Object.keys(ex).sort();
var options = objectMerge(currentOptions, {
message:
'Non-Error exception captured with keys: ' + serializeKeysForMessage(exKeys),
fingerprint: [md5(exKeys)],
extra: currentOptions.extra || {}
});
options.extra.__serialized__ = serializeException(ex);
return options;
},
/*
* Manually send a message to Sentry
*
* @param {string} msg A plain message to be captured in Sentry
* @param {object} options A specific set of options for this message [optional]
* @return {Raven}
*/
captureMessage: function(msg, options) {
// config() automagically converts ignoreErrors from a list to a RegExp so we need to test for an
// early call; we'll error on the side of logging anything called before configuration since it's
// probably something you should see:
if (
!!this._globalOptions.ignoreErrors.test &&
this._globalOptions.ignoreErrors.test(msg)
) {
return;
}
options = options || {};
msg = msg + ''; // Make sure it's actually a string
var data = objectMerge(
{
message: msg
},
options
);
var ex;
// Generate a "synthetic" stack trace from this point.
// NOTE: If you are a Sentry user, and you are seeing this stack frame, it is NOT indicative
// of a bug with Raven.js. Sentry generates synthetic traces either by configuration,
// or if it catches a thrown object without a "stack" property.
try {
throw new Error(msg);
} catch (ex1) {
ex = ex1;
}
// null exception name so `Error` isn't prefixed to msg
ex.name = null;
var stack = TraceKit.computeStackTrace(ex);
// stack[0] is `throw new Error(msg)` call itself, we are interested in the frame that was just before that, stack[1]
var initialCall = isArray(stack.stack) && stack.stack[1];
// if stack[1] is `Raven.captureException`, it means that someone passed a string to it and we redirected that call
// to be handled by `captureMessage`, thus `initialCall` is the 3rd one, not 2nd
// initialCall => captureException(string) => captureMessage(string)
if (initialCall && initialCall.func === 'Raven.captureException') {
initialCall = stack.stack[2];
}
var fileurl = (initialCall && initialCall.url) || '';
if (
!!this._globalOptions.ignoreUrls.test &&
this._globalOptions.ignoreUrls.test(fileurl)
) {
return;
}
if (
!!this._globalOptions.whitelistUrls.test &&
!this._globalOptions.whitelistUrls.test(fileurl)
) {
return;
}
// Always attempt to get stacktrace if message is empty.
// It's the only way to provide any helpful information to the user.
if (this._globalOptions.stacktrace || options.stacktrace || data.message === '') {
// fingerprint on msg, not stack trace (legacy behavior, could be revisited)
data.fingerprint = data.fingerprint == null ? msg : data.fingerprint;
options = objectMerge(
{
trimHeadFrames: 0
},
options
);
// Since we know this is a synthetic trace, the top frame (this function call)
// MUST be from Raven.js, so mark it for trimming
// We add to the trim counter so that callers can choose to trim extra frames, such
// as utility functions.
options.trimHeadFrames += 1;
var frames = this._prepareFrames(stack, options);
data.stacktrace = {
// Sentry expects frames oldest to newest
frames: frames.reverse()
};
}
// Make sure that fingerprint is always wrapped in an array
if (data.fingerprint) {
data.fingerprint = isArray(data.fingerprint)
? data.fingerprint
: [data.fingerprint];
}
// Fire away!
this._send(data);
return this;
},
captureBreadcrumb: function(obj) {
var crumb = objectMerge(
{
timestamp: now() / 1000
},
obj
);
if (isFunction(this._globalOptions.breadcrumbCallback)) {
var result = this._globalOptions.breadcrumbCallback(crumb);
if (isObject(result) && !isEmptyObject(result)) {
crumb = result;
} else if (result === false) {
return this;
}
}
this._breadcrumbs.push(crumb);
if (this._breadcrumbs.length > this._globalOptions.maxBreadcrumbs) {
this._breadcrumbs.shift();
}
return this;
},
addPlugin: function(plugin /*arg1, arg2, ... argN*/) {
var pluginArgs = [].slice.call(arguments, 1);
this._plugins.push([plugin, pluginArgs]);
if (this._isRavenInstalled) {
this._drainPlugins();
}
return this;
},
/*
* Set/clear a user to be sent along with the payload.
*
* @param {object} user An object representing user data [optional]
* @return {Raven}
*/
setUserContext: function(user) {
// Intentionally do not merge here since that's an unexpected behavior.
this._globalContext.user = user;
return this;
},
/*
* Merge extra attributes to be sent along with the payload.
*
* @param {object} extra An object representing extra data [optional]
* @return {Raven}
*/
setExtraContext: function(extra) {
this._mergeContext('extra', extra);
return this;
},
/*
* Merge tags to be sent along with the payload.
*
* @param {object} tags An object representing tags [optional]
* @return {Raven}
*/
setTagsContext: function(tags) {
this._mergeContext('tags', tags);
return this;
},
/*
* Clear all of the context.
*
* @return {Raven}
*/
clearContext: function() {
this._globalContext = {};
return this;
},
/*
* Get a copy of the current context. This cannot be mutated.
*
* @return {object} copy of context
*/
getContext: function() {
// lol javascript
return JSON.parse(stringify(this._globalContext));
},
/*
* Set environment of application
*
* @param {string} environment Typically something like 'production'.
* @return {Raven}
*/
setEnvironment: function(environment) {
this._globalOptions.environment = environment;
return this;
},
/*
* Set release version of application
*
* @param {string} release Typically something like a git SHA to identify version
* @return {Raven}
*/
setRelease: function(release) {
this._globalOptions.release = release;
return this;
},
/*
* Set the dataCallback option
*
* @param {function} callback The callback to run which allows the
* data blob to be mutated before sending
* @return {Raven}
*/
setDataCallback: function(callback) {
var original = this._globalOptions.dataCallback;
this._globalOptions.dataCallback = keepOriginalCallback(original, callback);
return this;
},
/*
* Set the breadcrumbCallback option
*
* @param {function} callback The callback to run which allows filtering
* or mutating breadcrumbs
* @return {Raven}
*/
setBreadcrumbCallback: function(callback) {
var original = this._globalOptions.breadcrumbCallback;
this._globalOptions.breadcrumbCallback = keepOriginalCallback(original, callback);
return this;
},
/*
* Set the shouldSendCallback option
*
* @param {function} callback The callback to run which allows
* introspecting the blob before sending
* @return {Raven}
*/
setShouldSendCallback: function(callback) {
var original = this._globalOptions.shouldSendCallback;
this._globalOptions.shouldSendCallback = keepOriginalCallback(original, callback);
return this;
},
/**
* Override the default HTTP transport mechanism that transmits data
* to the Sentry server.
*
* @param {function} transport Function invoked instead of the default
* `makeRequest` handler.
*
* @return {Raven}
*/
setTransport: function(transport) {
this._globalOptions.transport = transport;
return this;
},
/*
* Get the latest raw exception that was captured by Raven.
*
* @return {error}
*/
lastException: function() {
return this._lastCapturedException;
},
/*
* Get the last event id
*
* @return {string}
*/
lastEventId: function() {
return this._lastEventId;
},
/*
* Determine if Raven is setup and ready to go.
*
* @return {boolean}
*/
isSetup: function() {
if (!this._hasJSON) return false; // needs JSON support
if (!this._globalServer) {
if (!this.ravenNotConfiguredError) {
this.ravenNotConfiguredError = true;
this._logDebug('error', 'Error: Raven has not been configured.');
}
return false;
}
return true;
},
afterLoad: function() {
// TODO: remove window dependence?
// Attempt to initialize Raven on load
var RavenConfig = _window.RavenConfig;
if (RavenConfig) {
this.config(RavenConfig.dsn, RavenConfig.config).install();
}
},
showReportDialog: function(options) {
if (
!_document // doesn't work without a document (React native)
)
return;
options = objectMerge(
{
eventId: this.lastEventId(),
dsn: this._dsn,
user: this._globalContext.user || {}
},
options
);
if (!options.eventId) {
throw new RavenConfigError('Missing eventId');
}
if (!options.dsn) {
throw new RavenConfigError('Missing DSN');
}
var encode = encodeURIComponent;
var encodedOptions = [];
for (var key in options) {
if (key === 'user') {
var user = options.user;
if (user.name) encodedOptions.push('name=' + encode(user.name));
if (user.email) encodedOptions.push('email=' + encode(user.email));
} else {
encodedOptions.push(encode(key) + '=' + encode(options[key]));
}
}
var globalServer = this._getGlobalServer(this._parseDSN(options.dsn));
var script = _document.createElement('script');
script.async = true;
script.src = globalServer + '/api/embed/error-page/?' + encodedOptions.join('&');
(_document.head || _document.body).appendChild(script);
},
/**** Private functions ****/
_ignoreNextOnError: function() {
var self = this;
this._ignoreOnError += 1;
setTimeout(function() {
// onerror should trigger before setTimeout
self._ignoreOnError -= 1;
});
},
_triggerEvent: function(eventType, options) {
// NOTE: `event` is a native browser thing, so let's avoid conflicting wiht it
var evt, key;
if (!this._hasDocument) return;
options = options || {};
eventType = 'raven' + eventType.substr(0, 1).toUpperCase() + eventType.substr(1);
if (_document.createEvent) {
evt = _document.createEvent('HTMLEvents');
evt.initEvent(eventType, true, true);
} else {
evt = _document.createEventObject();
evt.eventType = eventType;
}
for (key in options)
if (hasKey(options, key)) {
evt[key] = options[key];
}
if (_document.createEvent) {
// IE9 if standards
_document.dispatchEvent(evt);
} else {
// IE8 regardless of Quirks or Standards
// IE9 if quirks
try {
_document.fireEvent('on' + evt.eventType.toLowerCase(), evt);
} catch (e) {
// Do nothing
}
}
},
/**
* Wraps addEventListener to capture UI breadcrumbs
* @param evtName the event name (e.g. "click")
* @returns {Function}
* @private
*/
_breadcrumbEventHandler: function(evtName) {
var self = this;
return function(evt) {
// reset keypress timeout; e.g. triggering a 'click' after
// a 'keypress' will reset the keypress debounce so that a new
// set of keypresses can be recorded
self._keypressTimeout = null;
// It's possible this handler might trigger multiple times for the same
// event (e.g. event propagation through node ancestors). Ignore if we've
// already captured the event.
if (self._lastCapturedEvent === evt) return;
self._lastCapturedEvent = evt;
// try/catch both:
// - accessing evt.target (see getsentry/raven-js#838, #768)
// - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
// can throw an exception in some circumstances.
var target;
try {
target = htmlTreeAsString(evt.target);
} catch (e) {
target = '<unknown>';
}
self.captureBreadcrumb({
category: 'ui.' + evtName, // e.g. ui.click, ui.input
message: target
});
};
},
/**
* Wraps addEventListener to capture keypress UI events
* @returns {Function}
* @private
*/
_keypressEventHandler: function() {
var self = this,
debounceDuration = 1000; // milliseconds
// TODO: if somehow user switches keypress target before
// debounce timeout is triggered, we will only capture
// a single breadcrumb from the FIRST target (acceptable?)
return function(evt) {
var target;
try {
target = evt.target;
} catch (e) {
// just accessing event properties can throw an exception in some rare circumstances
// see: https://github.com/getsentry/raven-js/issues/838
return;
}
var tagName = target && target.tagName;
// only consider keypress events on actual input elements
// this will disregard keypresses targeting body (e.g. tabbing
// through elements, hotkeys, etc)
if (
!tagName ||
(tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)
)
return;
// record first keypress in a series, but ignore subsequent
// keypresses until debounce clears
var timeout = self._keypressTimeout;
if (!timeout) {
self._breadcrumbEventHandler('input')(evt);
}
clearTimeout(timeout);
self._keypressTimeout = setTimeout(function() {
self._keypressTimeout = null;
}, debounceDuration);
};
},
/**
* Captures a breadcrumb of type "navigation", normalizing input URLs
* @param to the originating URL
* @param from the target URL
* @private
*/
_captureUrlChange: function(from, to) {
var parsedLoc = parseUrl(this._location.href);
var parsedTo = parseUrl(to);
var parsedFrom = parseUrl(from);
// because onpopstate only tells you the "new" (to) value of location.href, and
// not the previous (from) value, we need to track the value of the current URL
// state ourselves
this._lastHref = to;
// Use only the path component of the URL if the URL matches the current
// document (almost all the time when using pushState)
if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host)
to = parsedTo.relative;
if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host)
from = parsedFrom.relative;
this.captureBreadcrumb({
category: 'navigation',
data: {
to: to,
from: from
}
});
},
_patchFunctionToString: function() {
var self = this;
self._originalFunctionToString = Function.prototype.toString;
// eslint-disable-next-line no-extend-native
Function.prototype.toString = function() {
if (typeof this === 'function' && this.__raven__) {
return self._originalFunctionToString.apply(this.__orig__, arguments);
}
return self._originalFunctionToString.apply(this, arguments);
};
},
_unpatchFunctionToString: function() {
if (this._originalFunctionToString) {
// eslint-disable-next-line no-extend-native
Function.prototype.toString = this._originalFunctionToString;
}
},
/**
* Wrap timer functions and event targets to catch errors and provide
* better metadata.
*/
_instrumentTryCatch: function() {
var self = this;
var wrappedBuiltIns = self._wrappedBuiltIns;
function wrapTimeFn(orig) {
return function(fn, t) {
// preserve arity
// Make a copy of the arguments to prevent deoptimization
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var originalCallback = args[0];
if (isFunction(originalCallback)) {
args[0] = self.wrap(
{
mechanism: {
type: 'instrument',
data: {function: orig.name || '<anonymous>'}
}
},
originalCallback
);
}
// IE < 9 doesn't support .call/.apply on setInterval/setTimeout, but it
// also supports only two arguments and doesn't care what this is, so we
// can just call the original function directly.
if (orig.apply) {
return orig.apply(this, args);
} else {
return orig(args[0], args[1]);
}
};
}
var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
function wrapEventTarget(global) {
var proto = _window[global] && _window[global].prototype;
if (proto && proto.hasOwnProperty && proto.hasOwnProperty('addEventListener')) {
fill(
proto,
'addEventListener',
function(orig) {
return function(evtName, fn, capture, secure) {
// preserve arity
try {
if (fn && fn.handleEvent) {
fn.handleEvent = self.wrap(
{
mechanism: {
type: 'instrument',
data: {
target: global,
function: 'handleEvent',
handler: (fn && fn.name) || '<anonymous>'
}
}
},
fn.handleEvent
);
}
} catch (err) {
// can sometimes get 'Permission denied to access property "handle Event'
}
// More breadcrumb DOM capture ... done here and not in `_instrumentBreadcrumbs`
// so that we don't have more than one wrapper function
var before, clickHandler, keypressHandler;
if (
autoBreadcrumbs &&
autoBreadcrumbs.dom &&
(global === 'EventTarget' || global === 'Node')
) {
// NOTE: generating multiple handlers per addEventListener invocation, should
// revisit and verify we can just use one (almost certainly)
clickHandler = self._breadcrumbEventHandler('click');
keypressHandler = self._keypressEventHandler();
before = function(evt) {
// need to intercept every DOM event in `before` argument, in case that
// same wrapped method is re-used for different events (e.g. mousemove THEN click)
// see #724
if (!evt) return;
var eventType;
try {
eventType = evt.type;
} catch (e) {
// just accessing event properties can throw an exception in some rare circumstances
// see: https://github.com/getsentry/raven-js/issues/838
return;
}
if (eventType === 'click') return clickHandler(evt);
else if (eventType === 'keypress') return keypressHandler(evt);
};
}
return orig.call(
this,
evtName,
self.wrap(
{
mechanism: {
type: 'instrument',
data: {
target: global,
function: 'addEventListener',
handler: (fn && fn.name) || '<anonymous>'
}
}
},
fn,
before
),
capture,
secure
);
};
},
wrappedBuiltIns
);
fill(
proto,
'removeEventListener',
function(orig) {
return function(evt, fn, capture, secure) {
try {
fn = fn && (fn.__raven_wrapper__ ? fn.__raven_wrapper__ : fn);
} catch (e) {
// ignore, accessing __raven_wrapper__ will throw in some Selenium environments
}
return orig.call(this, evt, fn, capture, secure);
};
},
wrappedBuiltIns
);
}
}
fill(_window, 'setTimeout', wrapTimeFn, wrappedBuiltIns);
fill(_window, 'setInterval', wrapTimeFn, wrappedBuiltIns);
if (_window.requestAnimationFrame) {
fill(
_window,
'requestAnimationFrame',
function(orig) {
return function(cb) {
return orig(
self.wrap(
{
mechanism: {
type: 'instrument',
data: {
function: 'requestAnimationFrame',
handler: (orig && orig.name) || '<anonymous>'
}
}
},
cb
)
);
};
},
wrappedBuiltIns
);
}
// event targets borrowed from bugsnag-js:
// https://github.com/bugsnag/bugsnag-js/blob/master/src/bugsnag.js#L666
var eventTargets = [
'EventTarget',
'Window',
'Node',
'ApplicationCache',
'AudioTrackList',
'ChannelMergerNode',
'CryptoOperation',
'EventSource',
'FileReader',
'HTMLUnknownElement',
'IDBDatabase',
'IDBRequest',
'IDBTransaction',
'KeyOperation',
'MediaController',
'MessagePort',
'ModalWindow',
'Notification',
'SVGElementInstance',
'Screen',
'TextTrack',
'TextTrackCue',
'TextTrackList',
'WebSocket',
'WebSocketWorker',
'Worker',
'XMLHttpRequest',
'XMLHttpRequestEventTarget',
'XMLHttpRequestUpload'
];
for (var i = 0; i < eventTargets.length; i++) {
wrapEventTarget(eventTargets[i]);
}
},
/**
* Instrument browser built-ins w/ breadcrumb capturing
* - XMLHttpRequests
* - DOM interactions (click/typing)
* - window.location changes
* - console
*
* Can be disabled or individually configured via the `autoBreadcrumbs` config option
*/
_instrumentBreadcrumbs: function() {
var self = this;
var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
var wrappedBuiltIns = self._wrappedBuiltIns;
function wrapProp(prop, xhr) {
if (prop in xhr && isFunction(xhr[prop])) {
fill(xhr, prop, function(orig) {
return self.wrap(
{
mechanism: {
type: 'instrument',
data: {function: prop, handler: (orig && orig.name) || '<anonymous>'}
}
},
orig
);
}); // intentionally don't track filled methods on XHR instances
}
}
if (autoBreadcrumbs.xhr && 'XMLHttpRequest' in _window) {
var xhrproto = _window.XMLHttpRequest && _window.XMLHttpRequest.prototype;
fill(
xhrproto,
'open',
function(origOpen) {
return function(method, url) {
// preserve arity
// if Sentry key appears in URL, don't capture
if (isString(url) && url.indexOf(self._globalKey) === -1) {
this.__raven_xhr = {
method: method,
url: url,
status_code: null
};
}
return origOpen.apply(this, arguments);
};
},
wrappedBuiltIns
);
fill(
xhrproto,
'send',
function(origSend) {
return function() {
// preserve arity
var xhr = this;
function onreadystatechangeHandler() {
if (xhr.__raven_xhr && xhr.readyState === 4) {
try {
// touching statusCode in some platforms throws
// an exception
xhr.__raven_xhr.status_code = xhr.status;
} catch (e) {
/* do nothing */
}
self.captureBreadcrumb({
type: 'http',
category: 'xhr',
data: xhr.__raven_xhr
});
}
}
var props = ['onload', 'onerror', 'onprogress'];
for (var j = 0; j < props.length; j++) {
wrapProp(props[j], xhr);
}
if ('onreadystatechange' in xhr && isFunction(xhr.onreadystatechange)) {
fill(
xhr,
'onreadystatechange',
function(orig) {
return self.wrap(
{
mechanism: {
type: 'instrument',
data: {
function: 'onreadystatechange',
handler: (orig && orig.name) || '<anonymous>'
}
}
},
orig,
onreadystatechangeHandler
);
} /* intentionally don't track this instrumentation */
);
} else {
// if onreadystatechange wasn't actually set by the page on this xhr, we
// are free to set our own and capture the breadcrumb
xhr.onreadystatechange = onreadystatechangeHandler;
}
return origSend.apply(this, arguments);
};
},
wrappedBuiltIns
);
}
if (autoBreadcrumbs.xhr && supportsFetch()) {
fill(
_window,
'fetch',
function(origFetch) {
return function() {
// preserve arity
// Make a copy of the arguments to prevent deoptimization
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var fetchInput = args[0];
var method = 'GET';
var url;
if (typeof fetchInput === 'string') {
url = fetchInput;
} else if ('Request' in _window && fetchInput instanceof _window.Request) {
url = fetchInput.url;
if (fetchInput.method) {
method = fetchInput.method;
}
} else {
url = '' + fetchInput;
}
// if Sentry key appears in URL, don't capture, as it's our own request
if (url.indexOf(self._globalKey) !== -1) {
return origFetch.apply(this, args);
}
if (args[1] && args[1].method) {
method = args[1].method;
}
var fetchData = {
method: method,
url: url,
status_code: null
};
return origFetch
.apply(this, args)
.then(function(response) {
fetchData.status_code = response.status;
self.captureBreadcrumb({
type: 'http',
category: 'fetch',
data: fetchData
});
return response;
})
['catch'](function(err) {
// if there is an error performing the request
self.captureBreadcrumb({
type: 'http',
category: 'fetch',
data: fetchData,
level: 'error'
});
throw err;
});
};
},
wrappedBuiltIns
);
}
// Capture breadcrumbs from any click that is unhandled / bubbled up all the way
// to the document. Do this before we instrument addEventListener.
if (autoBreadcrumbs.dom && this._hasDocument) {
if (_document.addEventListener) {
_document.addEventListener('click', self._breadcrumbEventHandler('click'), false);
_document.addEventListener('keypress', self._keypressEventHandler(), false);
} else if (_document.attachEvent) {
// IE8 Compatibility
_document.attachEvent('onclick', self._breadcrumbEventHandler('click'));
_document.attachEvent('onkeypress', self._keypressEventHandler());
}
}
// record navigation (URL) changes
// NOTE: in Chrome App environment, touching history.pushState, *even inside
// a try/catch block*, will cause Chrome to output an error to console.error
// borrowed from: https://github.com/angular/angular.js/pull/13945/files
var chrome = _window.chrome;
var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;
var hasPushAndReplaceState =
!isChromePackagedApp &&
_window.history &&
_window.history.pushState &&
_window.history.replaceState;
if (autoBreadcrumbs.location && hasPushAndReplaceState) {
// TODO: remove onpopstate handler on uninstall()
var oldOnPopState = _window.onpopstate;
_window.onpopstate = function() {
var currentHref = self._location.href;
self._captureUrlChange(self._lastHref, currentHref);
if (oldOnPopState) {
return oldOnPopState.apply(this, arguments);
}
};
var historyReplacementFunction = function(origHistFunction) {
// note history.pushState.length is 0; intentionally not declaring
// params to preserve 0 arity
return function(/* state, title, url */) {
var url = arguments.length > 2 ? arguments[2] : undefined;
// url argument is optional
if (url) {
// coerce to string (this is what pushState does)
self._captureUrlChange(self._lastHref, url + '');
}
return origHistFunction.apply(this, arguments);
};
};
fill(_window.history, 'pushState', historyReplacementFunction, wrappedBuiltIns);
fill(_window.history, 'replaceState', historyReplacementFunction, wrappedBuiltIns);
}
if (autoBreadcrumbs.console && 'console' in _window && console.log) {
// console
var consoleMethodCallback = function(msg, data) {
self.captureBreadcrumb({
message: msg,
level: data.level,
category: 'console'
});
};
each(['debug', 'info', 'warn', 'error', 'log'], function(_, level) {
wrapConsoleMethod(console, level, consoleMethodCallback);
});
}
},
_restoreBuiltIns: function() {
// restore any wrapped builtins
var builtin;
while (this._wrappedBuiltIns.length) {
builtin = this._wrappedBuiltIns.shift();
var obj = builtin[0],
name = builtin[1],
orig = builtin[2];
obj[name] = orig;
}
},
_restoreConsole: function() {
// eslint-disable-next-line guard-for-in
for (var method in this._originalConsoleMethods) {
this._originalConsole[method] = this._originalConsoleMethods[method];
}
},
_drainPlugins: function() {
var self = this;
// FIX ME TODO
each(this._plugins, function(_, plugin) {
var installer = plugin[0];
var args = plugin[1];
installer.apply(self, [self].concat(args));
});
},
_parseDSN: function(str) {
var m = dsnPattern.exec(str),
dsn = {},
i = 7;
try {
while (i--) dsn[dsnKeys[i]] = m[i] || '';
} catch (e) {
throw new RavenConfigError('Invalid DSN: ' + str);
}
if (dsn.pass && !this._globalOptions.allowSecretKey) {
throw new RavenConfigError(
'Do not specify your secret key in the DSN. See: http://bit.ly/raven-secret-key'
);
}
return dsn;
},
_getGlobalServer: function(uri) {
// assemble the endpoint from the uri pieces
var globalServer = '//' + uri.host + (uri.port ? ':' + uri.port : '');
if (uri.protocol) {
globalServer = uri.protocol + ':' + globalServer;
}
return globalServer;
},
_handleOnErrorStackInfo: function(stackInfo, options) {
options = options || {};
options.mechanism = options.mechanism || {
type: 'onerror',
handled: false
};
// if we are intentionally ignoring errors via onerror, bail out
if (!this._ignoreOnError) {
this._handleStackInfo(stackInfo, options);
}
},
_handleStackInfo: function(stackInfo, options) {
var frames = this._prepareFrames(stackInfo, options);
this._triggerEvent('handle', {
stackInfo: stackInfo,
options: options
});
this._processException(
stackInfo.name,
stackInfo.message,
stackInfo.url,
stackInfo.lineno,
frames,
options
);
},
_prepareFrames: function(stackInfo, options) {
var self = this;
var frames = [];
if (stackInfo.stack && stackInfo.stack.length) {
each(stackInfo.stack, function(i, stack) {
var frame = self._normalizeFrame(stack, stackInfo.url);
if (frame) {
frames.push(frame);
}
});
// e.g. frames captured via captureMessage throw
if (options && options.trimHeadFrames) {
for (var j = 0; j < options.trimHeadFrames && j < frames.length; j++) {
frames[j].in_app = false;
}
}
}
frames = frames.slice(0, this._globalOptions.stackTraceLimit);
return frames;
},
_normalizeFrame: function(frame, stackInfoUrl) {
// normalize the frames data
var normalized = {
filename: frame.url,
lineno: frame.line,
colno: frame.column,
function: frame.func || '?'
};
// Case when we don't have any information about the error
// E.g. throwing a string or raw object, instead of an `Error` in Firefox
// Generating synthetic error doesn't add any value here
//
// We should probably somehow let a user know that they should fix their code
if (!frame.url) {
normalized.filename = stackInfoUrl; // fallback to whole stacks url from onerror handler
}
normalized.in_app = !// determine if an exception came from outside of our app
// first we check the global includePaths list.
(
(!!this._globalOptions.includePaths.test &&
!this._globalOptions.includePaths.test(normalized.filename)) ||
// Now we check for fun, if the function name is Raven or TraceKit
/(Raven|TraceKit)\./.test(normalized['function']) ||
// finally, we do a last ditch effort and check for raven.min.js
/raven\.(min\.)?js$/.test(normalized.filename)
);
return normalized;
},
_processException: function(type, message, fileurl, lineno, frames, options) {
var prefixedMessage = (type ? type + ': ' : '') + (message || '');
if (
!!this._globalOptions.ignoreErrors.test &&
(this._globalOptions.ignoreErrors.test(message) ||
this._globalOptions.ignoreErrors.test(prefixedMessage))
) {
return;
}
var stacktrace;
if (frames && frames.length) {
fileurl = frames[0].filename || fileurl;
// Sentry expects frames oldest to newest
// and JS sends them as newest to oldest
frames.reverse();
stacktrace = {frames: frames};
} else if (fileurl) {
stacktrace = {
frames: [
{
filename: fileurl,
lineno: lineno,
in_app: true
}
]
};
}
if (
!!this._globalOptions.ignoreUrls.test &&
this._globalOptions.ignoreUrls.test(fileurl)
) {
return;
}
if (
!!this._globalOptions.whitelistUrls.test &&
!this._globalOptions.whitelistUrls.test(fileurl)
) {
return;
}
var data = objectMerge(
{
// sentry.interfaces.Exception
exception: {
values: [
{
type: type,
value: message,
stacktrace: stacktrace
}
]
},
transaction: fileurl
},
options
);
var ex = data.exception.values[0];
if (ex.type == null && ex.value === '') {
ex.value = 'Unrecoverable error caught';
}
// Move mechanism from options to exception interface
// We do this, as requiring user to pass `{exception:{mechanism:{ ... }}}` would be
// too much
if (!data.exception.mechanism && data.mechanism) {
data.exception.mechanism = data.mechanism;
delete data.mechanism;
}
data.exception.mechanism = objectMerge(
{
type: 'generic',
handled: true
},
data.exception.mechanism || {}
);
// Fire away!
this._send(data);
},
_trimPacket: function(data) {
// For now, we only want to truncate the two different messages
// but this could/should be expanded to just trim everything
var max = this._globalOptions.maxMessageLength;
if (data.message) {
data.message = truncate(data.message, max);
}
if (data.exception) {
var exception = data.exception.values[0];
exception.value = truncate(exception.value, max);
}
var request = data.request;
if (request) {
if (request.url) {
request.url = truncate(request.url, this._globalOptions.maxUrlLength);
}
if (request.Referer) {
request.Referer = truncate(request.Referer, this._globalOptions.maxUrlLength);
}
}
if (data.breadcrumbs && data.breadcrumbs.values)
this._trimBreadcrumbs(data.breadcrumbs);
return data;
},
/**
* Truncate breadcrumb values (right now just URLs)
*/
_trimBreadcrumbs: function(breadcrumbs) {
// known breadcrumb properties with urls
// TODO: also consider arbitrary prop values that start with (https?)?://
var urlProps = ['to', 'from', 'url'],
urlProp,
crumb,
data;
for (var i = 0; i < breadcrumbs.values.length; ++i) {
crumb = breadcrumbs.values[i];
if (
!crumb.hasOwnProperty('data') ||
!isObject(crumb.data) ||
objectFrozen(crumb.data)
)
continue;
data = objectMerge({}, crumb.data);
for (var j = 0; j < urlProps.length; ++j) {
urlProp = urlProps[j];
if (data.hasOwnProperty(urlProp) && data[urlProp]) {
data[urlProp] = truncate(data[urlProp], this._globalOptions.maxUrlLength);
}
}
breadcrumbs.values[i].data = data;
}
},
_getHttpData: function() {
if (!this._hasNavigator && !this._hasDocument) return;
var httpData = {};
if (this._hasNavigator && _navigator.userAgent) {
httpData.headers = {
'User-Agent': _navigator.userAgent
};
}
// Check in `window` instead of `document`, as we may be in ServiceWorker environment
if (_window.location && _window.location.href) {
httpData.url = _window.location.href;
}
if (this._hasDocument && _document.referrer) {
if (!httpData.headers) httpData.headers = {};
httpData.headers.Referer = _document.referrer;
}
return httpData;
},
_resetBackoff: function() {
this._backoffDuration = 0;
this._backoffStart = null;
},
_shouldBackoff: function() {
return this._backoffDuration && now() - this._backoffStart < this._backoffDuration;
},
/**
* Returns true if the in-process data payload matches the signature
* of the previously-sent data
*
* NOTE: This has to be done at this level because TraceKit can generate
* data from window.onerror WITHOUT an exception object (IE8, IE9,
* other old browsers). This can take the form of an "exception"
* data object with a single frame (derived from the onerror args).
*/
_isRepeatData: function(current) {
var last = this._lastData;
if (
!last ||
current.message !== last.message || // defined for captureMessage
current.transaction !== last.transaction // defined for captureException/onerror
)
return false;
// Stacktrace interface (i.e. from captureMessage)
if (current.stacktrace || last.stacktrace) {
return isSameStacktrace(current.stacktrace, last.stacktrace);
} else if (current.exception || last.exception) {
// Exception interface (i.e. from captureException/onerror)
return isSameException(current.exception, last.exception);
}
return true;
},
_setBackoffState: function(request) {
// If we are already in a backoff state, don't change anything
if (this._shouldBackoff()) {
return;
}
var status = request.status;
// 400 - project_id doesn't exist or some other fatal
// 401 - invalid/revoked dsn
// 429 - too many requests
if (!(status === 400 || status === 401 || status === 429)) return;
var retry;
try {
// If Retry-After is not in Access-Control-Expose-Headers, most
// browsers will throw an exception trying to access it
if (supportsFetch()) {
retry = request.headers.get('Retry-After');
} else {
retry = request.getResponseHeader('Retry-After');
}
// Retry-After is returned in seconds
retry = parseInt(retry, 10) * 1000;
} catch (e) {
/* eslint no-empty:0 */
}
this._backoffDuration = retry
? // If Sentry server returned a Retry-After value, use it
retry
: // Otherwise, double the last backoff duration (starts at 1 sec)
this._backoffDuration * 2 || 1000;
this._backoffStart = now();
},
_send: function(data) {
var globalOptions = this._globalOptions;
var baseData = {
project: this._globalProject,
logger: globalOptions.logger,
platform: 'javascript'
},
httpData = this._getHttpData();
if (httpData) {
baseData.request = httpData;
}
// HACK: delete `trimHeadFrames` to prevent from appearing in outbound payload
if (data.trimHeadFrames) delete data.trimHeadFrames;
data = objectMerge(baseData, data);
// Merge in the tags and extra separately since objectMerge doesn't handle a deep merge
data.tags = objectMerge(objectMerge({}, this._globalContext.tags), data.tags);
data.extra = objectMerge(objectMerge({}, this._globalContext.extra), data.extra);
// Send along our own collected metadata with extra
data.extra['session:duration'] = now() - this._startTime;
if (this._breadcrumbs && this._breadcrumbs.length > 0) {
// intentionally make shallow copy so that additions
// to breadcrumbs aren't accidentally sent in this request
data.breadcrumbs = {
values: [].slice.call(this._breadcrumbs, 0)
};
}
if (this._globalContext.user) {
// sentry.interfaces.User
data.user = this._globalContext.user;
}
// Include the environment if it's defined in globalOptions
if (globalOptions.environment) data.environment = globalOptions.environment;
// Include the release if it's defined in globalOptions
if (globalOptions.release) data.release = globalOptions.release;
// Include server_name if it's defined in globalOptions
if (globalOptions.serverName) data.server_name = globalOptions.serverName;
data = this._sanitizeData(data);
// Cleanup empty properties before sending them to the server
Object.keys(data).forEach(function(key) {
if (data[key] == null || data[key] === '' || isEmptyObject(data[key])) {
delete data[key];
}
});
if (isFunction(globalOptions.dataCallback)) {
data = globalOptions.dataCallback(data) || data;
}
// Why??????????
if (!data || isEmptyObject(data)) {
return;
}
// Check if the request should be filtered or not
if (
isFunction(globalOptions.shouldSendCallback) &&
!globalOptions.shouldSendCallback(data)
) {
return;
}
// Backoff state: Sentry server previously responded w/ an error (e.g. 429 - too many requests),
// so drop requests until "cool-off" period has elapsed.
if (this._shouldBackoff()) {
this._logDebug('warn', 'Raven dropped error due to backoff: ', data);
return;
}
if (typeof globalOptions.sampleRate === 'number') {
if (Math.random() < globalOptions.sampleRate) {
this._sendProcessedPayload(data);
}
} else {
this._sendProcessedPayload(data);
}
},
_sanitizeData: function(data) {
return sanitize(data, this._globalOptions.sanitizeKeys);
},
_getUuid: function() {
return uuid4();
},
_sendProcessedPayload: function(data, callback) {
var self = this;
var globalOptions = this._globalOptions;
if (!this.isSetup()) return;
// Try and clean up the packet before sending by truncating long values
data = this._trimPacket(data);
// ideally duplicate error testing should occur *before* dataCallback/shouldSendCallback,
// but this would require copying an un-truncated copy of the data packet, which can be
// arbitrarily deep (extra_data) -- could be worthwhile? will revisit
if (!this._globalOptions.allowDuplicates && this._isRepeatData(data)) {
this._logDebug('warn', 'Raven dropped repeat event: ', data);
return;
}
// Send along an event_id if not explicitly passed.
// This event_id can be used to reference the error within Sentry itself.
// Set lastEventId after we know the error should actually be sent
this._lastEventId = data.event_id || (data.event_id = this._getUuid());
// Store outbound payload after trim
this._lastData = data;
this._logDebug('debug', 'Raven about to send:', data);
var auth = {
sentry_version: '7',
sentry_client: 'raven-js/' + this.VERSION,
sentry_key: this._globalKey
};
if (this._globalSecret) {
auth.sentry_secret = this._globalSecret;
}
var exception = data.exception && data.exception.values[0];
// only capture 'sentry' breadcrumb is autoBreadcrumbs is truthy
if (
this._globalOptions.autoBreadcrumbs &&
this._globalOptions.autoBreadcrumbs.sentry
) {
this.captureBreadcrumb({
category: 'sentry',
message: exception
? (exception.type ? exception.type + ': ' : '') + exception.value
: data.message,
event_id: data.event_id,
level: data.level || 'error' // presume error unless specified
});
}
var url = this._globalEndpoint;
(globalOptions.transport || this._makeRequest).call(this, {
url: url,
auth: auth,
data: data,
options: globalOptions,
onSuccess: function success() {
self._resetBackoff();
self._triggerEvent('success', {
data: data,
src: url
});
callback && callback();
},
onError: function failure(error) {
self._logDebug('error', 'Raven transport failed to send: ', error);
if (error.request) {
self._setBackoffState(error.request);
}
self._triggerEvent('failure', {
data: data,
src: url
});
error = error || new Error('Raven send failed (no additional details provided)');
callback && callback(error);
}
});
},
_makeRequest: function(opts) {
// Auth is intentionally sent as part of query string (NOT as custom HTTP header) to avoid preflight CORS requests
var url = opts.url + '?' + urlencode(opts.auth);
var evaluatedHeaders = null;
var evaluatedFetchParameters = {};
if (opts.options.headers) {
evaluatedHeaders = this._evaluateHash(opts.options.headers);
}
if (opts.options.fetchParameters) {
evaluatedFetchParameters = this._evaluateHash(opts.options.fetchParameters);
}
if (supportsFetch()) {
evaluatedFetchParameters.body = stringify(opts.data);
var defaultFetchOptions = objectMerge({}, this._fetchDefaults);
var fetchOptions = objectMerge(defaultFetchOptions, evaluatedFetchParameters);
if (evaluatedHeaders) {
fetchOptions.headers = evaluatedHeaders;
}
return _window
.fetch(url, fetchOptions)
.then(function(response) {
if (response.ok) {
opts.onSuccess && opts.onSuccess();
} else {
var error = new Error('Sentry error code: ' + response.status);
// It's called request only to keep compatibility with XHR interface
// and not add more redundant checks in setBackoffState method
error.request = response;
opts.onError && opts.onError(error);
}
})
['catch'](function() {
opts.onError &&
opts.onError(new Error('Sentry error code: network unavailable'));
});
}
var request = _window.XMLHttpRequest && new _window.XMLHttpRequest();
if (!request) return;
// if browser doesn't support CORS (e.g. IE7), we are out of luck
var hasCORS = 'withCredentials' in request || typeof XDomainRequest !== 'undefined';
if (!hasCORS) return;
if ('withCredentials' in request) {
request.onreadystatechange = function() {
if (request.readyState !== 4) {
return;
} else if (request.status === 200) {
opts.onSuccess && opts.onSuccess();
} else if (opts.onError) {
var err = new Error('Sentry error code: ' + request.status);
err.request = request;
opts.onError(err);
}
};
} else {
request = new XDomainRequest();
// xdomainrequest cannot go http -> https (or vice versa),
// so always use protocol relative
url = url.replace(/^https?:/, '');
// onreadystatechange not supported by XDomainRequest
if (opts.onSuccess) {
request.onload = opts.onSuccess;
}
if (opts.onError) {
request.onerror = function() {
var err = new Error('Sentry error code: XDomainRequest');
err.request = request;
opts.onError(err);
};
}
}
request.open('POST', url);
if (evaluatedHeaders) {
each(evaluatedHeaders, function(key, value) {
request.setRequestHeader(key, value);
});
}
request.send(stringify(opts.data));
},
_evaluateHash: function(hash) {
var evaluated = {};
for (var key in hash) {
if (hash.hasOwnProperty(key)) {
var value = hash[key];
evaluated[key] = typeof value === 'function' ? value() : value;
}
}
return evaluated;
},
_logDebug: function(level) {
// We allow `Raven.debug` and `Raven.config(DSN, { debug: true })` to not make backward incompatible API change
if (
this._originalConsoleMethods[level] &&
(this.debug || this._globalOptions.debug)
) {
// In IE<10 console methods do not have their own 'apply' method
Function.prototype.apply.call(
this._originalConsoleMethods[level],
this._originalConsole,
[].slice.call(arguments, 1)
);
}
},
_mergeContext: function(key, context) {
if (isUndefined(context)) {
delete this._globalContext[key];
} else {
this._globalContext[key] = objectMerge(this._globalContext[key] || {}, context);
}
}
};
// Deprecations
Raven.prototype.setUser = Raven.prototype.setUserContext;
Raven.prototype.setReleaseContext = Raven.prototype.setRelease;
module.exports = Raven;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"10":10,"11":11,"4":4,"5":5,"8":8,"9":9}],7:[function(_dereq_,module,exports){
(function (global){
/**
* Enforces a single instance of the Raven client, and the
* main entry point for Raven. If you are a consumer of the
* Raven library, you SHOULD load this file (vs raven.js).
**/
var RavenConstructor = _dereq_(6);
// This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var _Raven = _window.Raven;
var Raven = new RavenConstructor();
/*
* Allow multiple versions of Raven to be installed.
* Strip Raven from the global context and returns the instance.
*
* @return {Raven}
*/
Raven.noConflict = function() {
_window.Raven = _Raven;
return Raven;
};
Raven.afterLoad();
module.exports = Raven;
/**
* DISCLAIMER:
*
* Expose `Client` constructor for cases where user want to track multiple "sub-applications" in one larger app.
* It's not meant to be used by a wide audience, so pleaaase make sure that you know what you're doing before using it.
* Accidentally calling `install` multiple times, may result in an unexpected behavior that's very hard to debug.
*
* It's called `Client' to be in-line with Raven Node implementation.
*
* HOWTO:
*
* import Raven from 'raven-js';
*
* const someAppReporter = new Raven.Client();
* const someOtherAppReporter = new Raven.Client();
*
* someAppReporter.config('__DSN__', {
* ...config goes here
* });
*
* someOtherAppReporter.config('__OTHER_DSN__', {
* ...config goes here
* });
*
* someAppReporter.captureMessage(...);
* someAppReporter.captureException(...);
* someAppReporter.captureBreadcrumb(...);
*
* someOtherAppReporter.captureMessage(...);
* someOtherAppReporter.captureException(...);
* someOtherAppReporter.captureBreadcrumb(...);
*
* It should "just work".
*/
module.exports.Client = RavenConstructor;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"6":6}],8:[function(_dereq_,module,exports){
(function (global){
var stringify = _dereq_(10);
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
? self
: {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch (Object.prototype.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return Object.prototype.toString.call(value) === '[object ErrorEvent]';
}
function isDOMError(value) {
return Object.prototype.toString.call(value) === '[object DOMError]';
}
function isDOMException(value) {
return Object.prototype.toString.call(value) === '[object DOMException]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsDOMError() {
try {
new DOMError(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsDOMException() {
try {
new DOMException(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
if (typeof max !== 'number') {
throw new Error('2nd argument to `truncate` function should be a number');
}
if (typeof str !== 'string' || max === 0) {
return str;
}
return str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if stacktrace is malformed
if (frames1 === undefined || frames2 === undefined) return false;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
if (obj == null) return;
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
// Default Node.js REPL depth
var MAX_SERIALIZE_EXCEPTION_DEPTH = 3;
// 50kB, as 100kB is max payload size, so half sounds reasonable
var MAX_SERIALIZE_EXCEPTION_SIZE = 50 * 1024;
var MAX_SERIALIZE_KEYS_LENGTH = 40;
function utf8Length(value) {
return ~-encodeURI(value).split(/%..|./).length;
}
function jsonSize(value) {
return utf8Length(JSON.stringify(value));
}
function serializeValue(value) {
if (typeof value === 'string') {
var maxLength = 40;
return truncate(value, maxLength);
} else if (
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'undefined'
) {
return value;
}
var type = Object.prototype.toString.call(value);
// Node.js REPL notation
if (type === '[object Object]') return '[Object]';
if (type === '[object Array]') return '[Array]';
if (type === '[object Function]')
return value.name ? '[Function: ' + value.name + ']' : '[Function]';
return value;
}
function serializeObject(value, depth) {
if (depth === 0) return serializeValue(value);
if (isPlainObject(value)) {
return Object.keys(value).reduce(function(acc, key) {
acc[key] = serializeObject(value[key], depth - 1);
return acc;
}, {});
} else if (Array.isArray(value)) {
return value.map(function(val) {
return serializeObject(val, depth - 1);
});
}
return serializeValue(value);
}
function serializeException(ex, depth, maxSize) {
if (!isPlainObject(ex)) return ex;
depth = typeof depth !== 'number' ? MAX_SERIALIZE_EXCEPTION_DEPTH : depth;
maxSize = typeof depth !== 'number' ? MAX_SERIALIZE_EXCEPTION_SIZE : maxSize;
var serialized = serializeObject(ex, depth);
if (jsonSize(stringify(serialized)) > maxSize) {
return serializeException(ex, depth - 1);
}
return serialized;
}
function serializeKeysForMessage(keys, maxLength) {
if (typeof keys === 'number' || typeof keys === 'string') return keys.toString();
if (!Array.isArray(keys)) return '';
keys = keys.filter(function(key) {
return typeof key === 'string';
});
if (keys.length === 0) return '[object has no keys]';
maxLength = typeof maxLength !== 'number' ? MAX_SERIALIZE_KEYS_LENGTH : maxLength;
if (keys[0].length >= maxLength) return keys[0];
for (var usedKeys = keys.length; usedKeys > 0; usedKeys--) {
var serialized = keys.slice(0, usedKeys).join(', ');
if (serialized.length > maxLength) continue;
if (usedKeys === keys.length) return serialized;
return serialized + '\u2026';
}
return '';
}
function sanitize(input, sanitizeKeys) {
if (!isArray(sanitizeKeys) || (isArray(sanitizeKeys) && sanitizeKeys.length === 0))
return input;
var sanitizeRegExp = joinRegExp(sanitizeKeys);
var sanitizeMask = '********';
var safeInput;
try {
safeInput = JSON.parse(stringify(input));
} catch (o_O) {
return input;
}
function sanitizeWorker(workerInput) {
if (isArray(workerInput)) {
return workerInput.map(function(val) {
return sanitizeWorker(val);
});
}
if (isPlainObject(workerInput)) {
return Object.keys(workerInput).reduce(function(acc, k) {
if (sanitizeRegExp.test(k)) {
acc[k] = sanitizeMask;
} else {
acc[k] = sanitizeWorker(workerInput[k]);
}
return acc;
}, {});
}
return workerInput;
}
return sanitizeWorker(safeInput);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isDOMError: isDOMError,
isDOMException: isDOMException,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsDOMError: supportsDOMError,
supportsDOMException: supportsDOMException,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin,
serializeException: serializeException,
serializeKeysForMessage: serializeKeysForMessage,
sanitize: sanitize
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"10":10}],9:[function(_dereq_,module,exports){
(function (global){
var utils = _dereq_(8);
/*
TraceKit - Cross brower stack traces
This was originally forked from github.com/occ/TraceKit, but has since been
largely re-written and is now maintained as part of raven-js. Tests for
this are in test/vendor.
MIT license
*/
var TraceKit = {
collectWindowErrors: true,
debug: false
};
// This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
// global reference to slice
var _slice = [].slice;
var UNKNOWN_FUNCTION = '?';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;
function getLocationHref() {
if (typeof document === 'undefined' || document.location == null) return '';
return document.location.href;
}
function getLocationOrigin() {
if (typeof document === 'undefined' || document.location == null) return '';
// Oh dear IE10...
if (!document.location.origin) {
return (
document.location.protocol +
'//' +
document.location.hostname +
(document.location.port ? ':' + document.location.port : '')
);
}
return document.location.origin;
}
/**
* TraceKit.report: cross-browser processing of unhandled exceptions
*
* Syntax:
* TraceKit.report.subscribe(function(stackInfo) { ... })
* TraceKit.report.unsubscribe(function(stackInfo) { ... })
* TraceKit.report(exception)
* try { ...code... } catch(ex) { TraceKit.report(ex); }
*
* Supports:
* - Firefox: full stack trace with line numbers, plus column number
* on top frame; column number is not guaranteed
* - Opera: full stack trace with line and column numbers
* - Chrome: full stack trace with line and column numbers
* - Safari: line and column number for the top frame only; some frames
* may be missing, and column number is not guaranteed
* - IE: line and column number for the top frame only; some frames
* may be missing, and column number is not guaranteed
*
* In theory, TraceKit should work on all of the following versions:
* - IE5.5+ (only 8.0 tested)
* - Firefox 0.9+ (only 3.5+ tested)
* - Opera 7+ (only 10.50 tested; versions 9 and earlier may require
* Exceptions Have Stacktrace to be enabled in opera:config)
* - Safari 3+ (only 4+ tested)
* - Chrome 1+ (only 5+ tested)
* - Konqueror 3.5+ (untested)
*
* Requires TraceKit.computeStackTrace.
*
* Tries to catch all unhandled exceptions and report them to the
* subscribed handlers. Please note that TraceKit.report will rethrow the
* exception. This is REQUIRED in order to get a useful stack trace in IE.
* If the exception does not reach the top of the browser, you will only
* get a stack trace from the point where TraceKit.report was called.
*
* Handlers receive a stackInfo object as described in the
* TraceKit.computeStackTrace docs.
*/
TraceKit.report = (function reportModuleWrapper() {
var handlers = [],
lastArgs = null,
lastException = null,
lastExceptionStack = null;
/**
* Add a crash handler.
* @param {Function} handler
*/
function subscribe(handler) {
installGlobalHandler();
handlers.push(handler);
}
/**
* Remove a crash handler.
* @param {Function} handler
*/
function unsubscribe(handler) {
for (var i = handlers.length - 1; i >= 0; --i) {
if (handlers[i] === handler) {
handlers.splice(i, 1);
}
}
}
/**
* Remove all crash handlers.
*/
function unsubscribeAll() {
uninstallGlobalHandler();
handlers = [];
}
/**
* Dispatch stack information to all handlers.
* @param {Object.<string, *>} stack
*/
function notifyHandlers(stack, isWindowError) {
var exception = null;
if (isWindowError && !TraceKit.collectWindowErrors) {
return;
}
for (var i in handlers) {
if (handlers.hasOwnProperty(i)) {
try {
handlers[i].apply(null, [stack].concat(_slice.call(arguments, 2)));
} catch (inner) {
exception = inner;
}
}
}
if (exception) {
throw exception;
}
}
var _oldOnerrorHandler, _onErrorHandlerInstalled;
/**
* Ensures all global unhandled exceptions are recorded.
* Supported by Gecko and IE.
* @param {string} msg Error message.
* @param {string} url URL of script that generated the exception.
* @param {(number|string)} lineNo The line number at which the error
* occurred.
* @param {?(number|string)} colNo The column number at which the error
* occurred.
* @param {?Error} ex The actual Error object.
*/
function traceKitWindowOnError(msg, url, lineNo, colNo, ex) {
var stack = null;
// If 'ex' is ErrorEvent, get real Error from inside
var exception = utils.isErrorEvent(ex) ? ex.error : ex;
// If 'msg' is ErrorEvent, get real message from inside
var message = utils.isErrorEvent(msg) ? msg.message : msg;
if (lastExceptionStack) {
TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(
lastExceptionStack,
url,
lineNo,
message
);
processLastException();
} else if (exception && utils.isError(exception)) {
// non-string `exception` arg; attempt to extract stack trace
// New chrome and blink send along a real error object
// Let's just report that like a normal error.
// See: https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror
stack = TraceKit.computeStackTrace(exception);
notifyHandlers(stack, true);
} else {
var location = {
url: url,
line: lineNo,
column: colNo
};
var name = undefined;
var groups;
if ({}.toString.call(message) === '[object String]') {
var groups = message.match(ERROR_TYPES_RE);
if (groups) {
name = groups[1];
message = groups[2];
}
}
location.func = UNKNOWN_FUNCTION;
stack = {
name: name,
message: message,
url: getLocationHref(),
stack: [location]
};
notifyHandlers(stack, true);
}
if (_oldOnerrorHandler) {
return _oldOnerrorHandler.apply(this, arguments);
}
return false;
}
function installGlobalHandler() {
if (_onErrorHandlerInstalled) {
return;
}
_oldOnerrorHandler = _window.onerror;
_window.onerror = traceKitWindowOnError;
_onErrorHandlerInstalled = true;
}
function uninstallGlobalHandler() {
if (!_onErrorHandlerInstalled) {
return;
}
_window.onerror = _oldOnerrorHandler;
_onErrorHandlerInstalled = false;
_oldOnerrorHandler = undefined;
}
function processLastException() {
var _lastExceptionStack = lastExceptionStack,
_lastArgs = lastArgs;
lastArgs = null;
lastExceptionStack = null;
lastException = null;
notifyHandlers.apply(null, [_lastExceptionStack, false].concat(_lastArgs));
}
/**
* Reports an unhandled Error to TraceKit.
* @param {Error} ex
* @param {?boolean} rethrow If false, do not re-throw the exception.
* Only used for window.onerror to not cause an infinite loop of
* rethrowing.
*/
function report(ex, rethrow) {
var args = _slice.call(arguments, 1);
if (lastExceptionStack) {
if (lastException === ex) {
return; // already caught by an inner catch block, ignore
} else {
processLastException();
}
}
var stack = TraceKit.computeStackTrace(ex);
lastExceptionStack = stack;
lastException = ex;
lastArgs = args;
// If the stack trace is incomplete, wait for 2 seconds for
// slow slow IE to see if onerror occurs or not before reporting
// this exception; otherwise, we will end up with an incomplete
// stack trace
setTimeout(function() {
if (lastException === ex) {
processLastException();
}
}, stack.incomplete ? 2000 : 0);
if (rethrow !== false) {
throw ex; // re-throw to propagate to the top level (and cause window.onerror)
}
}
report.subscribe = subscribe;
report.unsubscribe = unsubscribe;
report.uninstall = unsubscribeAll;
return report;
})();
/**
* TraceKit.computeStackTrace: cross-browser stack traces in JavaScript
*
* Syntax:
* s = TraceKit.computeStackTrace(exception) // consider using TraceKit.report instead (see below)
* Returns:
* s.name - exception name
* s.message - exception message
* s.stack[i].url - JavaScript or HTML file URL
* s.stack[i].func - function name, or empty for anonymous functions (if guessing did not work)
* s.stack[i].args - arguments passed to the function, if known
* s.stack[i].line - line number, if known
* s.stack[i].column - column number, if known
*
* Supports:
* - Firefox: full stack trace with line numbers and unreliable column
* number on top frame
* - Opera 10: full stack trace with line and column numbers
* - Opera 9-: full stack trace with line numbers
* - Chrome: full stack trace with line and column numbers
* - Safari: line and column number for the topmost stacktrace element
* only
* - IE: no line numbers whatsoever
*
* Tries to guess names of anonymous functions by looking for assignments
* in the source code. In IE and Safari, we have to guess source file names
* by searching for function bodies inside all page scripts. This will not
* work for scripts that are loaded cross-domain.
* Here be dragons: some function names may be guessed incorrectly, and
* duplicate functions may be mismatched.
*
* TraceKit.computeStackTrace should only be used for tracing purposes.
* Logging of unhandled exceptions should be done with TraceKit.report,
* which builds on top of TraceKit.computeStackTrace and provides better
* IE support by utilizing the window.onerror event to retrieve information
* about the top of the stack.
*
* Note: In IE and Safari, no stack trace is recorded on the Error object,
* so computeStackTrace instead walks its *own* chain of callers.
* This means that:
* * in Safari, some methods may be missing from the stack trace;
* * in IE, the topmost function in the stack trace will always be the
* caller of computeStackTrace.
*
* This is okay for tracing (because you are likely to be calling
* computeStackTrace from the function you want to be the topmost element
* of the stack trace anyway), but not okay for logging unhandled
* exceptions (because your catch block will likely be far away from the
* inner function that actually caused the exception).
*
*/
TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
// Contents of Exception in various browsers.
//
// SAFARI:
// ex.message = Can't find variable: qq
// ex.line = 59
// ex.sourceId = 580238192
// ex.sourceURL = http://...
// ex.expressionBeginOffset = 96
// ex.expressionCaretOffset = 98
// ex.expressionEndOffset = 98
// ex.name = ReferenceError
//
// FIREFOX:
// ex.message = qq is not defined
// ex.fileName = http://...
// ex.lineNumber = 59
// ex.columnNumber = 69
// ex.stack = ...stack trace... (see the example below)
// ex.name = ReferenceError
//
// CHROME:
// ex.message = qq is not defined
// ex.name = ReferenceError
// ex.type = not_defined
// ex.arguments = ['aa']
// ex.stack = ...stack trace...
//
// INTERNET EXPLORER:
// ex.message = ...
// ex.name = ReferenceError
//
// OPERA:
// ex.message = ...message... (see the example below)
// ex.name = ReferenceError
// ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message)
// ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
/**
* Computes stack trace information from the stack property.
* Chrome and Gecko use this property.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceFromStackProp(ex) {
if (typeof ex.stack === 'undefined' || !ex.stack) return;
var chrome = /^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
var winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx(?:-web)|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
// NOTE: blob urls are now supposed to always have an origin, therefore it's format
// which is `blob:http://url/path/with-some-uuid`, is matched by `blob.*?:\/` as well
var gecko = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
// Used to additionally parse URL/line/column from eval frames
var geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
var chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/;
var lines = ex.stack.split('\n');
var stack = [];
var submatch;
var parts;
var element;
var reference = /^(.*) is undefined$/.exec(ex.message);
for (var i = 0, j = lines.length; i < j; ++i) {
if ((parts = chrome.exec(lines[i]))) {
var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line
var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line
if (isEval && (submatch = chromeEval.exec(parts[2]))) {
// throw out eval line/column and use top-most line/column number
parts[2] = submatch[1]; // url
parts[3] = submatch[2]; // line
parts[4] = submatch[3]; // column
}
element = {
url: !isNative ? parts[2] : null,
func: parts[1] || UNKNOWN_FUNCTION,
args: isNative ? [parts[2]] : [],
line: parts[3] ? +parts[3] : null,
column: parts[4] ? +parts[4] : null
};
} else if ((parts = winjs.exec(lines[i]))) {
element = {
url: parts[2],
func: parts[1] || UNKNOWN_FUNCTION,
args: [],
line: +parts[3],
column: parts[4] ? +parts[4] : null
};
} else if ((parts = gecko.exec(lines[i]))) {
var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;
if (isEval && (submatch = geckoEval.exec(parts[3]))) {
// throw out eval line/column and use top-most line number
parts[3] = submatch[1];
parts[4] = submatch[2];
parts[5] = null; // no column when eval
} else if (i === 0 && !parts[5] && typeof ex.columnNumber !== 'undefined') {
// FireFox uses this awesome columnNumber property for its top frame
// Also note, Firefox's column number is 0-based and everything else expects 1-based,
// so adding 1
// NOTE: this hack doesn't work if top-most frame is eval
stack[0].column = ex.columnNumber + 1;
}
element = {
url: parts[3],
func: parts[1] || UNKNOWN_FUNCTION,
args: parts[2] ? parts[2].split(',') : [],
line: parts[4] ? +parts[4] : null,
column: parts[5] ? +parts[5] : null
};
} else {
continue;
}
if (!element.func && element.line) {
element.func = UNKNOWN_FUNCTION;
}
if (element.url && element.url.substr(0, 5) === 'blob:') {
// Special case for handling JavaScript loaded into a blob.
// We use a synchronous AJAX request here as a blob is already in
// memory - it's not making a network request. This will generate a warning
// in the browser console, but there has already been an error so that's not
// that much of an issue.
var xhr = new XMLHttpRequest();
xhr.open('GET', element.url, false);
xhr.send(null);
// If we failed to download the source, skip this patch
if (xhr.status === 200) {
var source = xhr.responseText || '';
// We trim the source down to the last 300 characters as sourceMappingURL is always at the end of the file.
// Why 300? To be in line with: https://github.com/getsentry/sentry/blob/4af29e8f2350e20c28a6933354e4f42437b4ba42/src/sentry/lang/javascript/processor.py#L164-L175
source = source.slice(-300);
// Now we dig out the source map URL
var sourceMaps = source.match(/\/\/# sourceMappingURL=(.*)$/);
// If we don't find a source map comment or we find more than one, continue on to the next element.
if (sourceMaps) {
var sourceMapAddress = sourceMaps[1];
// Now we check to see if it's a relative URL.
// If it is, convert it to an absolute one.
if (sourceMapAddress.charAt(0) === '~') {
sourceMapAddress = getLocationOrigin() + sourceMapAddress.slice(1);
}
// Now we strip the '.map' off of the end of the URL and update the
// element so that Sentry can match the map to the blob.
element.url = sourceMapAddress.slice(0, -4);
}
}
}
stack.push(element);
}
if (!stack.length) {
return null;
}
return {
name: ex.name,
message: ex.message,
url: getLocationHref(),
stack: stack
};
}
/**
* Adds information about the first frame to incomplete stack traces.
* Safari and IE require this to get complete data on the first frame.
* @param {Object.<string, *>} stackInfo Stack trace information from
* one of the compute* methods.
* @param {string} url The URL of the script that caused an error.
* @param {(number|string)} lineNo The line number of the script that
* caused an error.
* @param {string=} message The error generated by the browser, which
* hopefully contains the name of the object that caused the error.
* @return {boolean} Whether or not the stack information was
* augmented.
*/
function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) {
var initial = {
url: url,
line: lineNo
};
if (initial.url && initial.line) {
stackInfo.incomplete = false;
if (!initial.func) {
initial.func = UNKNOWN_FUNCTION;
}
if (stackInfo.stack.length > 0) {
if (stackInfo.stack[0].url === initial.url) {
if (stackInfo.stack[0].line === initial.line) {
return false; // already in stack trace
} else if (
!stackInfo.stack[0].line &&
stackInfo.stack[0].func === initial.func
) {
stackInfo.stack[0].line = initial.line;
return false;
}
}
}
stackInfo.stack.unshift(initial);
stackInfo.partial = true;
return true;
} else {
stackInfo.incomplete = true;
}
return false;
}
/**
* Computes stack trace information by walking the arguments.caller
* chain at the time the exception occurred. This will cause earlier
* frames to be missed but is the only way to get any stack trace in
* Safari and IE. The top frame is restored by
* {@link augmentStackTraceWithInitialElement}.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceByWalkingCallerChain(ex, depth) {
var functionName = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,
stack = [],
funcs = {},
recursion = false,
parts,
item,
source;
for (
var curr = computeStackTraceByWalkingCallerChain.caller;
curr && !recursion;
curr = curr.caller
) {
if (curr === computeStackTrace || curr === TraceKit.report) {
// console.log('skipping internal function');
continue;
}
item = {
url: null,
func: UNKNOWN_FUNCTION,
line: null,
column: null
};
if (curr.name) {
item.func = curr.name;
} else if ((parts = functionName.exec(curr.toString()))) {
item.func = parts[1];
}
if (typeof item.func === 'undefined') {
try {
item.func = parts.input.substring(0, parts.input.indexOf('{'));
} catch (e) {}
}
if (funcs['' + curr]) {
recursion = true;
} else {
funcs['' + curr] = true;
}
stack.push(item);
}
if (depth) {
// console.log('depth is ' + depth);
// console.log('stack is ' + stack.length);
stack.splice(0, depth);
}
var result = {
name: ex.name,
message: ex.message,
url: getLocationHref(),
stack: stack
};
augmentStackTraceWithInitialElement(
result,
ex.sourceURL || ex.fileName,
ex.line || ex.lineNumber,
ex.message || ex.description
);
return result;
}
/**
* Computes a stack trace for an exception.
* @param {Error} ex
* @param {(string|number)=} depth
*/
function computeStackTrace(ex, depth) {
var stack = null;
depth = depth == null ? 0 : +depth;
try {
stack = computeStackTraceFromStackProp(ex);
if (stack) {
return stack;
}
} catch (e) {
if (TraceKit.debug) {
throw e;
}
}
try {
stack = computeStackTraceByWalkingCallerChain(ex, depth + 1);
if (stack) {
return stack;
}
} catch (e) {
if (TraceKit.debug) {
throw e;
}
}
return {
name: ex.name,
message: ex.message,
url: getLocationHref()
};
}
computeStackTrace.augmentStackTraceWithInitialElement = augmentStackTraceWithInitialElement;
computeStackTrace.computeStackTraceFromStackProp = computeStackTraceFromStackProp;
return computeStackTrace;
})();
module.exports = TraceKit;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"8":8}],10:[function(_dereq_,module,exports){
/*
json-stringify-safe
Like JSON.stringify, but doesn't throw on circular references.
Originally forked from https://github.com/isaacs/json-stringify-safe
version 5.0.1 on 3/8/2017 and modified to handle Errors serialization
and IE8 compatibility. Tests for this are in test/vendor.
ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE
*/
exports = module.exports = stringify;
exports.getSerialize = serializer;
function indexOf(haystack, needle) {
for (var i = 0; i < haystack.length; ++i) {
if (haystack[i] === needle) return i;
}
return -1;
}
function stringify(obj, replacer, spaces, cycleReplacer) {
return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
}
// https://github.com/ftlabs/js-abbreviate/blob/fa709e5f139e7770a71827b1893f22418097fbda/index.js#L95-L106
function stringifyError(value) {
var err = {
// These properties are implemented as magical getters and don't show up in for in
stack: value.stack,
message: value.message,
name: value.name
};
for (var i in value) {
if (Object.prototype.hasOwnProperty.call(value, i)) {
err[i] = value[i];
}
}
return err;
}
function serializer(replacer, cycleReplacer) {
var stack = [];
var keys = [];
if (cycleReplacer == null) {
cycleReplacer = function(key, value) {
if (stack[0] === value) {
return '[Circular ~]';
}
return '[Circular ~.' + keys.slice(0, indexOf(stack, value)).join('.') + ']';
};
}
return function(key, value) {
if (stack.length > 0) {
var thisPos = indexOf(stack, this);
~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
if (~indexOf(stack, value)) {
value = cycleReplacer.call(this, key, value);
}
} else {
stack.push(value);
}
return replacer == null
? value instanceof Error ? stringifyError(value) : value
: replacer.call(this, key, value);
};
}
},{}],11:[function(_dereq_,module,exports){
/*
* JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd(x, y) {
var lsw = (x & 0xffff) + (y & 0xffff);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRotateLeft(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn((b & c) | (~b & d), a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & ~d), a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binlMD5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i;
var olda;
var oldb;
var oldc;
var oldd;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i;
var output = '';
var length32 = input.length * 32;
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xff);
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i;
var output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
var length8 = input.length * 8;
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << (i % 32);
}
return output;
}
/*
* Calculate the MD5 of a raw string
*/
function rstrMD5(s) {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstrHMACMD5(key, data) {
var i;
var bkey = rstr2binl(key);
var ipad = [];
var opad = [];
var hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binlMD5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5c5c5c5c;
}
hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binlMD5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hexTab = '0123456789abcdef';
var output = '';
var x;
var i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f);
}
return output;
}
/*
* Encode a string as utf-8
*/
function str2rstrUTF8(input) {
return unescape(encodeURIComponent(input));
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function rawMD5(s) {
return rstrMD5(str2rstrUTF8(s));
}
function hexMD5(s) {
return rstr2hex(rawMD5(s));
}
function rawHMACMD5(k, d) {
return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d));
}
function hexHMACMD5(k, d) {
return rstr2hex(rawHMACMD5(k, d));
}
function md5(string, key, raw) {
if (!key) {
if (!raw) {
return hexMD5(string);
}
return rawMD5(string);
}
if (!raw) {
return hexHMACMD5(key, string);
}
return rawHMACMD5(key, string);
}
module.exports = md5;
},{}]},{},[7,1,2,3])(7)
});
|
FloatingActionButton.js | alangpierce/LambdaCalculusPlayground | /**
* @flow
*/
import React from 'react';
import {
Image,
TouchableWithoutFeedback,
View,
} from 'react-native';
import StatelessComponent from './StatelessComponent';
type AssetId = number;
/**
* Custom-built FAB since none of the existing FABs seem to work the way I want.
*
* TODO: Consolidate with ExecuteButton.js
*/
type ExecuteButtonPropTypes = {
onPress: () => void,
source: AssetId,
style: any,
};
class FloatingActionButton extends StatelessComponent<ExecuteButtonPropTypes> {
render() {
const {onPress, source} = this.props;
return <TouchableWithoutFeedback onPress={onPress}>
<View style={{
width: 56,
height: 56,
backgroundColor: '#00AA00',
borderRadius: 28,
elevation: 6,
alignItems: 'center',
justifyContent: 'center',
...this.props.style,
}}>
<Image
source={source}
style={{
width: 24,
height: 24,
tintColor: 'white',
resizeMode: 'contain',
}}
/>
</View>
</TouchableWithoutFeedback>;
}
}
export default FloatingActionButton; |
src/svg-icons/maps/flight.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsFlight = (props) => (
<SvgIcon {...props}>
<path d="M10.18 9"/><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>
</SvgIcon>
);
MapsFlight = pure(MapsFlight);
MapsFlight.displayName = 'MapsFlight';
export default MapsFlight;
|
packages/reactor-kitchensink/src/examples/Charts/Area/StackedArea/StackedArea.js | sencha/extjs-reactor | import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
export default class StackedAreaChartExample extends Component {
constructor(){
super();
}
store = Ext.create('Ext.data.Store', {
fields:['month', 'data1', 'data2', 'data3', 'data4', 'other'],
data:[
{ month: 'Jan', data1: 20, data2: 37, data3: 35, data4: 4, other: 4 },
{ month: 'Feb', data1: 20, data2: 37, data3: 36, data4: 5, other: 2 },
{ month: 'Mar', data1: 19, data2: 36, data3: 37, data4: 4, other: 4 },
{ month: 'Apr', data1: 18, data2: 36, data3: 38, data4: 5, other: 3 },
{ month: 'May', data1: 18, data2: 35, data3: 39, data4: 4, other: 4 },
{ month: 'Jun', data1: 17, data2: 34, data3: 42, data4: 4, other: 3 },
{ month: 'Jul', data1: 16, data2: 34, data3: 43, data4: 4, other: 3 },
{ month: 'Aug', data1: 16, data2: 33, data3: 44, data4: 4, other: 3 },
{ month: 'Sep', data1: 16, data2: 32, data3: 44, data4: 4, other: 4 },
{ month: 'Oct', data1: 16, data2: 32, data3: 45, data4: 4, other: 3 },
{ month: 'Nov', data1: 15, data2: 31, data3: 46, data4: 4, other: 4 },
{ month: 'Dec', data1: 15, data2: 31, data3: 47, data4: 4, other: 3 }]
});
state = {
theme: 'default'
};
changeTheme = theme => this.setState({ theme })
onAxisLabelRender = (axis, label) => {
return label.toFixed(label < 10 ? 1 : 0) + '%';
}
onSeriesTooltipRender = (tooltip, record, item) => {
var fieldIndex = Ext.Array.indexOf(item.series.getYField(), item.field),
browser = item.series.getTitle()[fieldIndex];
tooltip.setHtml(`${browser} on ${record.get('month')}: ${record.get(item.field)}%`)
}
render() {
const { theme } = this.state;
return (
<Container padding={!Ext.os.is.Phone && 10} layout="fit">
<ChartToolbar
onThemeChange={this.changeTheme}
theme={theme}
/>
<Cartesian
shadow
store={this.store}
theme={theme}
insetPadding={'20 20 10 10'}
legend={{type:'sprite'}}
axes={[{
type: 'numeric',
fields: 'data1',
position: 'left',
grid: true,
minimum: 0,
renderer: this.onAxisLabelRender
}, {
type: 'category',
fields: 'month',
position: 'bottom',
grid: true,
label: {
rotate: {
degrees: -90
}
}
}]}
series={[{
type: 'area',
title: [ 'IE', 'Firefox', 'Chrome', 'Safari' ],
xField: 'month',
yField: [ 'data1', 'data2', 'data3', 'data4' ],
style: {
opacity: 0.80
},
marker: {
opacity: 0,
scaling: 0.01,
animation: {
duration: 200,
easing: 'easeOut'
}
},
highlightCfg: {
opacity: 1,
scaling: 1.5
},
tooltip: {
trackMouse: true,
renderer: this.onSeriesTooltipRender
}
}]}
/>
</Container>
)
}
} |
node_modules/react-router/es/Prompt.js | morselapp/shop_directory | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
/**
* The public API for prompting the user before navigating away
* from a screen with a component.
*/
var Prompt = function (_React$Component) {
_inherits(Prompt, _React$Component);
function Prompt() {
_classCallCheck(this, Prompt);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Prompt.prototype.enable = function enable(message) {
if (this.unblock) this.unblock();
this.unblock = this.context.router.history.block(message);
};
Prompt.prototype.disable = function disable() {
if (this.unblock) {
this.unblock();
this.unblock = null;
}
};
Prompt.prototype.componentWillMount = function componentWillMount() {
if (this.props.when) this.enable(this.props.message);
};
Prompt.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps.when) {
if (!this.props.when || this.props.message !== nextProps.message) this.enable(nextProps.message);
} else {
this.disable();
}
};
Prompt.prototype.componentWillUnmount = function componentWillUnmount() {
this.disable();
};
Prompt.prototype.render = function render() {
return null;
};
return Prompt;
}(React.Component);
Prompt.propTypes = {
when: PropTypes.bool,
message: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired
};
Prompt.defaultProps = {
when: true
};
Prompt.contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
block: PropTypes.func.isRequired
}).isRequired
}).isRequired
};
export default Prompt; |
src/svg-icons/device/developer-mode.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceDeveloperMode = (props) => (
<SvgIcon {...props}>
<path d="M7 5h10v2h2V3c0-1.1-.9-1.99-2-1.99L7 1c-1.1 0-2 .9-2 2v4h2V5zm8.41 11.59L20 12l-4.59-4.59L14 8.83 17.17 12 14 15.17l1.41 1.42zM10 15.17L6.83 12 10 8.83 8.59 7.41 4 12l4.59 4.59L10 15.17zM17 19H7v-2H5v4c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-4h-2v2z"/>
</SvgIcon>
);
DeviceDeveloperMode = pure(DeviceDeveloperMode);
DeviceDeveloperMode.displayName = 'DeviceDeveloperMode';
DeviceDeveloperMode.muiName = 'SvgIcon';
export default DeviceDeveloperMode;
|
ajax/libs/jquery-localScroll/1.3.3/jquery.localScroll.js | jamzgoodguy/cdnjs | /*!
* jQuery.localScroll
* Copyright (c) 2007-2014 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Licensed under MIT
* http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html
* @author Ariel Flesler
* @version 1.3.3
*/
;(function(plugin) {
// AMD Support
if (typeof define === 'function' && define.amd) {
define('jquery.localScroll', ['jquery', 'jquery.scrollTo'], plugin);
} else {
plugin(jQuery);
}
}(function($) {
var URI = location.href.replace(/#.*/, ''); // local url without hash
var $localScroll = $.localScroll = function(settings) {
$('body').localScroll(settings);
};
// Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
// @see http://demos.flesler.com/jquery/scrollTo/
// The defaults are public and can be overriden.
$localScroll.defaults = {
duration: 1000, // How long to animate.
axis: 'y', // Which of top and left should be modified.
event: 'click', // On which event to react.
stop: true, // Avoid queuing animations
target: window // What to scroll (selector or element). The whole window by default.
/*
lock: false, // ignore events if already animating
lazy: false, // if true, links can be added later, and will still work.
filter: null, // filter some anchors out of the matched elements.
hash: false // if true, the hash of the selected link, will appear on the address bar.
*/
};
$.fn.localScroll = function(settings) {
settings = $.extend({}, $localScroll.defaults, settings);
if (settings.hash && location.hash) {
if (settings.target) window.scrollTo(0, 0);
scroll(0, location, settings);
}
return settings.lazy ?
// use event delegation, more links can be added later.
this.bind(settings.event, function(e) {
// Could use closest(), but that would leave out jQuery -1.3.x
var a = $([e.target, e.target.parentNode]).filter(filter)[0];
// if a valid link was clicked
if (a)
scroll(e, a, settings); // do scroll.
}) :
// bind concretely, to each matching link
this.find('a,area')
.filter(filter).bind(settings.event, function(e) {
scroll(e, this, settings);
}).end()
.end();
function filter() {// is this a link that points to an anchor and passes a possible filter ? href is checked to avoid a bug in FF.
return !!this.href && !!this.hash && this.href.replace(this.hash,'') == URI && (!settings.filter || $(this).is(settings.filter));
};
};
// Not needed anymore, kept for backwards compatibility
$localScroll.hash = function() {};
function scroll(e, link, settings) {
var id = link.hash.slice(1),
elem = document.getElementById(id) || document.getElementsByName(id)[0];
if (!elem)
return;
if (e)
e.preventDefault();
var $target = $(settings.target);
if (settings.lock && $target.is(':animated') ||
settings.onBefore && settings.onBefore(e, elem, $target) === false)
return;
if (settings.stop)
$target._scrollable().stop(true); // remove all its animations
if (settings.hash) {
var attr = elem.id === id ? 'id' : 'name',
$a = $('<a> </a>').attr(attr, id).css({
position:'absolute',
top: $(window).scrollTop(),
left: $(window).scrollLeft()
});
elem[attr] = '';
$('body').prepend($a);
location.hash = link.hash;
$a.remove();
elem[attr] = id;
}
$target
.scrollTo(elem, settings) // do scroll
.trigger('notify.serialScroll',[elem]); // notify serialScroll about this change
};
// AMD requirement
return $localScroll;
})); |
examples/js/hacker-news/client/containers/LoginInfo.js | reimagined/resolve | import React from 'react'
import { useSelector } from 'react-redux'
import styled from 'styled-components'
import { Link as NormalLink } from 'react-router-dom'
import { Splitter } from '../components/Splitter'
import { Form } from './Form'
const Link = styled(NormalLink)`
color: white;
&.active {
font-weight: bold;
text-decoration: underline;
}
`
const PageAuth = styled.div`
float: right;
`
const LoginInfo = () => {
const me = useSelector((state) => state.jwt)
return (
<PageAuth>
{me && me.id ? (
<div>
<Link to={`/user/${me.id}`}>{me.name}</Link>
<Splitter color="white" />
<Link
to="/newest"
onClick={() =>
document.getElementById('hidden-form-for-logout').submit()
}
>
logout
</Link>
<Form method="post" id="hidden-form-for-logout" action="/api/logout">
<input type="hidden" name="username" value="null" />
<input type="hidden" />
</Form>
</div>
) : (
<Link to="/login">login</Link>
)}
</PageAuth>
)
}
export { LoginInfo }
|
src/svg-icons/image/crop.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCrop = (props) => (
<SvgIcon {...props}>
<path d="M17 15h2V7c0-1.1-.9-2-2-2H9v2h8v8zM7 17V1H5v4H1v2h4v10c0 1.1.9 2 2 2h10v4h2v-4h4v-2H7z"/>
</SvgIcon>
);
ImageCrop = pure(ImageCrop);
ImageCrop.displayName = 'ImageCrop';
ImageCrop.muiName = 'SvgIcon';
export default ImageCrop;
|
kitsune/sumo/static/sumo/js/tests/lazyloadtests.js | silentbob73/kitsune | import {default as mochaJsdom, rerequire} from 'mocha-jsdom';
import {default as chai, expect} from 'chai';
import React from 'react';
import chaiLint from 'chai-lint';
import mochaJquery from './fixtures/mochaJquery.js';
chai.use(chaiLint);
describe('lazyload', () => {
mochaJsdom({useEach: true});
mochaJquery();
/* globals document, $ */
beforeEach(() => {
rerequire('../libs/jquery.lazyload.js');
});
it('should load original image', () => {
let img = <img className="lazy" data-original-src="http://example.com/test.jpg"/>;
React.render(img, document.body);
let $img = $('img');
$.fn.lazyload.loadOriginalImage($img);
expect($img.attr('src')).to.equal('http://example.com/test.jpg');
});
});
|
assets/jqwidgets/demos/react/app/tabs/defaultfunctionality/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxTabs from '../../../jqwidgets-react/react_jqxtabs.js';
import JqxCheckBox from '../../../jqwidgets-react/react_jqxcheckbox.js';
class App extends React.Component {
componentDidMount() {
this.refs.animation.on('change', (event) => {
let checked = event.args.checked;
this.refs.myTabs.selectionTracker(checked);
});
this.refs.contentAnimation.on('change', (event) => {
let checked = event.args.checked;
if (checked) {
this.refs.myTabs.animationType('fade');
}
else {
this.refs.myTabs.animationType('none');
}
});
}
render () {
let tabsHTML = `
<ul>
<li style="margin-left: 30px;">Node.js</li>
<li>JavaServer Pages</li>
<li>Active Server Pages</li>
<li>Python</li>
<li>Perl</li>
</ul>
<div>
Node.js is an event-driven I/O server-side JavaScript environment based on V8. It
is intended for writing scalable network programs such as web servers. It was created
by Ryan Dahl in 2009, and its growth is sponsored by Joyent, which employs Dahl.
Similar environments written in other programming languages include Twisted for
Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby.
Unlike most JavaScript, it is not executed in a web browser, but is instead a form
of server-side JavaScript. Node.js implements some CommonJS specifications. Node.js
includes a REPL environment for interactive testing.
</div>
<div>
JavaServer Pages (JSP) is a Java technology that helps software developers serve
dynamically generated web pages based on HTML, XML, or other document types. Released
in 1999 as Sun's answer to ASP and PHP,[citation needed] JSP was designed to address
the perception that the Java programming environment didn't provide developers with
enough support for the Web. To deploy and run, a compatible web server with servlet
container is required. The Java Servlet and the JavaServer Pages (JSP) specifications
from Sun Microsystems and the JCP (Java Community Process) must both be met by the
container.
</div>
<div>
ASP.NET is a web application framework developed and marketed by Microsoft to allow
programmers to build dynamic web sites, web applications and web services. It was
first released in January 2002 with version 1.0 of the .NET Framework, and is the
successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built
on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code
using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET
components to process SOAP messages.
</div>
<div>
Python is a general-purpose, high-level programming language[5] whose design philosophy
emphasizes code readability. Python claims to "[combine] remarkable power with very
clear syntax",[7] and its standard library is large and comprehensive. Its use of
indentation for block delimiters is unique among popular programming languages.
Python supports multiple programming paradigms, primarily but not limited to object-oriented,
imperative and, to a lesser extent, functional programming styles. It features a
fully dynamic type system and automatic memory management, similar to that of Scheme,
Ruby, Perl, and Tcl. Like other dynamic languages, Python is often used as a scripting
language, but is also used in a wide range of non-scripting contexts.
</div>
<div>
Perl is a high-level, general-purpose, interpreted, dynamic programming language.
Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting
language to make report processing easier. Since then, it has undergone many changes
and revisions and become widely popular amongst programmers. Larry Wall continues
to oversee development of the core language, and its upcoming version, Perl 6. Perl
borrows features from other programming languages including C, shell scripting (sh),
AWK, and sed.[5] The language provides powerful text processing facilities without
the arbitrary data length limits of many contemporary Unix tools, facilitating easy
manipulation of text files.
</div>
`;
return (
<div>
<JqxTabs ref='myTabs' template={tabsHTML}
width={'90%'} height={200} position={'top'}
/>
<div id='settings' style={{ marginTop: 5 }}>
<JqxCheckBox ref='animation' style={{ marginTop: 10 }} value='Enable Select Animation'/>
<JqxCheckBox ref='contentAnimation' style={{ marginTop: 10 }} value='Enable Content Animation'/>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
app/javascript/mastodon/components/hashtag.js | MastodonCloud/mastodon | import React from 'react';
import { Sparklines, SparklinesCurve } from 'react-sparklines';
import { Link } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { shortNumberFormat } from '../utils/numbers';
const Hashtag = ({ hashtag }) => (
<div className='trends__item'>
<div className='trends__item__name'>
<Link to={`/timelines/tag/${hashtag.get('name')}`}>
#<span>{hashtag.get('name')}</span>
</Link>
<FormattedMessage id='trends.count_by_accounts' defaultMessage='{count} {rawCount, plural, one {person} other {people}} talking' values={{ rawCount: hashtag.getIn(['history', 0, 'accounts']), count: <strong>{shortNumberFormat(hashtag.getIn(['history', 0, 'accounts']))}</strong> }} />
</div>
<div className='trends__item__current'>
{shortNumberFormat(hashtag.getIn(['history', 0, 'uses']))}
</div>
<div className='trends__item__sparkline'>
<Sparklines width={50} height={28} data={hashtag.get('history').reverse().map(day => day.get('uses')).toArray()}>
<SparklinesCurve style={{ fill: 'none' }} />
</Sparklines>
</div>
</div>
);
Hashtag.propTypes = {
hashtag: ImmutablePropTypes.map.isRequired,
};
export default Hashtag;
|
app/routes.js | sachinmour/newedenfaces-react | import React from 'react';
import {Route} from 'react-router';
import App from './components/App';
import Home from './components/Home';
import Stats from './components/Stats';
import Character from './components/Character';
import CharacterList from './components/CharacterList';
import AddCharacter from './components/AddCharacter';
export default (
<Route component={App}>
<Route path='/' component={Home} />
<Route path='/stats' component={Stats} />
<Route path='/characters/:id' component={Character} />
<Route path='/add' component={AddCharacter} />
<Route path=':category' component={CharacterList}>
<Route path=':race' component={CharacterList}>
<Route path=':bloodline' component={CharacterList} />
</Route>
</Route>
</Route>
);
|
addons/themes/striped/layouts/Home.js | rendact/rendact | import $ from 'jquery'
import React from 'react';
import gql from 'graphql-tag';
import {graphql} from 'react-apollo';
import moment from 'moment';
import {Link} from 'react-router';
import scrollToElement from 'scroll-to-element';
let Home = React.createClass({
componentDidMount(){
require('../assets/css/main.css')
},
handleScrolly(e){
scrollToElement("#inti", {
duration: 1500,
offset: 0,
ease: 'in-sine'
})
},
render(){
let {
theConfig,
data,
thePagination,
loadDone
} = this.props
return (
<div>
<div id="content">
<div className="inner">
{data && data.map((post, index) => (
<article className="box post post-excerpt">
<header>
<h2><Link to={"/post/" + post.id}>{post.title && post.title}</Link></h2>
</header>
<div className="info">
<span className="date"><span className="month">Jul<span>y</span></span> <span className="day">14</span><span className="year">, 2014</span></span>
<ul className="stats">
<li><a href="#" className="icon fa-comment">16</a></li>
<li><a href="#" className="icon fa-heart">32</a></li>
<li><a href="#" className="icon fa-twitter">64</a></li>
<li><a href="#" className="icon fa-facebook">128</a></li>
</ul>
</div>
<Link className="image featured" to={"/post/" + post.id}>
<img src={post.imageFeatured ? post.imageFeatured.blobUrl: require('images/logo-128.png') } alt="" />
</Link>
<p dangerouslySetInnerHTML={{__html: post.content ? post.content.slice(0, 220):""}} />
<Link className="button" to={"/post/" + post.id}>Read More</Link>
</article>
))}
<div style={{textAlign: "center"}}>
{this.props.thePagination}
</div>
</div>
</div>
<div id="sidebar">
<h1 id="logo"><Link to={"/"}>{theConfig?theConfig.name:"Rendact"}</Link></h1>
<nav id="nav">
{this.props.theMenu()}
</nav>
<section className="box search">
<form method="post" action="#">
<input type="text" className="text" name="search" placeholder="Search" />
</form>
</section>
<section className="box text-style1">
<div className="inner">
<p>
<strong>Striped:</strong> A free and fully responsive HTML5 site
template designed by <a href="http://twitter.com/ajlkn">AJ</a> for <a href="http://html5up.net/">HTML5 UP</a>
</p>
</div>
</section>
{this.props.footerWidgets &&
this.props.footerWidgets.map((fw, idx) =><section className="box recent-posts">{fw}</section>)}
<section className="box calendar">
<div className="inner">
<table>
<caption>July 2014</caption>
<thead>
<tr>
<th scope="col" title="Monday">M</th>
<th scope="col" title="Tuesday">T</th>
<th scope="col" title="Wednesday">W</th>
<th scope="col" title="Thursday">T</th>
<th scope="col" title="Friday">F</th>
<th scope="col" title="Saturday">S</th>
<th scope="col" title="Sunday">S</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" className="pad"><span> </span></td>
<td><span>1</span></td>
<td><span>2</span></td>
<td><span>3</span></td>
</tr>
<tr>
<td><span>4</span></td>
<td><span>5</span></td>
<td><a href="#">6</a></td>
<td><span>7</span></td>
<td><span>8</span></td>
<td><span>9</span></td>
<td><a href="#">10</a></td>
</tr>
<tr>
<td><span>11</span></td>
<td><span>12</span></td>
<td><span>13</span></td>
<td className="today"><a href="#">14</a></td>
<td><span>15</span></td>
<td><span>16</span></td>
<td><span>17</span></td>
</tr>
<tr>
<td><span>18</span></td>
<td><span>19</span></td>
<td><span>20</span></td>
<td><span>21</span></td>
<td><span>22</span></td>
<td><a href="#">23</a></td>
<td><span>24</span></td>
</tr>
<tr>
<td><a href="#">25</a></td>
<td><span>26</span></td>
<td><span>27</span></td>
<td><span>28</span></td>
<td className="pad" colspan="3"><span> </span></td>
</tr>
</tbody>
</table>
</div>
</section>
<ul id="copyright">
<li>© Rendact.</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</div>
)
}
});
export default Home; |
src/js/components/Grommet/stories/Background.js | HewlettPackard/grommet | import React from 'react';
import { grommet, Grommet, Box, Text } from 'grommet';
import { hpe } from 'grommet-theme-hpe';
export const Background = () => {
const themeColor = 'background-back';
const hexValue = '#DCD0FF';
const cssColor = 'gold';
return (
<Box gap="medium">
<Grommet>
<Box pad="medium">
<Text>Grommet with no theme or background prop</Text>
</Box>
</Grommet>
<Grommet theme={hpe} themeMode="dark">
<Box pad="medium">
<Text>Grommet with theme & themeMode but no background prop</Text>
</Box>
</Grommet>
<Grommet theme={hpe} themeMode="light" background={themeColor}>
<Box pad="medium">
<Text>
Grommet with background as theme color of '{themeColor}'
</Text>
</Box>
</Grommet>
<Grommet theme={grommet} background={hexValue}>
<Box pad="medium">
<Text>
Grommet with background as HEX value of '{hexValue}'
</Text>
</Box>
</Grommet>
<Grommet theme={grommet} background={cssColor}>
<Box pad="medium">
<Text>
Grommet with background as CSS color name of '{cssColor}'
</Text>
</Box>
</Grommet>
<Grommet
theme={grommet}
background={{
color: 'pink',
image:
'url(http://librelogo.org/wp-content/uploads/2014/04/gradient2.png)',
}}
>
<Box pad="medium">
<Text>
Grommet with background as object containing color and image
</Text>
</Box>
</Grommet>
</Box>
);
};
export default {
title: 'Utilities/Grommet/Background',
};
|
src/Parser/Hunter/Marksmanship/Modules/Items/MKIIGyroscopicStabilizer.js | enragednuke/WoWAnalyzer | import React from 'react';
import ITEMS from 'common/ITEMS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Wrapper from 'common/Wrapper';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
/**
* Equip: Your Aimed Shot grants you gyroscopic stabilization, increasing the critical strike chance of your next Aimed Shot by 15% and making it castable while moving.
*/
class MKIIGyroscopicStabilizer extends Analyzer {
static dependencies = {
combatants: Combatants,
};
usedBuffs = 0;
on_initialized() {
this.active = this.combatants.selected.hasHands(ITEMS.MKII_GYROSCOPIC_STABILIZER.id);
}
on_byPlayer_removebuff(event) {
const buffId = event.ability.guid;
if (buffId !== SPELLS.GYROSCOPIC_STABILIZATION.id) {
return;
}
this.usedBuffs += 1;
}
item() {
return {
item: ITEMS.MKII_GYROSCOPIC_STABILIZER,
result: <Wrapper>This allowed you to move while casting {this.usedBuffs} <SpellLink id={SPELLS.AIMED_SHOT.id} />s throughout the fight, these <SpellLink id={SPELLS.AIMED_SHOT.id} />s also had 15% increased crit chance.</Wrapper>,
};
}
}
export default MKIIGyroscopicStabilizer;
|
project_react_template/src/js/components/Navbar.js | Mikeysax/mikey | import React from 'react';
export default class Navbar extends React.Component {
render() {
return (
<div>
<nav className="navbar navbar-default text-center" role="navigation">
<a href="https://www.npmjs.com/package/mikey">
Mikey
</a>
was built by
<a href="http://mikeysax.com">
Mikeysax
</a>
Made with love for the <a href="http://theFirehoseProject.com">Firehose Project</a>
</nav>
</div>
);
}
}
|
node_modules/react-bootstrap/es/CarouselItem.js | skinsshark/skinsshark.github.io | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import TransitionEvents from './utils/TransitionEvents';
// TODO: This should use a timeout instead of TransitionEvents, or else just
// not wait until transition end to trigger continuing animations.
var propTypes = {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
index: React.PropTypes.number
};
var defaultProps = {
active: false,
animateIn: false,
animateOut: false
};
var CarouselItem = function (_React$Component) {
_inherits(CarouselItem, _React$Component);
function CarouselItem(props, context) {
_classCallCheck(this, CarouselItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this);
_this.state = {
direction: null
};
_this.isUnmounted = false;
return _this;
}
CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({ direction: null });
}
};
CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var active = this.props.active;
var prevActive = prevProps.active;
if (!active && prevActive) {
TransitionEvents.addEndEventListener(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd);
}
if (active !== prevActive) {
setTimeout(function () {
return _this2.startAnimation();
}, 20);
}
};
CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() {
this.isUnmounted = true;
};
CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() {
if (this.isUnmounted) {
return;
}
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd(this.props.index);
}
};
CarouselItem.prototype.startAnimation = function startAnimation() {
if (this.isUnmounted) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
};
CarouselItem.prototype.render = function render() {
var _props = this.props;
var direction = _props.direction;
var active = _props.active;
var animateIn = _props.animateIn;
var animateOut = _props.animateOut;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']);
delete props.onAnimateOutEnd;
delete props.index;
var classes = {
item: true,
active: active && !animateIn || animateOut
};
if (direction && active && animateIn) {
classes[direction] = true;
}
if (this.state.direction && (animateIn || animateOut)) {
classes[this.state.direction] = true;
}
return React.createElement('div', _extends({}, props, {
className: classNames(className, classes)
}));
};
return CarouselItem;
}(React.Component);
CarouselItem.propTypes = propTypes;
CarouselItem.defaultProps = defaultProps;
export default CarouselItem; |
frontend/src/picturedisplay/components/TagDisplay.js | mangosmoothie/picappa | import React from 'react'
import List from 'material-ui/List'
import Subheader from 'material-ui/Subheader';
import Chip from 'material-ui/Chip'
const Tag = ( {onTagClick, name} ) => {
const style = {
margin: 4
}
return (
<Chip style={style} onClick={onTagClick}>
{name}
</Chip>
)
}
export default ({ tags, onTagClick, title }) => {
const style = {
list: {
align: 'center',
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap'
}
}
return (
<List style={style.list}>
<Subheader>{title}</Subheader>
{Object.values(tags).map(function (tag) {
return (
<Tag key={tag.id}
onTagClick={() => onTagClick(tag.id)}
name={tag.name} />
)
})}
</List>
)
}
|
node_modules/react/lib/ReactInstanceMap.js | dianpan/github-tags | /**
* Copyright 2013-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.
*
* @providesModule ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function(key) {
key._reactInternalInstance = undefined;
},
get: function(key) {
return key._reactInternalInstance;
},
has: function(key) {
return key._reactInternalInstance !== undefined;
},
set: function(key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
|
docs/src/app/components/pages/components/FlatButton/Page.js | kittyjumbalaya/material-components-web | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import flatButtonReadmeText from './README';
import flatButtonExampleSimpleCode from '!raw!./ExampleSimple';
import FlatButtonExampleSimple from './ExampleSimple';
import flatButtonExampleComplexCode from '!raw!./ExampleComplex';
import FlatButtonExampleComplex from './ExampleComplex';
import flatButtonExampleIconCode from '!raw!./ExampleIcon';
import FlatButtonExampleIcon from './ExampleIcon';
import flatButtonCode from '!raw!material-ui/FlatButton/FlatButton';
const descriptions = {
simple: '`FlatButton` with default color, `primary`, `secondary` and `disabled` props applied.',
complex: 'The first example uses an `input` as a child component. ' +
'The second example has an [SVG Icon](/#/components/svg-icon), with the label positioned after. ' +
'The final example uses a [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.',
icon: 'Examples of Flat Buttons using an icon without a label. The first example uses an' +
' [SVG Icon](/#/components/svg-icon), and has the default color. The second example shows' +
' how the icon and background color can be changed. The final example uses a' +
' [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.',
};
const FlatButtonPage = () => (
<div>
<Title render={(previousTitle) => `Flat Button - ${previousTitle}`} />
<MarkdownElement text={flatButtonReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={flatButtonExampleSimpleCode}
>
<FlatButtonExampleSimple />
</CodeExample>
<CodeExample
title="Complex examples"
description={descriptions.complex}
code={flatButtonExampleComplexCode}
>
<FlatButtonExampleComplex />
</CodeExample>
<CodeExample
title="Icon examples"
description={descriptions.icon}
code={flatButtonExampleIconCode}
>
<FlatButtonExampleIcon />
</CodeExample>
<PropTypeDescription code={flatButtonCode} />
</div>
);
export default FlatButtonPage;
|
api/app/components/activities/tags.js | cmilfont/zonaextrema | import React from 'react';
import TagEdit from './tagedit.js'
export default function TagsCard( {description='',editHandler} ) {
const createTag = (tag, index) =>
<TagEdit key={`tag${index}`} description={tag} editHandler={editHandler} />;
const list = description.split(' ')
.map( createTag );
return (
<div className="mdl-cell--hide-phone tags">
{list}
</div>
);
}
TagsCard.propTypes = { description: React.PropTypes.string };
|
packages/material-ui-icons/src/ColorizeTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M15.8961 9.0233l-.9192-.9192 2.694-2.694.9193.9192z" opacity=".3" /><path d="M20.71 5.63l-2.34-2.34c-.2-.2-.45-.29-.71-.29s-.51.1-.7.29l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19zm8.98-9.97l-.93-.93 2.69-2.69.92.92-2.68 2.7z" /></g></React.Fragment>
, 'ColorizeTwoTone');
|
src/svg-icons/social/person-outline.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPersonOutline = (props) => (
<SvgIcon {...props}>
<path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/>
</SvgIcon>
);
SocialPersonOutline = pure(SocialPersonOutline);
SocialPersonOutline.displayName = 'SocialPersonOutline';
SocialPersonOutline.muiName = 'SvgIcon';
export default SocialPersonOutline;
|
src/renderers/dom/shared/ReactDefaultInjection.js | agileurbanite/react | /**
* Copyright 2013-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.
*
* @providesModule ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = require('BeforeInputEventPlugin');
var ChangeEventPlugin = require('ChangeEventPlugin');
var ClientReactRootIndex = require('ClientReactRootIndex');
var DefaultEventPluginOrder = require('DefaultEventPluginOrder');
var EnterLeaveEventPlugin = require('EnterLeaveEventPlugin');
var ExecutionEnvironment = require('ExecutionEnvironment');
var HTMLDOMPropertyConfig = require('HTMLDOMPropertyConfig');
var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin');
var ReactComponentBrowserEnvironment =
require('ReactComponentBrowserEnvironment');
var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy');
var ReactDOMComponent = require('ReactDOMComponent');
var ReactDOMTextComponent = require('ReactDOMTextComponent');
var ReactEventListener = require('ReactEventListener');
var ReactInjection = require('ReactInjection');
var ReactInstanceHandles = require('ReactInstanceHandles');
var ReactMount = require('ReactMount');
var ReactReconcileTransaction = require('ReactReconcileTransaction');
var SelectEventPlugin = require('SelectEventPlugin');
var ServerReactRootIndex = require('ServerReactRootIndex');
var SimpleEventPlugin = require('SimpleEventPlugin');
var SVGDOMPropertyConfig = require('SVGDOMPropertyConfig');
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(
ReactEventListener
);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin,
});
ReactInjection.NativeComponent.injectGenericComponentClass(
ReactDOMComponent
);
ReactInjection.NativeComponent.injectTextComponentClass(
ReactDOMTextComponent
);
ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
ReactInjection.Updates.injectReconcileTransaction(
ReactReconcileTransaction
);
ReactInjection.Updates.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
ReactInjection.RootIndex.injectCreateReactRootIndex(
ExecutionEnvironment.canUseDOM ?
ClientReactRootIndex.createReactRootIndex :
ServerReactRootIndex.createReactRootIndex
);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if (__DEV__) {
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
if ((/[?&]react_perf\b/).test(url)) {
var ReactDefaultPerf = require('ReactDefaultPerf');
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject,
};
|
packages/playground/stories/ValueIcon.story.js | appearhere/bloom | import React from 'react';
import { storiesOf } from '@storybook/react';
import {
ValueIcons,
Modifiers as m
} from '@appearhere/bloom';
const story = storiesOf('ValueIcons', module);
story
.add('ValueIcons.Handshake', () => <ValueIcons.Handshake className={m.titleLarge} />)
.add('ValueIcons.ThumbsUp', () => <ValueIcons.ThumbsUp className={m.titleLarge} />)
.add('ValueIcons.NoBull', () => <ValueIcons.NoBull className={m.titleLarge} />)
.add('ValueIcons.Scissors', () => <ValueIcons.Scissors className={m.titleLarge} />)
.add('ValueIcons.Open', () => <ValueIcons.Open className={m.titleLarge} />)
.add('ValueIcons.BoxingGlove', () => <ValueIcons.BoxingGlove className={m.titleLarge} />);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.