target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
definitions/npm/recompose_v0.24.x/flow_v0.53.x-/test_statics.js
gaborsar/flow-typed
/* eslint-disable no-unused-vars, no-unused-expressions, arrow-body-style */ /* @flow */ import React from "react"; import { compose, withProps, setStatic, setPropTypes, setDisplayName } from "recompose"; // import PropTypes from 'prop-types' import type { HOC } from "recompose"; const PropTypes = { string: () => {} }; type EnhancedCompProps = { eA: 1 }; const Comp = ({ eA }) => <div> {(eA: number)} { // $ExpectError eA nor any nor string (eA: string) } </div>; const enhacer: HOC<*, EnhancedCompProps> = compose( setStatic("hello", "world"), setPropTypes({ a: PropTypes.string }), setDisplayName("hello"), withProps(props => ({ eA: (props.eA: number), // $ExpectError eA nor any nor string eAErr: (props.eA: string) })), withProps(props => ({ // $ExpectError property not found err: props.iMNotExists })) ); // $ExpectError name is string setDisplayName(1); // $ExpectError propTypes is object setPropTypes(1); // $ExpectError name is string setStatic(1, "world"); const EnhancedComponent = enhacer(Comp);
ajax/libs/angular-ui-grid/3.0.1/ui-grid.js
BenjaminVanRyseghem/cdnjs
/*! * ui-grid - v3.0.1 - 2015-07-17 * Copyright (c) 2015 ; License: MIT */ (function () { 'use strict'; angular.module('ui.grid.i18n', []); angular.module('ui.grid', ['ui.grid.i18n']); })(); (function () { 'use strict'; angular.module('ui.grid').constant('uiGridConstants', { LOG_DEBUG_MESSAGES: true, LOG_WARN_MESSAGES: true, LOG_ERROR_MESSAGES: true, CUSTOM_FILTERS: /CUSTOM_FILTERS/g, COL_FIELD: /COL_FIELD/g, MODEL_COL_FIELD: /MODEL_COL_FIELD/g, TOOLTIP: /title=\"TOOLTIP\"/g, DISPLAY_CELL_TEMPLATE: /DISPLAY_CELL_TEMPLATE/g, TEMPLATE_REGEXP: /<.+>/, FUNC_REGEXP: /(\([^)]*\))?$/, DOT_REGEXP: /\./g, APOS_REGEXP: /'/g, BRACKET_REGEXP: /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/, COL_CLASS_PREFIX: 'ui-grid-col', events: { GRID_SCROLL: 'uiGridScroll', COLUMN_MENU_SHOWN: 'uiGridColMenuShown', ITEM_DRAGGING: 'uiGridItemDragStart', // For any item being dragged COLUMN_HEADER_CLICK: 'uiGridColumnHeaderClick' }, // copied from http://www.lsauer.com/2011/08/javascript-keymap-keycodes-in-json.html keymap: { TAB: 9, STRG: 17, CAPSLOCK: 20, CTRL: 17, CTRLRIGHT: 18, CTRLR: 18, SHIFT: 16, RETURN: 13, ENTER: 13, BACKSPACE: 8, BCKSP: 8, ALT: 18, ALTR: 17, ALTRIGHT: 17, SPACE: 32, WIN: 91, MAC: 91, FN: null, PG_UP: 33, PG_DOWN: 34, UP: 38, DOWN: 40, LEFT: 37, RIGHT: 39, ESC: 27, DEL: 46, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123 }, ASC: 'asc', DESC: 'desc', filter: { STARTS_WITH: 2, ENDS_WITH: 4, EXACT: 8, CONTAINS: 16, GREATER_THAN: 32, GREATER_THAN_OR_EQUAL: 64, LESS_THAN: 128, LESS_THAN_OR_EQUAL: 256, NOT_EQUAL: 512, SELECT: 'select', INPUT: 'input' }, aggregationTypes: { sum: 2, count: 4, avg: 8, min: 16, max: 32 }, // TODO(c0bra): Create full list of these somehow. NOTE: do any allow a space before or after them? CURRENCY_SYMBOLS: ['ƒ', '$', '£', '$', '¤', '¥', '៛', '₩', '₱', '฿', '₫'], scrollDirection: { UP: 'up', DOWN: 'down', LEFT: 'left', RIGHT: 'right', NONE: 'none' }, dataChange: { ALL: 'all', EDIT: 'edit', ROW: 'row', COLUMN: 'column', OPTIONS: 'options' }, scrollbars: { NEVER: 0, ALWAYS: 1 //WHEN_NEEDED: 2 } }); })(); angular.module('ui.grid').directive('uiGridCell', ['$compile', '$parse', 'gridUtil', 'uiGridConstants', function ($compile, $parse, gridUtil, uiGridConstants) { var uiGridCell = { priority: 0, scope: false, require: '?^uiGrid', compile: function() { return { pre: function($scope, $elm, $attrs, uiGridCtrl) { function compileTemplate() { var compiledElementFn = $scope.col.compiledElementFn; compiledElementFn($scope, function(clonedElement, scope) { $elm.append(clonedElement); }); } // If the grid controller is present, use it to get the compiled cell template function if (uiGridCtrl && $scope.col.compiledElementFn) { compileTemplate(); } // No controller, compile the element manually (for unit tests) else { if ( uiGridCtrl && !$scope.col.compiledElementFn ){ // gridUtil.logError('Render has been called before precompile. Please log a ui-grid issue'); $scope.col.getCompiledElementFn() .then(function (compiledElementFn) { compiledElementFn($scope, function(clonedElement, scope) { $elm.append(clonedElement); }); }); } else { var html = $scope.col.cellTemplate .replace(uiGridConstants.MODEL_COL_FIELD, 'row.entity.' + gridUtil.preEval($scope.col.field)) .replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var cellElement = $compile(html)($scope); $elm.append(cellElement); } } }, post: function($scope, $elm, $attrs, uiGridCtrl) { var initColClass = $scope.col.getColClass(false); $elm.addClass(initColClass); var classAdded; var updateClass = function( grid ){ var contents = $elm; if ( classAdded ){ contents.removeClass( classAdded ); classAdded = null; } if (angular.isFunction($scope.col.cellClass)) { classAdded = $scope.col.cellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex); } else { classAdded = $scope.col.cellClass; } contents.addClass(classAdded); }; if ($scope.col.cellClass) { updateClass(); } // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN, uiGridConstants.dataChange.EDIT]); // watch the col and row to see if they change - which would indicate that we've scrolled or sorted or otherwise // changed the row/col that this cell relates to, and we need to re-evaluate cell classes and maybe other things var cellChangeFunction = function( n, o ){ if ( n !== o ) { if ( classAdded || $scope.col.cellClass ){ updateClass(); } // See if the column's internal class has changed var newColClass = $scope.col.getColClass(false); if (newColClass !== initColClass) { $elm.removeClass(initColClass); $elm.addClass(newColClass); initColClass = newColClass; } } }; // TODO(c0bra): Turn this into a deep array watch /* shouldn't be needed any more given track by col.name var colWatchDereg = $scope.$watch( 'col', cellChangeFunction ); */ var rowWatchDereg = $scope.$watch( 'row', cellChangeFunction ); var deregisterFunction = function() { dataChangeDereg(); // colWatchDereg(); rowWatchDereg(); }; $scope.$on( '$destroy', deregisterFunction ); $elm.on( '$destroy', deregisterFunction ); } }; } }; return uiGridCell; }]); (function(){ angular.module('ui.grid') .service('uiGridColumnMenuService', [ 'i18nService', 'uiGridConstants', 'gridUtil', function ( i18nService, uiGridConstants, gridUtil ) { /** * @ngdoc service * @name ui.grid.service:uiGridColumnMenuService * * @description Services for working with column menus, factored out * to make the code easier to understand */ var service = { /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name initialize * @description Sets defaults, puts a reference to the $scope on * the uiGridController * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {controller} uiGridCtrl the uiGridController for the grid * we're on * */ initialize: function( $scope, uiGridCtrl ){ $scope.grid = uiGridCtrl.grid; // Store a reference to this link/controller in the main uiGrid controller // to allow showMenu later uiGridCtrl.columnMenuScope = $scope; // Save whether we're shown or not so the columns can check $scope.menuShown = false; }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name setColMenuItemWatch * @description Setup a watch on $scope.col.menuItems, and update * menuItems based on this. $scope.col needs to be set by the column * before calling the menu. * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {controller} uiGridCtrl the uiGridController for the grid * we're on * */ setColMenuItemWatch: function ( $scope ){ var deregFunction = $scope.$watch('col.menuItems', function (n, o) { if (typeof(n) !== 'undefined' && n && angular.isArray(n)) { n.forEach(function (item) { if (typeof(item.context) === 'undefined' || !item.context) { item.context = {}; } item.context.col = $scope.col; }); $scope.menuItems = $scope.defaultMenuItems.concat(n); } else { $scope.menuItems = $scope.defaultMenuItems; } }); $scope.$on( '$destroy', deregFunction ); }, /** * @ngdoc boolean * @name enableSorting * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) True by default. When enabled, this setting adds sort * widgets to the column header, allowing sorting of the data in the individual column. */ /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name sortable * @description determines whether this column is sortable * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ sortable: function( $scope ) { if ( $scope.grid.options.enableSorting && typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.enableSorting) { return true; } else { return false; } }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name isActiveSort * @description determines whether the requested sort direction is current active, to * allow highlighting in the menu * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {string} direction the direction that we'd have selected for us to be active * */ isActiveSort: function( $scope, direction ){ return (typeof($scope.col) !== 'undefined' && typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined' && $scope.col.sort.direction === direction); }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name suppressRemoveSort * @description determines whether we should suppress the removeSort option * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ suppressRemoveSort: function( $scope ) { if ($scope.col && $scope.col.suppressRemoveSort) { return true; } else { return false; } }, /** * @ngdoc boolean * @name enableHiding * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) True by default. When set to false, this setting prevents a user from hiding the column * using the column menu or the grid menu. */ /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name hideable * @description determines whether a column can be hidden, by checking the enableHiding columnDef option * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ hideable: function( $scope ) { if (typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.colDef && $scope.col.colDef.enableHiding === false ) { return false; } else { return true; } }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name getDefaultMenuItems * @description returns the default menu items for a column menu * @param {$scope} $scope the $scope from the uiGridColumnMenu * */ getDefaultMenuItems: function( $scope ){ return [ { title: i18nService.getSafeText('sort.ascending'), icon: 'ui-grid-icon-sort-alt-up', action: function($event) { $event.stopPropagation(); $scope.sortColumn($event, uiGridConstants.ASC); }, shown: function () { return service.sortable( $scope ); }, active: function() { return service.isActiveSort( $scope, uiGridConstants.ASC); } }, { title: i18nService.getSafeText('sort.descending'), icon: 'ui-grid-icon-sort-alt-down', action: function($event) { $event.stopPropagation(); $scope.sortColumn($event, uiGridConstants.DESC); }, shown: function() { return service.sortable( $scope ); }, active: function() { return service.isActiveSort( $scope, uiGridConstants.DESC); } }, { title: i18nService.getSafeText('sort.remove'), icon: 'ui-grid-icon-cancel', action: function ($event) { $event.stopPropagation(); $scope.unsortColumn(); }, shown: function() { return service.sortable( $scope ) && typeof($scope.col) !== 'undefined' && (typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined') && $scope.col.sort.direction !== null && !service.suppressRemoveSort( $scope ); } }, { title: i18nService.getSafeText('column.hide'), icon: 'ui-grid-icon-cancel', shown: function() { return service.hideable( $scope ); }, action: function ($event) { $event.stopPropagation(); $scope.hideColumn(); } } ]; }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name getColumnElementPosition * @description gets the position information needed to place the column * menu below the column header * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {GridCol} column the column we want to position below * @param {element} $columnElement the column element we want to position below * @returns {hash} containing left, top, offset, height, width * */ getColumnElementPosition: function( $scope, column, $columnElement ){ var positionData = {}; positionData.left = $columnElement[0].offsetLeft; positionData.top = $columnElement[0].offsetTop; positionData.parentLeft = $columnElement[0].offsetParent.offsetLeft; // Get the grid scrollLeft positionData.offset = 0; if (column.grid.options.offsetLeft) { positionData.offset = column.grid.options.offsetLeft; } positionData.height = gridUtil.elementHeight($columnElement, true); positionData.width = gridUtil.elementWidth($columnElement, true); return positionData; }, /** * @ngdoc method * @methodOf ui.grid.service:uiGridColumnMenuService * @name repositionMenu * @description Reposition the menu below the new column. If the menu has no child nodes * (i.e. it's not currently visible) then we guess it's width at 100, we'll be called again * later to fix it * @param {$scope} $scope the $scope from the uiGridColumnMenu * @param {GridCol} column the column we want to position below * @param {hash} positionData a hash containing left, top, offset, height, width * @param {element} $elm the column menu element that we want to reposition * @param {element} $columnElement the column element that we want to reposition underneath * */ repositionMenu: function( $scope, column, positionData, $elm, $columnElement ) { var menu = $elm[0].querySelectorAll('.ui-grid-menu'); var containerId = column.renderContainer ? column.renderContainer : 'body'; var renderContainer = column.grid.renderContainers[containerId]; // It's possible that the render container of the column we're attaching to is // offset from the grid (i.e. pinned containers), we need to get the difference in the offsetLeft // between the render container and the grid var renderContainerElm = gridUtil.closestElm($columnElement, '.ui-grid-render-container'); var renderContainerOffset = renderContainerElm.getBoundingClientRect().left - $scope.grid.element[0].getBoundingClientRect().left; var containerScrollLeft = renderContainerElm.querySelectorAll('.ui-grid-viewport')[0].scrollLeft; // default value the last width for _this_ column, otherwise last width for _any_ column, otherwise default to 170 var myWidth = column.lastMenuWidth ? column.lastMenuWidth : ( $scope.lastMenuWidth ? $scope.lastMenuWidth : 170); var paddingRight = column.lastMenuPaddingRight ? column.lastMenuPaddingRight : ( $scope.lastMenuPaddingRight ? $scope.lastMenuPaddingRight : 10); if ( menu.length !== 0 ){ var mid = menu[0].querySelectorAll('.ui-grid-menu-mid'); if ( mid.length !== 0 && !angular.element(mid).hasClass('ng-hide') ) { myWidth = gridUtil.elementWidth(menu, true); $scope.lastMenuWidth = myWidth; column.lastMenuWidth = myWidth; // TODO(c0bra): use padding-left/padding-right based on document direction (ltr/rtl), place menu on proper side // Get the column menu right padding paddingRight = parseInt(gridUtil.getStyles(angular.element(menu)[0])['paddingRight'], 10); $scope.lastMenuPaddingRight = paddingRight; column.lastMenuPaddingRight = paddingRight; } } var left = positionData.left + renderContainerOffset - containerScrollLeft + positionData.parentLeft + positionData.width - myWidth + paddingRight; if (left < positionData.offset){ left = positionData.offset; } $elm.css('left', left + 'px'); $elm.css('top', (positionData.top + positionData.height) + 'px'); } }; return service; }]) .directive('uiGridColumnMenu', ['$timeout', 'gridUtil', 'uiGridConstants', 'uiGridColumnMenuService', function ($timeout, gridUtil, uiGridConstants, uiGridColumnMenuService) { /** * @ngdoc directive * @name ui.grid.directive:uiGridColumnMenu * @description Provides the column menu framework, leverages uiGridMenu underneath * */ var uiGridColumnMenu = { priority: 0, scope: true, require: '?^uiGrid', templateUrl: 'ui-grid/uiGridColumnMenu', replace: true, link: function ($scope, $elm, $attrs, uiGridCtrl) { var self = this; uiGridColumnMenuService.initialize( $scope, uiGridCtrl ); $scope.defaultMenuItems = uiGridColumnMenuService.getDefaultMenuItems( $scope ); // Set the menu items for use with the column menu. The user can later add additional items via the watch $scope.menuItems = $scope.defaultMenuItems; uiGridColumnMenuService.setColMenuItemWatch( $scope ); /** * @ngdoc method * @methodOf ui.grid.directive:uiGridColumnMenu * @name showMenu * @description Shows the column menu. If the menu is already displayed it * calls the menu to ask it to hide (it will animate), then it repositions the menu * to the right place whilst hidden (it will make an assumption on menu width), * then it asks the menu to show (it will animate), then it repositions the menu again * once we can calculate it's size. * @param {GridCol} column the column we want to position below * @param {element} $columnElement the column element we want to position below */ $scope.showMenu = function(column, $columnElement, event) { // Swap to this column $scope.col = column; // Get the position information for the column element var colElementPosition = uiGridColumnMenuService.getColumnElementPosition( $scope, column, $columnElement ); if ($scope.menuShown) { // we want to hide, then reposition, then show, but we want to wait for animations // we set a variable, and then rely on the menu-hidden event to call the reposition and show $scope.colElement = $columnElement; $scope.colElementPosition = colElementPosition; $scope.hideThenShow = true; $scope.$broadcast('hide-menu', { originalEvent: event }); } else { self.shown = $scope.menuShown = true; uiGridColumnMenuService.repositionMenu( $scope, column, colElementPosition, $elm, $columnElement ); $scope.colElement = $columnElement; $scope.colElementPosition = colElementPosition; $scope.$broadcast('show-menu', { originalEvent: event }); } }; /** * @ngdoc method * @methodOf ui.grid.directive:uiGridColumnMenu * @name hideMenu * @description Hides the column menu. * @param {boolean} broadcastTrigger true if we were triggered by a broadcast * from the menu itself - in which case don't broadcast again as we'll get * an infinite loop */ $scope.hideMenu = function( broadcastTrigger ) { // delete $scope.col; $scope.menuShown = false; if ( !broadcastTrigger ){ $scope.$broadcast('hide-menu'); } }; $scope.$on('menu-hidden', function() { if ( $scope.hideThenShow ){ delete $scope.hideThenShow; uiGridColumnMenuService.repositionMenu( $scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement ); $scope.$broadcast('show-menu'); $scope.menuShown = true; } else { $scope.hideMenu( true ); } }); $scope.$on('menu-shown', function() { $timeout( function() { uiGridColumnMenuService.repositionMenu( $scope, $scope.col, $scope.colElementPosition, $elm, $scope.colElement ); delete $scope.colElementPosition; delete $scope.columnElement; }, 200); }); /* Column methods */ $scope.sortColumn = function (event, dir) { event.stopPropagation(); $scope.grid.sortColumn($scope.col, dir, true) .then(function () { $scope.grid.refresh(); $scope.hideMenu(); }); }; $scope.unsortColumn = function () { $scope.col.unsort(); $scope.grid.refresh(); $scope.hideMenu(); }; $scope.hideColumn = function () { $scope.col.colDef.visible = false; $scope.col.visible = false; $scope.grid.queueGridRefresh(); $scope.hideMenu(); $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); $scope.grid.api.core.raise.columnVisibilityChanged( $scope.col ); }; }, controller: ['$scope', function ($scope) { var self = this; $scope.$watch('menuItems', function (n, o) { self.menuItems = n; }); }] }; return uiGridColumnMenu; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridFilter', ['$compile', '$templateCache', function ($compile, $templateCache) { return { compile: function() { return { pre: function ($scope, $elm, $attrs, controllers) { $scope.col.updateFilters = function( filterable ){ $elm.children().remove(); if ( filterable ){ var template = $scope.col.filterHeaderTemplate; $elm.append($compile(template)($scope)); } }; $scope.$on( '$destroy', function() { delete $scope.col.updateFilters; }); } }; } }; }]); })(); (function () { 'use strict'; angular.module('ui.grid').directive('uiGridFooterCell', ['$timeout', 'gridUtil', 'uiGridConstants', '$compile', function ($timeout, gridUtil, uiGridConstants, $compile) { var uiGridFooterCell = { priority: 0, scope: { col: '=', row: '=', renderIndex: '=' }, replace: true, require: '^uiGrid', compile: function compile(tElement, tAttrs, transclude) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { var cellFooter = $compile($scope.col.footerCellTemplate)($scope); $elm.append(cellFooter); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { //$elm.addClass($scope.col.getColClass(false)); $scope.grid = uiGridCtrl.grid; var initColClass = $scope.col.getColClass(false); $elm.addClass(initColClass); // apply any footerCellClass var classAdded; var updateClass = function( grid ){ var contents = $elm; if ( classAdded ){ contents.removeClass( classAdded ); classAdded = null; } if (angular.isFunction($scope.col.footerCellClass)) { classAdded = $scope.col.footerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex); } else { classAdded = $scope.col.footerCellClass; } contents.addClass(classAdded); }; if ($scope.col.footerCellClass) { updateClass(); } $scope.col.updateAggregationValue(); // Watch for column changes so we can alter the col cell class properly /* shouldn't be needed any more, given track by col.name $scope.$watch('col', function (n, o) { if (n !== o) { // See if the column's internal class has changed var newColClass = $scope.col.getColClass(false); if (newColClass !== initColClass) { $elm.removeClass(initColClass); $elm.addClass(newColClass); initColClass = newColClass; } } }); */ // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateClass, [uiGridConstants.dataChange.COLUMN]); // listen for visible rows change and update aggregation values $scope.grid.api.core.on.rowsRendered( $scope, $scope.col.updateAggregationValue ); $scope.$on( '$destroy', dataChangeDereg ); } }; } }; return uiGridFooterCell; }]); })(); (function () { 'use strict'; angular.module('ui.grid').directive('uiGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($templateCache, $compile, uiGridConstants, gridUtil, $timeout) { return { restrict: 'EA', replace: true, // priority: 1000, require: ['^uiGrid', '^uiGridRenderContainer'], scope: true, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; $scope.grid = uiGridCtrl.grid; $scope.colContainer = containerCtrl.colContainer; containerCtrl.footer = $elm; var footerTemplate = $scope.grid.options.footerTemplate; gridUtil.getTemplate(footerTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.append(newElm); if (containerCtrl) { // Inject a reference to the footer viewport (if it exists) into the grid controller for use in the horizontal scroll handler below var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0]; if (footerViewport) { containerCtrl.footerViewport = footerViewport; } } }); }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; // gridUtil.logDebug('ui-grid-footer link'); var grid = uiGridCtrl.grid; // Don't animate footer cells gridUtil.disableAnimations($elm); containerCtrl.footer = $elm; var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0]; if (footerViewport) { containerCtrl.footerViewport = footerViewport; } } }; } }; }]); })(); (function () { 'use strict'; angular.module('ui.grid').directive('uiGridGridFooter', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($templateCache, $compile, uiGridConstants, gridUtil, $timeout) { return { restrict: 'EA', replace: true, // priority: 1000, require: '^uiGrid', scope: true, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { $scope.grid = uiGridCtrl.grid; var footerTemplate = $scope.grid.options.gridFooterTemplate; gridUtil.getTemplate(footerTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.append(newElm); }); }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridGroupPanel', ["$compile", "uiGridConstants", "gridUtil", function($compile, uiGridConstants, gridUtil) { var defaultTemplate = 'ui-grid/ui-grid-group-panel'; return { restrict: 'EA', replace: true, require: '?^uiGrid', scope: false, compile: function($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { var groupPanelTemplate = $scope.grid.options.groupPanelTemplate || defaultTemplate; gridUtil.getTemplate(groupPanelTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.append(newElm); }); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { $elm.bind('$destroy', function() { // scrollUnbinder(); }); } }; } }; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridHeaderCell', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', 'ScrollEvent', function ($compile, $timeout, $window, $document, gridUtil, uiGridConstants, ScrollEvent) { // Do stuff after mouse has been down this many ms on the header cell var mousedownTimeout = 500; var changeModeTimeout = 500; // length of time between a touch event and a mouse event being recognised again, and vice versa var uiGridHeaderCell = { priority: 0, scope: { col: '=', row: '=', renderIndex: '=' }, require: ['?^uiGrid', '^uiGridRenderContainer'], replace: true, compile: function() { return { pre: function ($scope, $elm, $attrs) { var cellHeader = $compile($scope.col.headerCellTemplate)($scope); $elm.append(cellHeader); }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var renderContainerCtrl = controllers[1]; $scope.grid = uiGridCtrl.grid; $scope.renderContainer = uiGridCtrl.grid.renderContainers[renderContainerCtrl.containerId]; var initColClass = $scope.col.getColClass(false); $elm.addClass(initColClass); // Hide the menu by default $scope.menuShown = false; // Put asc and desc sort directions in scope $scope.asc = uiGridConstants.ASC; $scope.desc = uiGridConstants.DESC; // Store a reference to menu element var $colMenu = angular.element( $elm[0].querySelectorAll('.ui-grid-header-cell-menu') ); var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') ); // apply any headerCellClass var classAdded; var previousMouseX; // filter watchers var filterDeregisters = []; /* * Our basic approach here for event handlers is that we listen for a down event (mousedown or touchstart). * Once we have a down event, we need to work out whether we have a click, a drag, or a * hold. A click would sort the grid (if sortable). A drag would be used by moveable, so * we ignore it. A hold would open the menu. * * So, on down event, we put in place handlers for move and up events, and a timer. If the * timer expires before we see a move or up, then we have a long press and hence a column menu open. * If the up happens before the timer, then we have a click, and we sort if the column is sortable. * If a move happens before the timer, then we are doing column move, so we do nothing, the moveable feature * will handle it. * * To deal with touch enabled devices that also have mice, we only create our handlers when * we get the down event, and we create the corresponding handlers - if we're touchstart then * we get touchmove and touchend, if we're mousedown then we get mousemove and mouseup. * * We also suppress the click action whilst this is happening - otherwise after the mouseup there * will be a click event and that can cause the column menu to close * */ $scope.downFn = function( event ){ event.stopPropagation(); if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) { event = event.originalEvent; } // Don't show the menu if it's not the left button if (event.button && event.button !== 0) { return; } previousMouseX = event.pageX; $scope.mousedownStartTime = (new Date()).getTime(); $scope.mousedownTimeout = $timeout(function() { }, mousedownTimeout); $scope.mousedownTimeout.then(function () { if ( $scope.colMenu ) { uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm, event); } }); uiGridCtrl.fireEvent(uiGridConstants.events.COLUMN_HEADER_CLICK, {event: event, columnName: $scope.col.colDef.name}); $scope.offAllEvents(); if ( event.type === 'touchstart'){ $document.on('touchend', $scope.upFn); $document.on('touchmove', $scope.moveFn); } else if ( event.type === 'mousedown' ){ $document.on('mouseup', $scope.upFn); $document.on('mousemove', $scope.moveFn); } }; $scope.upFn = function( event ){ event.stopPropagation(); $timeout.cancel($scope.mousedownTimeout); $scope.offAllEvents(); $scope.onDownEvents(event.type); var mousedownEndTime = (new Date()).getTime(); var mousedownTime = mousedownEndTime - $scope.mousedownStartTime; if (mousedownTime > mousedownTimeout) { // long click, handled above with mousedown } else { // short click if ( $scope.sortable ){ $scope.handleClick(event); } } }; $scope.moveFn = function( event ){ // Chrome is known to fire some bogus move events. var changeValue = event.pageX - previousMouseX; if ( changeValue === 0 ){ return; } // we're a move, so do nothing and leave for column move (if enabled) to take over $timeout.cancel($scope.mousedownTimeout); $scope.offAllEvents(); $scope.onDownEvents(event.type); }; $scope.clickFn = function ( event ){ event.stopPropagation(); $contentsElm.off('click', $scope.clickFn); }; $scope.offAllEvents = function(){ $contentsElm.off('touchstart', $scope.downFn); $contentsElm.off('mousedown', $scope.downFn); $document.off('touchend', $scope.upFn); $document.off('mouseup', $scope.upFn); $document.off('touchmove', $scope.moveFn); $document.off('mousemove', $scope.moveFn); $contentsElm.off('click', $scope.clickFn); }; $scope.onDownEvents = function( type ){ // If there is a previous event, then wait a while before // activating the other mode - i.e. if the last event was a touch event then // don't enable mouse events for a wee while (500ms or so) // Avoids problems with devices that emulate mouse events when you have touch events switch (type){ case 'touchmove': case 'touchend': $contentsElm.on('click', $scope.clickFn); $contentsElm.on('touchstart', $scope.downFn); $timeout(function(){ $contentsElm.on('mousedown', $scope.downFn); }, changeModeTimeout); break; case 'mousemove': case 'mouseup': $contentsElm.on('click', $scope.clickFn); $contentsElm.on('mousedown', $scope.downFn); $timeout(function(){ $contentsElm.on('touchstart', $scope.downFn); }, changeModeTimeout); break; default: $contentsElm.on('click', $scope.clickFn); $contentsElm.on('touchstart', $scope.downFn); $contentsElm.on('mousedown', $scope.downFn); } }; var updateHeaderOptions = function( grid ){ var contents = $elm; if ( classAdded ){ contents.removeClass( classAdded ); classAdded = null; } if (angular.isFunction($scope.col.headerCellClass)) { classAdded = $scope.col.headerCellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex); } else { classAdded = $scope.col.headerCellClass; } contents.addClass(classAdded); var rightMostContainer = $scope.grid.renderContainers['right'] ? $scope.grid.renderContainers['right'] : $scope.grid.renderContainers['body']; $scope.isLastCol = ( $scope.col === rightMostContainer.visibleColumnCache[ rightMostContainer.visibleColumnCache.length - 1 ] ); // Figure out whether this column is sortable or not if (uiGridCtrl.grid.options.enableSorting && $scope.col.enableSorting) { $scope.sortable = true; } else { $scope.sortable = false; } // Figure out whether this column is filterable or not var oldFilterable = $scope.filterable; if (uiGridCtrl.grid.options.enableFiltering && $scope.col.enableFiltering) { $scope.filterable = true; } else { $scope.filterable = false; } if ( oldFilterable !== $scope.filterable){ if ( typeof($scope.col.updateFilters) !== 'undefined' ){ $scope.col.updateFilters($scope.filterable); } // if column is filterable add a filter watcher if ($scope.filterable) { $scope.col.filters.forEach( function(filter, i) { filterDeregisters.push($scope.$watch('col.filters[' + i + '].term', function(n, o) { if (n !== o) { uiGridCtrl.grid.api.core.raise.filterChanged(); uiGridCtrl.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); uiGridCtrl.grid.queueGridRefresh(); } })); }); $scope.$on('$destroy', function() { filterDeregisters.forEach( function(filterDeregister) { filterDeregister(); }); }); } else { filterDeregisters.forEach( function(filterDeregister) { filterDeregister(); }); } } // figure out whether we support column menus if ($scope.col.grid.options && $scope.col.grid.options.enableColumnMenus !== false && $scope.col.colDef && $scope.col.colDef.enableColumnMenu !== false){ $scope.colMenu = true; } else { $scope.colMenu = false; } /** * @ngdoc property * @name enableColumnMenu * @propertyOf ui.grid.class:GridOptions.columnDef * @description if column menus are enabled, controls the column menus for this specific * column (i.e. if gridOptions.enableColumnMenus, then you can control column menus * using this option. If gridOptions.enableColumnMenus === false then you get no column * menus irrespective of the value of this option ). Defaults to true. * */ /** * @ngdoc property * @name enableColumnMenus * @propertyOf ui.grid.class:GridOptions.columnDef * @description Override for column menus everywhere - if set to false then you get no * column menus. Defaults to true. * */ $scope.offAllEvents(); if ($scope.sortable || $scope.colMenu) { $scope.onDownEvents(); $scope.$on('$destroy', function () { $scope.offAllEvents(); }); } }; /* $scope.$watch('col', function (n, o) { if (n !== o) { // See if the column's internal class has changed var newColClass = $scope.col.getColClass(false); if (newColClass !== initColClass) { $elm.removeClass(initColClass); $elm.addClass(newColClass); initColClass = newColClass; } } }); */ updateHeaderOptions(); // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateHeaderOptions, [uiGridConstants.dataChange.COLUMN]); $scope.$on( '$destroy', dataChangeDereg ); $scope.handleClick = function(event) { // If the shift key is being held down, add this column to the sort var add = false; if (event.shiftKey) { add = true; } // Sort this column then rebuild the grid's rows uiGridCtrl.grid.sortColumn($scope.col, add) .then(function () { if (uiGridCtrl.columnMenuScope) { uiGridCtrl.columnMenuScope.hideMenu(); } uiGridCtrl.grid.refresh(); }); }; $scope.toggleMenu = function(event) { event.stopPropagation(); // If the menu is already showing... if (uiGridCtrl.columnMenuScope.menuShown) { // ... and we're the column the menu is on... if (uiGridCtrl.columnMenuScope.col === $scope.col) { // ... hide it uiGridCtrl.columnMenuScope.hideMenu(); } // ... and we're NOT the column the menu is on else { // ... move the menu to our column uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm); } } // If the menu is NOT showing else { // ... show it on our column uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm); } }; } }; } }; return uiGridHeaderCell; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridHeader', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', 'ScrollEvent', function($templateCache, $compile, uiGridConstants, gridUtil, $timeout, ScrollEvent) { var defaultTemplate = 'ui-grid/ui-grid-header'; var emptyTemplate = 'ui-grid/ui-grid-no-header'; return { restrict: 'EA', // templateUrl: 'ui-grid/ui-grid-header', replace: true, // priority: 1000, require: ['^uiGrid', '^uiGridRenderContainer'], scope: true, compile: function($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; $scope.grid = uiGridCtrl.grid; $scope.colContainer = containerCtrl.colContainer; updateHeaderReferences(); var headerTemplate; if (!$scope.grid.options.showHeader) { headerTemplate = emptyTemplate; } else { headerTemplate = ($scope.grid.options.headerTemplate) ? $scope.grid.options.headerTemplate : defaultTemplate; } gridUtil.getTemplate(headerTemplate) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.replaceWith(newElm); // And update $elm to be the new element $elm = newElm; updateHeaderReferences(); if (containerCtrl) { // Inject a reference to the header viewport (if it exists) into the grid controller for use in the horizontal scroll handler below var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0]; if (headerViewport) { containerCtrl.headerViewport = headerViewport; angular.element(headerViewport).on('scroll', scrollHandler); $scope.$on('$destroy', function () { angular.element(headerViewport).off('scroll', scrollHandler); }); } } $scope.grid.queueRefresh(); }); function updateHeaderReferences() { containerCtrl.header = containerCtrl.colContainer.header = $elm; var headerCanvases = $elm[0].getElementsByClassName('ui-grid-header-canvas'); if (headerCanvases.length > 0) { containerCtrl.headerCanvas = containerCtrl.colContainer.headerCanvas = headerCanvases[0]; } else { containerCtrl.headerCanvas = null; } } function scrollHandler(evt) { if (uiGridCtrl.grid.isScrollingHorizontally) { return; } var newScrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.headerViewport, uiGridCtrl.grid); var horizScrollPercentage = containerCtrl.colContainer.scrollHorizontal(newScrollLeft); var scrollEvent = new ScrollEvent(uiGridCtrl.grid, null, containerCtrl.colContainer, ScrollEvent.Sources.ViewPortScroll); scrollEvent.newScrollLeft = newScrollLeft; if ( horizScrollPercentage > -1 ){ scrollEvent.x = { percentage: horizScrollPercentage }; } uiGridCtrl.grid.scrollContainers(null, scrollEvent); } }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; // gridUtil.logDebug('ui-grid-header link'); var grid = uiGridCtrl.grid; // Don't animate header cells gridUtil.disableAnimations($elm); function updateColumnWidths() { // this styleBuilder always runs after the renderContainer, so we can rely on the column widths // already being populated correctly var columnCache = containerCtrl.colContainer.visibleColumnCache; // Build the CSS // uiGridCtrl.grid.columns.forEach(function (column) { var ret = ''; var canvasWidth = 0; columnCache.forEach(function (column) { ret = ret + column.getColClassDefinition(); canvasWidth += column.drawnWidth; }); containerCtrl.colContainer.canvasWidth = canvasWidth; // Return the styles back to buildStyles which pops them into the `customStyles` scope variable return ret; } containerCtrl.header = $elm; var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0]; if (headerViewport) { containerCtrl.headerViewport = headerViewport; } //todo: remove this if by injecting gridCtrl into unit tests if (uiGridCtrl) { uiGridCtrl.grid.registerStyleComputation({ priority: 15, func: updateColumnWidths }); } } }; } }; }]); })(); (function(){ angular.module('ui.grid') .service('uiGridGridMenuService', [ 'gridUtil', 'i18nService', 'uiGridConstants', function( gridUtil, i18nService, uiGridConstants ) { /** * @ngdoc service * @name ui.grid.gridMenuService * * @description Methods for working with the grid menu */ var service = { /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name initialize * @description Sets up the gridMenu. Most importantly, sets our * scope onto the grid object as grid.gridMenuScope, allowing us * to operate when passed only the grid. Second most importantly, * we register the 'addToGridMenu' and 'removeFromGridMenu' methods * on the core api. * @param {$scope} $scope the scope of this gridMenu * @param {Grid} grid the grid to which this gridMenu is associated */ initialize: function( $scope, grid ){ grid.gridMenuScope = $scope; $scope.grid = grid; $scope.registeredMenuItems = []; // not certain this is needed, but would be bad to create a memory leak $scope.$on('$destroy', function() { if ( $scope.grid && $scope.grid.gridMenuScope ){ $scope.grid.gridMenuScope = null; } if ( $scope.grid ){ $scope.grid = null; } if ( $scope.registeredMenuItems ){ $scope.registeredMenuItems = null; } }); $scope.registeredMenuItems = []; /** * @ngdoc function * @name addToGridMenu * @methodOf ui.grid.core.api:PublicApi * @description add items to the grid menu. Used by features * to add their menu items if they are enabled, can also be used by * end users to add menu items. This method has the advantage of allowing * remove again, which can simplify management of which items are included * in the menu when. (Noting that in most cases the shown and active functions * provide a better way to handle visibility of menu items) * @param {Grid} grid the grid on which we are acting * @param {array} items menu items in the format as described in the tutorial, with * the added note that if you want to use remove you must also specify an `id` field, * which is provided when you want to remove an item. The id should be unique. * */ grid.api.registerMethod( 'core', 'addToGridMenu', service.addToGridMenu ); /** * @ngdoc function * @name removeFromGridMenu * @methodOf ui.grid.core.api:PublicApi * @description Remove an item from the grid menu based on a provided id. Assumes * that the id is unique, removes only the last instance of that id. Does nothing if * the specified id is not found * @param {Grid} grid the grid on which we are acting * @param {string} id the id we'd like to remove from the menu * */ grid.api.registerMethod( 'core', 'removeFromGridMenu', service.removeFromGridMenu ); }, /** * @ngdoc function * @name addToGridMenu * @propertyOf ui.grid.gridMenuService * @description add items to the grid menu. Used by features * to add their menu items if they are enabled, can also be used by * end users to add menu items. This method has the advantage of allowing * remove again, which can simplify management of which items are included * in the menu when. (Noting that in most cases the shown and active functions * provide a better way to handle visibility of menu items) * @param {Grid} grid the grid on which we are acting * @param {array} items menu items in the format as described in the tutorial, with * the added note that if you want to use remove you must also specify an `id` field, * which is provided when you want to remove an item. The id should be unique. * */ addToGridMenu: function( grid, menuItems ) { if ( !angular.isArray( menuItems ) ) { gridUtil.logError( 'addToGridMenu: menuItems must be an array, and is not, not adding any items'); } else { if ( grid.gridMenuScope ){ grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems ? grid.gridMenuScope.registeredMenuItems : []; grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems.concat( menuItems ); } else { gridUtil.logError( 'Asked to addToGridMenu, but gridMenuScope not present. Timing issue? Please log issue with ui-grid'); } } }, /** * @ngdoc function * @name removeFromGridMenu * @methodOf ui.grid.gridMenuService * @description Remove an item from the grid menu based on a provided id. Assumes * that the id is unique, removes only the last instance of that id. Does nothing if * the specified id is not found. If there is no gridMenuScope or registeredMenuItems * then do nothing silently - the desired result is those menu items not be present and they * aren't. * @param {Grid} grid the grid on which we are acting * @param {string} id the id we'd like to remove from the menu * */ removeFromGridMenu: function( grid, id ){ var foundIndex = -1; if ( grid && grid.gridMenuScope ){ grid.gridMenuScope.registeredMenuItems.forEach( function( value, index ) { if ( value.id === id ){ if (foundIndex > -1) { gridUtil.logError( 'removeFromGridMenu: found multiple items with the same id, removing only the last' ); } else { foundIndex = index; } } }); } if ( foundIndex > -1 ){ grid.gridMenuScope.registeredMenuItems.splice( foundIndex, 1 ); } }, /** * @ngdoc array * @name gridMenuCustomItems * @propertyOf ui.grid.class:GridOptions * @description (optional) An array of menu items that should be added to * the gridMenu. Follow the format documented in the tutorial for column * menu customisation. The context provided to the action function will * include context.grid. An alternative if working with dynamic menus is to use the * provided api - core.addToGridMenu and core.removeFromGridMenu, which handles * some of the management of items for you. * */ /** * @ngdoc boolean * @name gridMenuShowHideColumns * @propertyOf ui.grid.class:GridOptions * @description true by default, whether the grid menu should allow hide/show * of columns * */ /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name getMenuItems * @description Decides the menu items to show in the menu. This is a * combination of: * * - the default menu items that are always included, * - any menu items that have been provided through the addMenuItem api. These * are typically added by features within the grid * - any menu items included in grid.options.gridMenuCustomItems. These can be * changed dynamically, as they're always recalculated whenever we show the * menu * @param {$scope} $scope the scope of this gridMenu, from which we can find all * the information that we need * @returns {array} an array of menu items that can be shown */ getMenuItems: function( $scope ) { var menuItems = [ // this is where we add any menu items we want to always include ]; if ( $scope.grid.options.gridMenuCustomItems ){ if ( !angular.isArray( $scope.grid.options.gridMenuCustomItems ) ){ gridUtil.logError( 'gridOptions.gridMenuCustomItems must be an array, and is not'); } else { menuItems = menuItems.concat( $scope.grid.options.gridMenuCustomItems ); } } menuItems = menuItems.concat( $scope.registeredMenuItems ); if ( $scope.grid.options.gridMenuShowHideColumns !== false ){ menuItems = menuItems.concat( service.showHideColumns( $scope ) ); } menuItems.sort(function(a, b){ return a.order - b.order; }); return menuItems; }, /** * @ngdoc array * @name gridMenuTitleFilter * @propertyOf ui.grid.class:GridOptions * @description (optional) A function that takes a title string * (usually the col.displayName), and converts it into a display value. The function * must return either a string or a promise. * * Used for internationalization of the grid menu column names - for angular-translate * you can pass $translate as the function, for i18nService you can pass getSafeText as the * function * @example * <pre> * gridOptions = { * gridMenuTitleFilter: $translate * } * </pre> */ /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name showHideColumns * @description Adds two menu items for each of the columns in columnDefs. One * menu item for hide, one menu item for show. Each is visible when appropriate * (show when column is not visible, hide when column is visible). Each toggles * the visible property on the columnDef using toggleColumnVisibility * @param {$scope} $scope of a gridMenu, which contains a reference to the grid */ showHideColumns: function( $scope ){ var showHideColumns = []; if ( !$scope.grid.options.columnDefs || $scope.grid.options.columnDefs.length === 0 || $scope.grid.columns.length === 0 ) { return showHideColumns; } // add header for columns showHideColumns.push({ title: i18nService.getSafeText('gridMenu.columns'), order: 300 }); $scope.grid.options.gridMenuTitleFilter = $scope.grid.options.gridMenuTitleFilter ? $scope.grid.options.gridMenuTitleFilter : function( title ) { return title; }; $scope.grid.options.columnDefs.forEach( function( colDef, index ){ if ( colDef.enableHiding !== false ){ // add hide menu item - shows an OK icon as we only show when column is already visible var menuItem = { icon: 'ui-grid-icon-ok', action: function($event) { $event.stopPropagation(); service.toggleColumnVisibility( this.context.gridCol ); }, shown: function() { return this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined; }, context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) }, leaveOpen: true, order: 301 + index * 2 }; service.setMenuItemTitle( menuItem, colDef, $scope.grid ); showHideColumns.push( menuItem ); // add show menu item - shows no icon as we only show when column is invisible menuItem = { icon: 'ui-grid-icon-cancel', action: function($event) { $event.stopPropagation(); service.toggleColumnVisibility( this.context.gridCol ); }, shown: function() { return !(this.context.gridCol.colDef.visible === true || this.context.gridCol.colDef.visible === undefined); }, context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) }, leaveOpen: true, order: 301 + index * 2 + 1 }; service.setMenuItemTitle( menuItem, colDef, $scope.grid ); showHideColumns.push( menuItem ); } }); return showHideColumns; }, /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name setMenuItemTitle * @description Handles the response from gridMenuTitleFilter, adding it directly to the menu * item if it returns a string, otherwise waiting for the promise to resolve or reject then * putting the result into the title * @param {object} menuItem the menuItem we want to put the title on * @param {object} colDef the colDef from which we can get displayName, name or field * @param {Grid} grid the grid, from which we can get the options.gridMenuTitleFilter * */ setMenuItemTitle: function( menuItem, colDef, grid ){ var title = grid.options.gridMenuTitleFilter( colDef.displayName || gridUtil.readableColumnName(colDef.name) || colDef.field ); if ( typeof(title) === 'string' ){ menuItem.title = title; } else if ( title.then ){ // must be a promise menuItem.title = ""; title.then( function( successValue ) { menuItem.title = successValue; }, function( errorValue ) { menuItem.title = errorValue; }); } else { gridUtil.logError('Expected gridMenuTitleFilter to return a string or a promise, it has returned neither, bad config'); menuItem.title = 'badconfig'; } }, /** * @ngdoc method * @methodOf ui.grid.gridMenuService * @name toggleColumnVisibility * @description Toggles the visibility of an individual column. Expects to be * provided a context that has on it a gridColumn, which is the column that * we'll operate upon. We change the visibility, and refresh the grid as appropriate * @param {GridCol} gridCol the column that we want to toggle * */ toggleColumnVisibility: function( gridCol ) { gridCol.colDef.visible = !( gridCol.colDef.visible === true || gridCol.colDef.visible === undefined ); gridCol.grid.refresh(); gridCol.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); gridCol.grid.api.core.raise.columnVisibilityChanged( gridCol ); } }; return service; }]) .directive('uiGridMenuButton', ['gridUtil', 'uiGridConstants', 'uiGridGridMenuService', function (gridUtil, uiGridConstants, uiGridGridMenuService) { return { priority: 0, scope: true, require: ['?^uiGrid'], templateUrl: 'ui-grid/ui-grid-menu-button', replace: true, link: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; uiGridGridMenuService.initialize($scope, uiGridCtrl.grid); $scope.shown = false; $scope.toggleMenu = function () { if ( $scope.shown ){ $scope.$broadcast('hide-menu'); $scope.shown = false; } else { $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope ); $scope.$broadcast('show-menu'); $scope.shown = true; } }; $scope.$on('menu-hidden', function() { $scope.shown = false; }); } }; }]); })(); (function(){ /** * @ngdoc directive * @name ui.grid.directive:uiGridMenu * @element style * @restrict A * * @description * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', function ($scope) { }]); </script> <div ng-controller="MainCtrl"> <div ui-grid-menu shown="true" ></div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angular.module('ui.grid') .directive('uiGridMenu', ['$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', function ($compile, $timeout, $window, $document, gridUtil, uiGridConstants) { var uiGridMenu = { priority: 0, scope: { // shown: '&', menuItems: '=', autoHide: '=?' }, require: '?^uiGrid', templateUrl: 'ui-grid/uiGridMenu', replace: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var self = this; var menuMid; var $animate; // *** Show/Hide functions ****** self.showMenu = $scope.showMenu = function(event, args) { if ( !$scope.shown ){ /* * In order to animate cleanly we remove the ng-if, wait a digest cycle, then * animate the removal of the ng-hide. We can't successfully (so far as I can tell) * animate removal of the ng-if, as the menu items aren't there yet. And we don't want * to rely on ng-show only, as that leaves elements in the DOM that are needlessly evaluated * on scroll events. * * Note when testing animation that animations don't run on the tutorials. When debugging it looks * like they do, but angular has a default $animate provider that is just a stub, and that's what's * being called. ALso don't be fooled by the fact that your browser has actually loaded the * angular-translate.js, it's not using it. You need to test animations in an external application. */ $scope.shown = true; $timeout( function() { $scope.shownMid = true; $scope.$emit('menu-shown'); }); } else if ( !$scope.shownMid ) { // we're probably doing a hide then show, so we don't need to wait for ng-if $scope.shownMid = true; $scope.$emit('menu-shown'); } var docEventType = 'click'; if (args && args.originalEvent && args.originalEvent.type && args.originalEvent.type === 'touchstart') { docEventType = args.originalEvent.type; } // Turn off an existing document click handler angular.element(document).off('click touchstart', applyHideMenu); // Turn on the document click handler, but in a timeout so it doesn't apply to THIS click if there is one $timeout(function() { angular.element(document).on(docEventType, applyHideMenu); }); }; self.hideMenu = $scope.hideMenu = function(event, args) { if ( $scope.shown ){ /* * In order to animate cleanly we animate the addition of ng-hide, then use a $timeout to * set the ng-if (shown = false) after the animation runs. In theory we can cascade off the * callback on the addClass method, but it is very unreliable with unit tests for no discernable reason. * * The user may have clicked on the menu again whilst * we're waiting, so we check that the mid isn't shown before applying the ng-if. */ $scope.shownMid = false; $timeout( function() { if ( !$scope.shownMid ){ $scope.shown = false; $scope.$emit('menu-hidden'); } }, 200); } angular.element(document).off('click touchstart', applyHideMenu); }; $scope.$on('hide-menu', function (event, args) { $scope.hideMenu(event, args); }); $scope.$on('show-menu', function (event, args) { $scope.showMenu(event, args); }); // *** Auto hide when click elsewhere ****** var applyHideMenu = function(){ if ($scope.shown) { $scope.$apply(function () { $scope.hideMenu(); }); } }; if (typeof($scope.autoHide) === 'undefined' || $scope.autoHide === undefined) { $scope.autoHide = true; } if ($scope.autoHide) { angular.element($window).on('resize', applyHideMenu); } $scope.$on('$destroy', function () { angular.element(document).off('click touchstart', applyHideMenu); }); $scope.$on('$destroy', function() { angular.element($window).off('resize', applyHideMenu); }); if (uiGridCtrl) { $scope.$on('$destroy', uiGridCtrl.grid.api.core.on.scrollBegin($scope, applyHideMenu )); } $scope.$on('$destroy', $scope.$on(uiGridConstants.events.ITEM_DRAGGING, applyHideMenu )); }, controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) { var self = this; }] }; return uiGridMenu; }]) .directive('uiGridMenuItem', ['gridUtil', '$compile', 'i18nService', function (gridUtil, $compile, i18nService) { var uiGridMenuItem = { priority: 0, scope: { name: '=', active: '=', action: '=', icon: '=', shown: '=', context: '=', templateUrl: '=', leaveOpen: '=' }, require: ['?^uiGrid', '^uiGridMenu'], templateUrl: 'ui-grid/uiGridMenuItem', replace: true, compile: function($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], uiGridMenuCtrl = controllers[1]; if ($scope.templateUrl) { gridUtil.getTemplate($scope.templateUrl) .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); $elm.replaceWith(newElm); }); } }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], uiGridMenuCtrl = controllers[1]; // TODO(c0bra): validate that shown and active are functions if they're defined. An exception is already thrown above this though // if (typeof($scope.shown) !== 'undefined' && $scope.shown && typeof($scope.shown) !== 'function') { // throw new TypeError("$scope.shown is defined but not a function"); // } if (typeof($scope.shown) === 'undefined' || $scope.shown === null) { $scope.shown = function() { return true; }; } $scope.itemShown = function () { var context = {}; if ($scope.context) { context.context = $scope.context; } if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) { context.grid = uiGridCtrl.grid; } return $scope.shown.call(context); }; $scope.itemAction = function($event,title) { // gridUtil.logDebug('itemAction'); $event.stopPropagation(); if (typeof($scope.action) === 'function') { var context = {}; if ($scope.context) { context.context = $scope.context; } // Add the grid to the function call context if the uiGrid controller is present if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) { context.grid = uiGridCtrl.grid; } $scope.action.call(context, $event, title); if ( !$scope.leaveOpen ){ $scope.$emit('hide-menu'); } } }; $scope.i18n = i18nService.get(); } }; } }; return uiGridMenuItem; }]); })(); (function(){ 'use strict'; /** * @ngdoc overview * @name ui.grid.directive:uiGridOneBind * @summary A group of directives that provide a one time bind to a dom element. * @description A group of directives that provide a one time bind to a dom element. * As one time bindings are not supported in Angular 1.2.* this directive provdes this capability. * This is done to reduce the number of watchers on the dom. * <br/> * <h2>Short Example ({@link ui.grid.directive:uiGridOneBindSrc ui-grid-one-bind-src})</h2> * <pre> <div ng-init="imageName = 'myImageDir.jpg'"> <img ui-grid-one-bind-src="imageName"></img> </div> </pre> * Will become: * <pre> <div ng-init="imageName = 'myImageDir.jpg'"> <img ui-grid-one-bind-src="imageName" src="myImageDir.jpg"></img> </div> </pre> </br> <h2>Short Example ({@link ui.grid.directive:uiGridOneBindText ui-grid-one-bind-text})</h2> * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-text="text"></div> </pre> * Will become: * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-text="text">Add this text</div> </pre> </br> * <b>Note:</b> This behavior is slightly different for the {@link ui.grid.directive:uiGridOneBindIdGrid uiGridOneBindIdGrid} * and {@link ui.grid.directive:uiGridOneBindAriaLabelledbyGrid uiGridOneBindAriaLabelledbyGrid} directives. * */ //https://github.com/joshkurz/Black-Belt-AngularJS-Directives/blob/master/directives/Optimization/oneBind.js var oneBinders = angular.module('ui.grid'); angular.forEach([ /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindSrc * @memberof ui.grid.directive:uiGridOneBind * @element img * @restrict A * @param {String} uiGridOneBindSrc The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the src dom tag. * */ {tag: 'Src', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindText * @element div * @restrict A * @param {String} uiGridOneBindText The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the text dom tag. */ {tag: 'Text', method: 'text'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindHref * @element div * @restrict A * @param {String} uiGridOneBindHref The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the href dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Href', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindClass * @element div * @restrict A * @param {String} uiGridOneBindClass The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @param {Object} uiGridOneBindClass The object that you want to bind. At least one of the values in the object must be something other than null or undefined for the watcher to be removed. * this is to prevent the watcher from being removed before the scope is initialized. * @param {Array} uiGridOneBindClass An array of classes to bind to this element. * @description One time binding for the class dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Class', method: 'addClass'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindHtml * @element div * @restrict A * @param {String} uiGridOneBindHtml The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the html method on a dom element. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Html', method: 'html'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAlt * @element div * @restrict A * @param {String} uiGridOneBindAlt The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the alt dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Alt', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindStyle * @element div * @restrict A * @param {String} uiGridOneBindStyle The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the style dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Style', method: 'css'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindValue * @element div * @restrict A * @param {String} uiGridOneBindValue The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Value', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindId * @element div * @restrict A * @param {String} uiGridOneBindId The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Id', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindIdGrid * @element div * @restrict A * @param {String} uiGridOneBindIdGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the id dom tag. * <h1>Important Note!</h1> * If the id tag passed as a parameter does <b>not</b> contain the grid id as a substring * then the directive will search the scope and the parent controller (if it is a uiGridController) for the grid.id value. * If this value is found then it is appended to the begining of the id tag. If the grid is not found then the directive throws an error. * This is done in order to ensure uniqueness of id tags across the grid. * This is to prevent two grids in the same document having duplicate id tags. */ {tag: 'Id', directiveName:'IdGrid', method: 'attr', appendGridId: true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindTitle * @element div * @restrict A * @param {String} uiGridOneBindTitle The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the title dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. */ {tag: 'Title', method: 'attr'}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaLabel * @element div * @restrict A * @param {String} uiGridOneBindAriaLabel The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-label dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. *<br/> * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text"></div> </pre> * Will become: * <pre> <div ng-init="text='Add this text'" ui-grid-one-bind-aria-label="text" aria-label="Add this text"></div> </pre> */ {tag: 'Label', method: 'attr', aria:true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaLabelledby * @element div * @restrict A * @param {String} uiGridOneBindAriaLabelledby The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. *<br/> * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId"></div> </pre> * Will become: * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby="anId" aria-labelledby="gridID32"></div> </pre> */ {tag: 'Labelledby', method: 'attr', aria:true}, /** * @ngdoc directive * @name ui.grid.directive:uiGridOneBindAriaLabelledbyGrid * @element div * @restrict A * @param {String} uiGridOneBindAriaLabelledbyGrid The angular string you want to bind. Does not support interpolation. Don't use <code>{{scopeElt}}</code> instead use <code>scopeElt</code>. * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}. * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the * grid id to each one. *<br/> * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId"></div> </pre> * Will become ([grid.id] will be replaced by the actual grid id): * <pre> <div ng-init="anId = 'gridID32'" ui-grid-one-bind-aria-labelledby-grid="anId" aria-labelledby-Grid="[grid.id]-gridID32"></div> </pre> */ {tag: 'Labelledby', directiveName:'LabelledbyGrid', appendGridId:true, method: 'attr', aria:true}], function(v){ var baseDirectiveName = 'uiGridOneBind'; //If it is an aria tag then append the aria label seperately //This is done because the aria tags are formatted aria-* and the directive name can't have a '-' character in it. //If the diretiveName has to be overridden then it does so here. This is because the tag being modified and the directive sometimes don't match up. var directiveName = (v.aria ? baseDirectiveName + 'Aria' : baseDirectiveName) + (v.directiveName ? v.directiveName : v.tag); oneBinders.directive(directiveName, ['gridUtil', function(gridUtil){ return { restrict: 'A', require: ['?uiGrid','?^uiGrid'], link: function(scope, iElement, iAttrs, controllers){ /* Appends the grid id to the beginnig of the value. */ var appendGridId = function(val){ var grid; //Get an instance of the grid if its available //If its available in the scope then we don't need to try to find it elsewhere if (scope.grid) { grid = scope.grid; } //Another possible location to try to find the grid else if (scope.col && scope.col.grid){ grid = scope.col.grid; } //Last ditch effort: Search through the provided controllers. else if (!controllers.some( //Go through the controllers till one has the element we need function(controller){ if (controller && controller.grid) { grid = controller.grid; return true; //We've found the grid } })){ //We tried our best to find it for you gridUtil.logError("["+directiveName+"] A valid grid could not be found to bind id. Are you using this directive " + "within the correct scope? Trying to generate id: [gridID]-" + val); throw new Error("No valid grid could be found"); } if (grid){ var idRegex = new RegExp(grid.id.toString()); //If the grid id hasn't been appended already in the template declaration if (!idRegex.test(val)){ val = grid.id.toString() + '-' + val; } } return val; }; // The watch returns a function to remove itself. var rmWatcher = scope.$watch(iAttrs[directiveName], function(newV){ if (newV){ //If we are trying to add an id element then we also apply the grid id if it isn't already there if (v.appendGridId) { var newIdString = null; //Append the id to all of the new ids. angular.forEach( newV.split(' '), function(s){ newIdString = (newIdString ? (newIdString + ' ') : '') + appendGridId(s); }); newV = newIdString; } // Append this newValue to the dom element. switch (v.method) { case 'attr': //The attr method takes two paraams the tag and the value if (v.aria) { //If it is an aria element then append the aria prefix iElement[v.method]('aria-' + v.tag.toLowerCase(),newV); } else { iElement[v.method](v.tag.toLowerCase(),newV); } break; case 'addClass': //Pulled from https://github.com/Pasvaz/bindonce/blob/master/bindonce.js if (angular.isObject(newV) && !angular.isArray(newV)) { var results = []; var nonNullFound = false; //We don't want to remove the binding unless the key is actually defined angular.forEach(newV, function (value, index) { if (value !== null && typeof(value) !== "undefined"){ nonNullFound = true; //A non null value for a key was found so the object must have been initialized if (value) {results.push(index);} } }); //A non null value for a key wasn't found so assume that the scope values haven't been fully initialized if (!nonNullFound){ return; // If not initialized then the watcher should not be removed yet. } newV = results; } if (newV) { iElement.addClass(angular.isArray(newV) ? newV.join(' ') : newV); } else { return; } break; default: iElement[v.method](newV); break; } //Removes the watcher on itself after the bind rmWatcher(); } // True ensures that equality is determined using angular.equals instead of === }, true); //End rm watchers } //End compile function }; //End directive return } // End directive function ]); //End directive }); // End angular foreach })(); (function () { 'use strict'; var module = angular.module('ui.grid'); module.directive('uiGridRenderContainer', ['$timeout', '$document', 'uiGridConstants', 'gridUtil', 'ScrollEvent', function($timeout, $document, uiGridConstants, gridUtil, ScrollEvent) { return { replace: true, transclude: true, templateUrl: 'ui-grid/uiGridRenderContainer', require: ['^uiGrid', 'uiGridRenderContainer'], scope: { containerId: '=', rowContainerName: '=', colContainerName: '=', bindScrollHorizontal: '=', bindScrollVertical: '=', enableVerticalScrollbar: '=', enableHorizontalScrollbar: '=' }, controller: 'uiGridRenderContainer as RenderContainer', compile: function () { return { pre: function prelink($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; var grid = $scope.grid = uiGridCtrl.grid; // Verify that the render container for this element exists if (!$scope.rowContainerName) { throw "No row render container name specified"; } if (!$scope.colContainerName) { throw "No column render container name specified"; } if (!grid.renderContainers[$scope.rowContainerName]) { throw "Row render container '" + $scope.rowContainerName + "' is not registered."; } if (!grid.renderContainers[$scope.colContainerName]) { throw "Column render container '" + $scope.colContainerName + "' is not registered."; } var rowContainer = $scope.rowContainer = grid.renderContainers[$scope.rowContainerName]; var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName]; containerCtrl.containerId = $scope.containerId; containerCtrl.rowContainer = rowContainer; containerCtrl.colContainer = colContainer; }, post: function postlink($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; var grid = uiGridCtrl.grid; var rowContainer = containerCtrl.rowContainer; var colContainer = containerCtrl.colContainer; var scrollTop = null; var scrollLeft = null; var renderContainer = grid.renderContainers[$scope.containerId]; // Put the container name on this element as a class $elm.addClass('ui-grid-render-container-' + $scope.containerId); // Scroll the render container viewport when the mousewheel is used gridUtil.on.mousewheel($elm, function (event) { var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.RenderContainerMouseWheel); if (event.deltaY !== 0) { var scrollYAmount = event.deltaY * -1 * event.deltaFactor; scrollTop = containerCtrl.viewport[0].scrollTop; // Get the scroll percentage scrollEvent.verticalScrollLength = rowContainer.getVerticalScrollLength(); var scrollYPercentage = (scrollTop + scrollYAmount) / scrollEvent.verticalScrollLength; // If we should be scrolled 100%, make sure the scrollTop matches the maximum scroll length // Viewports that have "overflow: hidden" don't let the mousewheel scroll all the way to the bottom without this check if (scrollYPercentage >= 1 && scrollTop < scrollEvent.verticalScrollLength) { containerCtrl.viewport[0].scrollTop = scrollEvent.verticalScrollLength; } // Keep scrollPercentage within the range 0-1. if (scrollYPercentage < 0) { scrollYPercentage = 0; } else if (scrollYPercentage > 1) { scrollYPercentage = 1; } scrollEvent.y = { percentage: scrollYPercentage, pixels: scrollYAmount }; } if (event.deltaX !== 0) { var scrollXAmount = event.deltaX * event.deltaFactor; // Get the scroll percentage scrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.viewport, grid); scrollEvent.horizontalScrollLength = (colContainer.getCanvasWidth() - colContainer.getViewportWidth()); var scrollXPercentage = (scrollLeft + scrollXAmount) / scrollEvent.horizontalScrollLength; // Keep scrollPercentage within the range 0-1. if (scrollXPercentage < 0) { scrollXPercentage = 0; } else if (scrollXPercentage > 1) { scrollXPercentage = 1; } scrollEvent.x = { percentage: scrollXPercentage, pixels: scrollXAmount }; } // Let the parent container scroll if the grid is already at the top/bottom if ((event.deltaY !== 0 && (scrollEvent.atTop(scrollTop) || scrollEvent.atBottom(scrollTop))) || (event.deltaX !== 0 && (scrollEvent.atLeft(scrollLeft) || scrollEvent.atRight(scrollLeft)))) { //parent controller scrolls } else { event.preventDefault(); scrollEvent.fireThrottledScrollingEvent('', scrollEvent); } }); $elm.bind('$destroy', function() { $elm.unbind('keydown'); ['touchstart', 'touchmove', 'touchend','keydown', 'wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) { $elm.unbind(eventName); }); }); // TODO(c0bra): Handle resizing the inner canvas based on the number of elements function update() { var ret = ''; var canvasWidth = colContainer.canvasWidth; var viewportWidth = colContainer.getViewportWidth(); var canvasHeight = rowContainer.getCanvasHeight(); //add additional height for scrollbar on left and right container //if ($scope.containerId !== 'body') { // canvasHeight -= grid.scrollbarHeight; //} var viewportHeight = rowContainer.getViewportHeight(); //shorten the height to make room for a scrollbar placeholder if (colContainer.needsHScrollbarPlaceholder()) { viewportHeight -= grid.scrollbarHeight; } var headerViewportWidth, footerViewportWidth; headerViewportWidth = footerViewportWidth = colContainer.getHeaderViewportWidth(); // Set canvas dimensions ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-canvas { width: ' + canvasWidth + 'px; height: ' + canvasHeight + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }'; if (renderContainer.explicitHeaderCanvasHeight) { ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: ' + renderContainer.explicitHeaderCanvasHeight + 'px; }'; } else { ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: inherit; }'; } ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-viewport { width: ' + viewportWidth + 'px; height: ' + viewportHeight + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-viewport { width: ' + headerViewportWidth + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }'; ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-footer-viewport { width: ' + footerViewportWidth + 'px; }'; return ret; } uiGridCtrl.grid.registerStyleComputation({ priority: 6, func: update }); } }; } }; }]); module.controller('uiGridRenderContainer', ['$scope', 'gridUtil', function ($scope, gridUtil) { }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridRow', ['gridUtil', function(gridUtil) { return { replace: true, // priority: 2001, // templateUrl: 'ui-grid/ui-grid-row', require: ['^uiGrid', '^uiGridRenderContainer'], scope: { row: '=uiGridRow', //rowRenderIndex is added to scope to give the true visual index of the row to any directives that need it rowRenderIndex: '=' }, compile: function() { return { pre: function($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; var grid = uiGridCtrl.grid; $scope.grid = uiGridCtrl.grid; $scope.colContainer = containerCtrl.colContainer; // Function for attaching the template to this scope var clonedElement, cloneScope; function compileTemplate() { $scope.row.getRowTemplateFn.then(function (compiledElementFn) { // var compiledElementFn = $scope.row.compiledElementFn; // Create a new scope for the contents of this row, so we can destroy it later if need be var newScope = $scope.$new(); compiledElementFn(newScope, function (newElm, scope) { // If we already have a cloned element, we need to remove it and destroy its scope if (clonedElement) { clonedElement.remove(); cloneScope.$destroy(); } // Empty the row and append the new element $elm.empty().append(newElm); // Save the new cloned element and scope clonedElement = newElm; cloneScope = newScope; }); }); } // Initially attach the compiled template to this scope compileTemplate(); // If the row's compiled element function changes, we need to replace this element's contents with the new compiled template $scope.$watch('row.getRowTemplateFn', function (newFunc, oldFunc) { if (newFunc !== oldFunc) { compileTemplate(); } }); }, post: function($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function(){ // 'use strict'; /** * @ngdoc directive * @name ui.grid.directive:uiGridStyle * @element style * @restrict A * * @description * Allows us to interpolate expressions in `<style>` elements. Angular doesn't do this by default as it can/will/might? break in IE8. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.myStyle = '.blah { border: 1px solid }'; }]); </script> <div ng-controller="MainCtrl"> <style ui-grid-style>{{ myStyle }}</style> <span class="blah">I am in a box.</span> </div> </doc:source> <doc:scenario> it('should apply the right class to the element', function () { element(by.css('.blah')).getCssValue('border-top-width') .then(function(c) { expect(c).toContain('1px'); }); }); </doc:scenario> </doc:example> */ angular.module('ui.grid').directive('uiGridStyle', ['gridUtil', '$interpolate', function(gridUtil, $interpolate) { return { // restrict: 'A', // priority: 1000, // require: '?^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { // gridUtil.logDebug('ui-grid-style link'); // if (uiGridCtrl === undefined) { // gridUtil.logWarn('[ui-grid-style link] uiGridCtrl is undefined!'); // } var interpolateFn = $interpolate($elm.text(), true); if (interpolateFn) { $scope.$watch(interpolateFn, function(value) { $elm.text(value); }); } // uiGridCtrl.recalcRowStyles = function() { // var offset = (scope.options.offsetTop || 0) - (scope.options.excessRows * scope.options.rowHeight); // var rowHeight = scope.options.rowHeight; // var ret = ''; // var rowStyleCount = uiGridCtrl.minRowsToRender() + (scope.options.excessRows * 2); // for (var i = 1; i <= rowStyleCount; i++) { // ret = ret + ' .grid' + scope.gridId + ' .ui-grid-row:nth-child(' + i + ') { top: ' + offset + 'px; }'; // offset = offset + rowHeight; // } // scope.rowStyles = ret; // }; // uiGridCtrl.styleComputions.push(uiGridCtrl.recalcRowStyles); } }; }]); })(); (function(){ 'use strict'; angular.module('ui.grid').directive('uiGridViewport', ['gridUtil','ScrollEvent','uiGridConstants', '$log', function(gridUtil, ScrollEvent, uiGridConstants, $log) { return { replace: true, scope: {}, controllerAs: 'Viewport', templateUrl: 'ui-grid/uiGridViewport', require: ['^uiGrid', '^uiGridRenderContainer'], link: function($scope, $elm, $attrs, controllers) { // gridUtil.logDebug('viewport post-link'); var uiGridCtrl = controllers[0]; var containerCtrl = controllers[1]; $scope.containerCtrl = containerCtrl; var rowContainer = containerCtrl.rowContainer; var colContainer = containerCtrl.colContainer; var grid = uiGridCtrl.grid; $scope.grid = uiGridCtrl.grid; // Put the containers in scope so we can get rows and columns from them $scope.rowContainer = containerCtrl.rowContainer; $scope.colContainer = containerCtrl.colContainer; // Register this viewport with its container containerCtrl.viewport = $elm; $elm.on('scroll', scrollHandler); var ignoreScroll = false; function scrollHandler(evt) { //Leaving in this commented code in case it can someday be used //It does improve performance, but because the horizontal scroll is normalized, // using this code will lead to the column header getting slightly out of line with columns // //if (ignoreScroll && (grid.isScrollingHorizontally || grid.isScrollingHorizontally)) { // //don't ask for scrollTop if we just set it // ignoreScroll = false; // return; //} //ignoreScroll = true; var newScrollTop = $elm[0].scrollTop; var newScrollLeft = gridUtil.normalizeScrollLeft($elm, grid); var vertScrollPercentage = rowContainer.scrollVertical(newScrollTop); var horizScrollPercentage = colContainer.scrollHorizontal(newScrollLeft); var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.ViewPortScroll); scrollEvent.newScrollLeft = newScrollLeft; scrollEvent.newScrollTop = newScrollTop; if ( horizScrollPercentage > -1 ){ scrollEvent.x = { percentage: horizScrollPercentage }; } if ( vertScrollPercentage > -1 ){ scrollEvent.y = { percentage: vertScrollPercentage }; } grid.scrollContainers($scope.$parent.containerId, scrollEvent); } if ($scope.$parent.bindScrollVertical) { grid.addVerticalScrollSync($scope.$parent.containerId, syncVerticalScroll); } if ($scope.$parent.bindScrollHorizontal) { grid.addHorizontalScrollSync($scope.$parent.containerId, syncHorizontalScroll); grid.addHorizontalScrollSync($scope.$parent.containerId + 'header', syncHorizontalHeader); grid.addHorizontalScrollSync($scope.$parent.containerId + 'footer', syncHorizontalFooter); } function syncVerticalScroll(scrollEvent){ containerCtrl.prevScrollArgs = scrollEvent; var newScrollTop = scrollEvent.getNewScrollTop(rowContainer,containerCtrl.viewport); $elm[0].scrollTop = newScrollTop; } function syncHorizontalScroll(scrollEvent){ containerCtrl.prevScrollArgs = scrollEvent; var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); $elm[0].scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); } function syncHorizontalHeader(scrollEvent){ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); if (containerCtrl.headerViewport) { containerCtrl.headerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); } } function syncHorizontalFooter(scrollEvent){ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); if (containerCtrl.footerViewport) { containerCtrl.footerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); } } }, controller: ['$scope', function ($scope) { this.rowStyle = function (index) { var rowContainer = $scope.rowContainer; var colContainer = $scope.colContainer; var styles = {}; if (index === 0 && rowContainer.currentTopRow !== 0) { // The row offset-top is just the height of the rows above the current top-most row, which are no longer rendered var hiddenRowWidth = (rowContainer.currentTopRow) * rowContainer.grid.options.rowHeight; // return { 'margin-top': hiddenRowWidth + 'px' }; styles['margin-top'] = hiddenRowWidth + 'px'; } if (colContainer.currentFirstColumn !== 0) { if (colContainer.grid.isRTL()) { styles['margin-right'] = colContainer.columnOffset + 'px'; } else { styles['margin-left'] = colContainer.columnOffset + 'px'; } } return styles; }; }] }; } ]); })(); (function() { angular.module('ui.grid') .directive('uiGridVisible', function uiGridVisibleAction() { return function ($scope, $elm, $attr) { $scope.$watch($attr.uiGridVisible, function (visible) { // $elm.css('visibility', visible ? 'visible' : 'hidden'); $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible'); }); }; }); })(); (function () { 'use strict'; angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', 'gridUtil', '$q', 'uiGridConstants', '$templateCache', 'gridClassFactory', '$timeout', '$parse', '$compile', function ($scope, $elm, $attrs, gridUtil, $q, uiGridConstants, $templateCache, gridClassFactory, $timeout, $parse, $compile) { // gridUtil.logDebug('ui-grid controller'); var self = this; self.grid = gridClassFactory.createGrid($scope.uiGrid); //assign $scope.$parent if appScope not already assigned self.grid.appScope = self.grid.appScope || $scope.$parent; $elm.addClass('grid' + self.grid.id); self.grid.rtl = gridUtil.getStyles($elm[0])['direction'] === 'rtl'; // angular.extend(self.grid.options, ); //all properties of grid are available on scope $scope.grid = self.grid; if ($attrs.uiGridColumns) { $attrs.$observe('uiGridColumns', function(value) { self.grid.options.columnDefs = value; self.grid.buildColumns() .then(function(){ self.grid.preCompileCellTemplates(); self.grid.refreshCanvas(true); }); }); } // if fastWatch is set we watch only the length and the reference, not every individual object var deregFunctions = []; if (self.grid.options.fastWatch) { self.uiGrid = $scope.uiGrid; if (angular.isString($scope.uiGrid.data)) { deregFunctions.push( $scope.$parent.$watch($scope.uiGrid.data, dataWatchFunction) ); deregFunctions.push( $scope.$parent.$watch(function() { if ( self.grid.appScope[$scope.uiGrid.data] ){ return self.grid.appScope[$scope.uiGrid.data].length; } else { return undefined; } }, dataWatchFunction) ); } else { deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data; }, dataWatchFunction) ); deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data.length; }, dataWatchFunction) ); } deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) ); deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs.length; }, columnDefsWatchFunction) ); } else { if (angular.isString($scope.uiGrid.data)) { deregFunctions.push( $scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction) ); } else { deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction) ); } deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) ); } function columnDefsWatchFunction(n, o) { if (n && n !== o) { self.grid.options.columnDefs = n; self.grid.buildColumns({ orderByColumnDefs: true }) .then(function(){ self.grid.preCompileCellTemplates(); self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.COLUMN); }); } } function dataWatchFunction(newData) { // gridUtil.logDebug('dataWatch fired'); var promises = []; if ( self.grid.options.fastWatch ){ if (angular.isString($scope.uiGrid.data)) { newData = self.grid.appScope[$scope.uiGrid.data]; } else { newData = $scope.uiGrid.data; } } if (newData) { if ( // If we have no columns (i.e. columns length is either 0 or equal to the number of row header columns, which don't count because they're created automatically) self.grid.columns.length === (self.grid.rowHeaderColumns ? self.grid.rowHeaderColumns.length : 0) && // ... and we don't have a ui-grid-columns attribute, which would define columns for us !$attrs.uiGridColumns && // ... and we have no pre-defined columns self.grid.options.columnDefs.length === 0 && // ... but we DO have data newData.length > 0 ) { // ... then build the column definitions from the data that we have self.grid.buildColumnDefsFromData(newData); } // If we either have some columns defined, or some data defined if (self.grid.options.columnDefs.length > 0 || newData.length > 0) { // Build the column set, then pre-compile the column cell templates promises.push(self.grid.buildColumns() .then(function() { self.grid.preCompileCellTemplates(); })); } $q.all(promises).then(function() { self.grid.modifyRows(newData) .then(function () { // if (self.viewport) { self.grid.redrawInPlace(true); // } $scope.$evalAsync(function() { self.grid.refreshCanvas(true); self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.ROW); }); }); }); } } var styleWatchDereg = $scope.$watch(function () { return self.grid.styleComputations; }, function() { self.grid.refreshCanvas(true); }); $scope.$on('$destroy', function() { deregFunctions.forEach( function( deregFn ){ deregFn(); }); styleWatchDereg(); }); self.fireEvent = function(eventName, args) { // Add the grid to the event arguments if it's not there if (typeof(args) === 'undefined' || args === undefined) { args = {}; } if (typeof(args.grid) === 'undefined' || args.grid === undefined) { args.grid = self.grid; } $scope.$broadcast(eventName, args); }; self.innerCompile = function innerCompile(elm) { $compile(elm)($scope); }; }]); /** * @ngdoc directive * @name ui.grid.directive:uiGrid * @element div * @restrict EA * @param {Object} uiGrid Options for the grid to use * * @description Create a very basic grid. * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data }"></div> </div> </file> </example> */ angular.module('ui.grid').directive('uiGrid', uiGridDirective); uiGridDirective.$inject = ['$compile', '$templateCache', '$timeout', '$window', 'gridUtil', 'uiGridConstants']; function uiGridDirective($compile, $templateCache, $timeout, $window, gridUtil, uiGridConstants) { return { templateUrl: 'ui-grid/ui-grid', scope: { uiGrid: '=' }, replace: true, transclude: true, controller: 'uiGridController', compile: function () { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { var grid = uiGridCtrl.grid; // Initialize scrollbars (TODO: move to controller??) uiGridCtrl.scrollbars = []; grid.element = $elm; // See if the grid has a rendered width, if not, wait a bit and try again var sizeCheckInterval = 100; // ms var maxSizeChecks = 20; // 2 seconds total var sizeChecks = 0; // Setup (event listeners) the grid setup(); // And initialize it init(); // Mark rendering complete so API events can happen grid.renderingComplete(); // If the grid doesn't have size currently, wait for a bit to see if it gets size checkSize(); /*-- Methods --*/ function checkSize() { // If the grid has no width and we haven't checked more than <maxSizeChecks> times, check again in <sizeCheckInterval> milliseconds if ($elm[0].offsetWidth <= 0 && sizeChecks < maxSizeChecks) { setTimeout(checkSize, sizeCheckInterval); sizeChecks++; } else { $timeout(init); } } // Setup event listeners and watchers function setup() { // Bind to window resize events angular.element($window).on('resize', gridResize); // Unbind from window resize events when the grid is destroyed $elm.on('$destroy', function () { angular.element($window).off('resize', gridResize); }); // If we add a left container after render, we need to watch and react $scope.$watch(function () { return grid.hasLeftContainer();}, function (newValue, oldValue) { if (newValue === oldValue) { return; } grid.refreshCanvas(true); }); // If we add a right container after render, we need to watch and react $scope.$watch(function () { return grid.hasRightContainer();}, function (newValue, oldValue) { if (newValue === oldValue) { return; } grid.refreshCanvas(true); }); } // Initialize the directive function init() { grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm); // Default canvasWidth to the grid width, in case we don't get any column definitions to calculate it from grid.canvasWidth = uiGridCtrl.grid.gridWidth; grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm); // If the grid isn't tall enough to fit a single row, it's kind of useless. Resize it to fit a minimum number of rows if (grid.gridHeight < grid.options.rowHeight && grid.options.enableMinHeightCheck) { autoAdjustHeight(); } // Run initial canvas refresh grid.refreshCanvas(true); } // Set the grid's height ourselves in the case that its height would be unusably small function autoAdjustHeight() { // Figure out the new height var contentHeight = grid.options.minRowsToShow * grid.options.rowHeight; var headerHeight = grid.options.showHeader ? grid.options.headerRowHeight : 0; var footerHeight = grid.calcFooterHeight(); var scrollbarHeight = 0; if (grid.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) { scrollbarHeight = gridUtil.getScrollbarWidth(); } var maxNumberOfFilters = 0; // Calculates the maximum number of filters in the columns angular.forEach(grid.options.columnDefs, function(col) { if (col.hasOwnProperty('filter')) { if (maxNumberOfFilters < 1) { maxNumberOfFilters = 1; } } else if (col.hasOwnProperty('filters')) { if (maxNumberOfFilters < col.filters.length) { maxNumberOfFilters = col.filters.length; } } }); var filterHeight = maxNumberOfFilters * headerHeight; var newHeight = headerHeight + contentHeight + footerHeight + scrollbarHeight + filterHeight; $elm.css('height', newHeight + 'px'); grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm); } // Resize the grid on window resize events function gridResize($event) { grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm); grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm); grid.refreshCanvas(true); } } }; } }; } })(); (function(){ 'use strict'; // TODO: rename this file to ui-grid-pinned-container.js angular.module('ui.grid').directive('uiGridPinnedContainer', ['gridUtil', function (gridUtil) { return { restrict: 'EA', replace: true, template: '<div class="ui-grid-pinned-container"><div ui-grid-render-container container-id="side" row-container-name="\'body\'" col-container-name="side" bind-scroll-vertical="true" class="{{ side }} ui-grid-render-container-{{ side }}"></div></div>', scope: { side: '=uiGridPinnedContainer' }, require: '^uiGrid', compile: function compile() { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { // gridUtil.logDebug('ui-grid-pinned-container ' + $scope.side + ' link'); var grid = uiGridCtrl.grid; var myWidth = 0; $elm.addClass('ui-grid-pinned-container-' + $scope.side); // Monkey-patch the viewport width function if ($scope.side === 'left' || $scope.side === 'right') { grid.renderContainers[$scope.side].getViewportWidth = monkeyPatchedGetViewportWidth; } function monkeyPatchedGetViewportWidth() { /*jshint validthis: true */ var self = this; var viewportWidth = 0; self.visibleColumnCache.forEach(function (column) { viewportWidth += column.drawnWidth; }); var adjustment = self.getViewportAdjustment(); viewportWidth = viewportWidth + adjustment.width; return viewportWidth; } function updateContainerWidth() { if ($scope.side === 'left' || $scope.side === 'right') { var cols = grid.renderContainers[$scope.side].visibleColumnCache; var width = 0; for (var i = 0; i < cols.length; i++) { var col = cols[i]; width += col.drawnWidth || col.width || 0; } return width; } } function updateContainerDimensions() { var ret = ''; // Column containers if ($scope.side === 'left' || $scope.side === 'right') { myWidth = updateContainerWidth(); // gridUtil.logDebug('myWidth', myWidth); // TODO(c0bra): Subtract sum of col widths from grid viewport width and update it $elm.attr('style', null); // var myHeight = grid.renderContainers.body.getViewportHeight(); // + grid.horizontalScrollbarHeight; ret += '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.side + ', .grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.side + ' .ui-grid-render-container-' + $scope.side + ' .ui-grid-viewport { width: ' + myWidth + 'px; } '; } return ret; } grid.renderContainers.body.registerViewportAdjuster(function (adjustment) { myWidth = updateContainerWidth(); // Subtract our own width adjustment.width -= myWidth; adjustment.side = $scope.side; return adjustment; }); // Register style computation to adjust for columns in `side`'s render container grid.registerStyleComputation({ priority: 15, func: updateContainerDimensions }); } }; } }; }]); })(); (function(){ angular.module('ui.grid') .factory('Grid', ['$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout','ScrollEvent', function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout, ScrollEvent) { /** * @ngdoc object * @name ui.grid.core.api:PublicApi * @description Public Api for the core grid features * */ /** * @ngdoc function * @name ui.grid.class:Grid * @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in * this prototype. One instance of Grid is created per Grid directive instance. * @param {object} options Object map of options to pass into the grid. An 'id' property is expected. */ var Grid = function Grid(options) { var self = this; // Get the id out of the options, then remove it if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) { if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) { throw new Error("Grid id '" + options.id + '" is invalid. It must follow CSS selector syntax rules.'); } } else { throw new Error('No ID provided. An ID must be given when creating a grid.'); } self.id = options.id; delete options.id; // Get default options self.options = GridOptions.initialize( options ); /** * @ngdoc object * @name appScope * @propertyOf ui.grid.class:Grid * @description reference to the application scope (the parent scope of the ui-grid element). Assigned in ui-grid controller * <br/> * use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference */ self.appScope = self.options.appScopeProvider; self.headerHeight = self.options.headerRowHeight; /** * @ngdoc object * @name footerHeight * @propertyOf ui.grid.class:Grid * @description returns the total footer height gridFooter + columnFooter */ self.footerHeight = self.calcFooterHeight(); /** * @ngdoc object * @name columnFooterHeight * @propertyOf ui.grid.class:Grid * @description returns the total column footer height */ self.columnFooterHeight = self.calcColumnFooterHeight(); self.rtl = false; self.gridHeight = 0; self.gridWidth = 0; self.columnBuilders = []; self.rowBuilders = []; self.rowsProcessors = []; self.columnsProcessors = []; self.styleComputations = []; self.viewportAdjusters = []; self.rowHeaderColumns = []; self.dataChangeCallbacks = {}; self.verticalScrollSyncCallBackFns = {}; self.horizontalScrollSyncCallBackFns = {}; // self.visibleRowCache = []; // Set of 'render' containers for self grid, which can render sets of rows self.renderContainers = {}; // Create a self.renderContainers.body = new GridRenderContainer('body', self); self.cellValueGetterCache = {}; // Cached function to use with custom row templates self.getRowTemplateFn = null; //representation of the rows on the grid. //these are wrapped references to the actual data rows (options.data) self.rows = []; //represents the columns on the grid self.columns = []; /** * @ngdoc boolean * @name isScrollingVertically * @propertyOf ui.grid.class:Grid * @description set to true when Grid is scrolling vertically. Set to false via debounced method */ self.isScrollingVertically = false; /** * @ngdoc boolean * @name isScrollingHorizontally * @propertyOf ui.grid.class:Grid * @description set to true when Grid is scrolling horizontally. Set to false via debounced method */ self.isScrollingHorizontally = false; /** * @ngdoc property * @name scrollDirection * @propertyOf ui.grid.class:Grid * @description set one of the uiGridConstants.scrollDirection values (UP, DOWN, LEFT, RIGHT, NONE), which tells * us which direction we are scrolling. Set to NONE via debounced method */ self.scrollDirection = uiGridConstants.scrollDirection.NONE; //if true, grid will not respond to any scroll events self.disableScrolling = false; function vertical (scrollEvent) { self.isScrollingVertically = false; self.api.core.raise.scrollEnd(scrollEvent); self.scrollDirection = uiGridConstants.scrollDirection.NONE; } var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce); var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0); function horizontal (scrollEvent) { self.isScrollingHorizontally = false; self.api.core.raise.scrollEnd(scrollEvent); self.scrollDirection = uiGridConstants.scrollDirection.NONE; } var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce); var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0); /** * @ngdoc function * @name flagScrollingVertically * @methodOf ui.grid.class:Grid * @description sets isScrollingVertically to true and sets it to false in a debounced function */ self.flagScrollingVertically = function(scrollEvent) { if (!self.isScrollingVertically && !self.isScrollingHorizontally) { self.api.core.raise.scrollBegin(scrollEvent); } self.isScrollingVertically = true; if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) { debouncedVerticalMinDelay(scrollEvent); } else { debouncedVertical(scrollEvent); } }; /** * @ngdoc function * @name flagScrollingHorizontally * @methodOf ui.grid.class:Grid * @description sets isScrollingHorizontally to true and sets it to false in a debounced function */ self.flagScrollingHorizontally = function(scrollEvent) { if (!self.isScrollingVertically && !self.isScrollingHorizontally) { self.api.core.raise.scrollBegin(scrollEvent); } self.isScrollingHorizontally = true; if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) { debouncedHorizontalMinDelay(scrollEvent); } else { debouncedHorizontal(scrollEvent); } }; self.scrollbarHeight = 0; self.scrollbarWidth = 0; if (self.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) { self.scrollbarHeight = gridUtil.getScrollbarWidth(); } if (self.options.enableVerticalScrollbar === uiGridConstants.scrollbars.ALWAYS) { self.scrollbarWidth = gridUtil.getScrollbarWidth(); } self.api = new GridApi(self); /** * @ngdoc function * @name refresh * @methodOf ui.grid.core.api:PublicApi * @description Refresh the rendered grid on screen. * The refresh method re-runs both the columnProcessors and the * rowProcessors, as well as calling refreshCanvas to update all * the grid sizing. In general you should prefer to use queueGridRefresh * instead, which is basically a debounced version of refresh. * * If you only want to resize the grid, not regenerate all the rows * and columns, you should consider directly calling refreshCanvas instead. * */ self.api.registerMethod( 'core', 'refresh', this.refresh ); /** * @ngdoc function * @name queueGridRefresh * @methodOf ui.grid.core.api:PublicApi * @description Request a refresh of the rendered grid on screen, if multiple * calls to queueGridRefresh are made within a digest cycle only one will execute. * The refresh method re-runs both the columnProcessors and the * rowProcessors, as well as calling refreshCanvas to update all * the grid sizing. In general you should prefer to use queueGridRefresh * instead, which is basically a debounced version of refresh. * */ self.api.registerMethod( 'core', 'queueGridRefresh', this.queueGridRefresh ); /** * @ngdoc function * @name refreshRows * @methodOf ui.grid.core.api:PublicApi * @description Runs only the rowProcessors, columns remain as they were. * It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing. * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'refreshRows', this.refreshRows ); /** * @ngdoc function * @name queueRefresh * @methodOf ui.grid.core.api:PublicApi * @description Requests execution of refreshCanvas, if multiple requests are made * during a digest cycle only one will run. RefreshCanvas updates the grid sizing. * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'queueRefresh', this.queueRefresh ); /** * @ngdoc function * @name handleWindowResize * @methodOf ui.grid.core.api:PublicApi * @description Trigger a grid resize, normally this would be picked * up by a watch on window size, but in some circumstances it is necessary * to call this manually * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'handleWindowResize', this.handleWindowResize ); /** * @ngdoc function * @name addRowHeaderColumn * @methodOf ui.grid.core.api:PublicApi * @description adds a row header column to the grid * @param {object} column def * */ self.api.registerMethod( 'core', 'addRowHeaderColumn', this.addRowHeaderColumn ); /** * @ngdoc function * @name scrollToIfNecessary * @methodOf ui.grid.core.api:PublicApi * @description Scrolls the grid to make a certain row and column combo visible, * in the case that it is not completely visible on the screen already. * @param {GridRow} gridRow row to make visible * @param {GridCol} gridCol column to make visible * @returns {promise} a promise that is resolved when scrolling is complete * */ self.api.registerMethod( 'core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol);} ); /** * @ngdoc function * @name scrollTo * @methodOf ui.grid.core.api:PublicApi * @description Scroll the grid such that the specified * row and column is in view * @param {object} rowEntity gridOptions.data[] array instance to make visible * @param {object} colDef to make visible * @returns {promise} a promise that is resolved after any scrolling is finished */ self.api.registerMethod( 'core', 'scrollTo', function (rowEntity, colDef) { return self.scrollTo(rowEntity, colDef);} ); /** * @ngdoc function * @name registerRowsProcessor * @methodOf ui.grid.core.api:PublicApi * @description * Register a "rows processor" function. When the rows are updated, * the grid calls each registered "rows processor", which has a chance * to alter the set of rows (sorting, etc) as long as the count is not * modified. * * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated rows list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier. * * At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100, * sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last) */ self.api.registerMethod( 'core', 'registerRowsProcessor', this.registerRowsProcessor ); /** * @ngdoc function * @name registerColumnsProcessor * @methodOf ui.grid.core.api:PublicApi * @description * Register a "columns processor" function. When the columns are updated, * the grid calls each registered "columns processor", which has a chance * to alter the set of columns as long as the count is not * modified. * * @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated columns list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier. * * At present allRowsVisible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) */ self.api.registerMethod( 'core', 'registerColumnsProcessor', this.registerColumnsProcessor ); /** * @ngdoc function * @name sortHandleNulls * @methodOf ui.grid.core.api:PublicApi * @description A null handling method that can be used when building custom sort * functions * @example * <pre> * mySortFn = function(a, b) { * var nulls = $scope.gridApi.core.sortHandleNulls(a, b); * if ( nulls !== null ){ * return nulls; * } else { * // your code for sorting here * }; * </pre> * @param {object} a sort value a * @param {object} b sort value b * @returns {number} null if there were no nulls/undefineds, otherwise returns * a sort value that should be passed back from the sort function * */ self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls ); /** * @ngdoc function * @name sortChanged * @methodOf ui.grid.core.api:PublicApi * @description The sort criteria on one or more columns has * changed. Provides as parameters the grid and the output of * getColumnSorting, which is an array of gridColumns * that have sorting on them, sorted in priority order. * * @param {Grid} grid the grid * @param {array} sortColumns an array of columns with * sorts on them, in priority order * * @example * <pre> * gridApi.core.on.sortChanged( grid, sortColumns ); * </pre> */ self.api.registerEvent( 'core', 'sortChanged' ); /** * @ngdoc function * @name columnVisibilityChanged * @methodOf ui.grid.core.api:PublicApi * @description The visibility of a column has changed, * the column itself is passed out as a parameter of the event. * * @param {GridCol} column the column that changed * * @example * <pre> * gridApi.core.on.columnVisibilityChanged( $scope, function (column) { * // do something * } ); * </pre> */ self.api.registerEvent( 'core', 'columnVisibilityChanged' ); /** * @ngdoc method * @name notifyDataChange * @methodOf ui.grid.core.api:PublicApi * @description Notify the grid that a data or config change has occurred, * where that change isn't something the grid was otherwise noticing. This * might be particularly relevant where you've changed values within the data * and you'd like cell classes to be re-evaluated, or changed config within * the columnDef and you'd like headerCellClasses to be re-evaluated. * @param {string} type one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN), which tells * us which refreshes to fire. * */ self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange ); /** * @ngdoc method * @name clearAllFilters * @methodOf ui.grid.core.api:PublicApi * @description Clears all filters and optionally refreshes the visible rows. * @param {object} refreshRows Defaults to true. * @param {object} clearConditions Defaults to false. * @param {object} clearFlags Defaults to false. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. */ self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters); self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]); self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]); self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]); self.registerStyleComputation({ priority: 10, func: self.getFooterStyles }); }; Grid.prototype.calcFooterHeight = function () { if (!this.hasFooter()) { return 0; } var height = 0; if (this.options.showGridFooter) { height += this.options.gridFooterHeight; } height += this.calcColumnFooterHeight(); return height; }; Grid.prototype.calcColumnFooterHeight = function () { var height = 0; if (this.options.showColumnFooter) { height += this.options.columnFooterHeight; } return height; }; Grid.prototype.getFooterStyles = function () { var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }'; style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }'; return style; }; Grid.prototype.hasFooter = function () { return this.options.showGridFooter || this.options.showColumnFooter; }; /** * @ngdoc function * @name isRTL * @methodOf ui.grid.class:Grid * @description Returns true if grid is RightToLeft */ Grid.prototype.isRTL = function () { return this.rtl; }; /** * @ngdoc function * @name registerColumnBuilder * @methodOf ui.grid.class:Grid * @description When the build creates columns from column definitions, the columnbuilders will be called to add * additional properties to the column. * @param {function(colDef, col, gridOptions)} columnBuilder function to be called */ Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) { this.columnBuilders.push(columnBuilder); }; /** * @ngdoc function * @name buildColumnDefsFromData * @methodOf ui.grid.class:Grid * @description Populates columnDefs from the provided data * @param {function(colDef, col, gridOptions)} rowBuilder function to be called */ Grid.prototype.buildColumnDefsFromData = function (dataRows){ this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties); }; /** * @ngdoc function * @name registerRowBuilder * @methodOf ui.grid.class:Grid * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add * additional properties to the row. * @param {function(row, gridOptions)} rowBuilder function to be called */ Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) { this.rowBuilders.push(rowBuilder); }; /** * @ngdoc function * @name registerDataChangeCallback * @methodOf ui.grid.class:Grid * @description When a data change occurs, the data change callbacks of the specified type * will be called. The rules are: * * - when the data watch fires, that is considered a ROW change (the data watch only notices * added or removed rows) * - when the api is called to inform us of a change, the declared type of that change is used * - when a cell edit completes, the EDIT callbacks are triggered * - when the columnDef watch fires, the COLUMN callbacks are triggered * - when the options watch fires, the OPTIONS callbacks are triggered * * For a given event: * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks * - ROW calls ROW and ALL callbacks * - EDIT calls EDIT and ALL callbacks * - COLUMN calls COLUMN and ALL callbacks * - OPTIONS calls OPTIONS and ALL callbacks * * @param {function(grid)} callback function to be called * @param {array} types the types of data change you want to be informed of. Values from * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to * ALL * @returns {function} deregister function - a function that can be called to deregister this callback */ Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) { var uid = gridUtil.nextUid(); if ( !types ){ types = [uiGridConstants.dataChange.ALL]; } if ( !Array.isArray(types)){ gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types ); } this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this }; var self = this; var deregisterFunction = function() { delete self.dataChangeCallbacks[uid]; }; return deregisterFunction; }; /** * @ngdoc function * @name callDataChangeCallbacks * @methodOf ui.grid.class:Grid * @description Calls the callbacks based on the type of data change that * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the * event type is matching, or if the type is ALL. * @param {number} type the type of event that occurred - one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS) */ Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) { angular.forEach( this.dataChangeCallbacks, function( callback, uid ){ if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 || callback.types.indexOf( type ) !== -1 || type === uiGridConstants.dataChange.ALL ) { if (callback._this) { callback.callback.apply(callback._this,this); } else { callback.callback( this ); } } }, this); }; /** * @ngdoc function * @name notifyDataChange * @methodOf ui.grid.class:Grid * @description Notifies us that a data change has occurred, used in the public * api for users to tell us when they've changed data or some other event that * our watches cannot pick up * @param {string} type the type of event that occurred - one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN) */ Grid.prototype.notifyDataChange = function notifyDataChange(type) { var constants = uiGridConstants.dataChange; if ( type === constants.ALL || type === constants.COLUMN || type === constants.EDIT || type === constants.ROW || type === constants.OPTIONS ){ this.callDataChangeCallbacks( type ); } else { gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type); } }; /** * @ngdoc function * @name columnRefreshCallback * @methodOf ui.grid.class:Grid * @description refreshes the grid when a column refresh * is notified, which triggers handling of the visible flag. * This is called on uiGridConstants.dataChange.COLUMN, and is * registered as a dataChangeCallback in grid.js * @param {string} name column name */ Grid.prototype.columnRefreshCallback = function columnRefreshCallback( grid ){ grid.buildColumns(); grid.queueGridRefresh(); }; /** * @ngdoc function * @name processRowsCallback * @methodOf ui.grid.class:Grid * @description calls the row processors, specifically * intended to reset the sorting when an edit is called, * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT * @param {string} name column name */ Grid.prototype.processRowsCallback = function processRowsCallback( grid ){ grid.queueGridRefresh(); }; /** * @ngdoc function * @name updateFooterHeightCallback * @methodOf ui.grid.class:Grid * @description recalculates the footer height, * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS * @param {string} name column name */ Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){ grid.footerHeight = grid.calcFooterHeight(); grid.columnFooterHeight = grid.calcColumnFooterHeight(); }; /** * @ngdoc function * @name getColumn * @methodOf ui.grid.class:Grid * @description returns a grid column for the column name * @param {string} name column name */ Grid.prototype.getColumn = function getColumn(name) { var columns = this.columns.filter(function (column) { return column.colDef.name === name; }); return columns.length > 0 ? columns[0] : null; }; /** * @ngdoc function * @name getColDef * @methodOf ui.grid.class:Grid * @description returns a grid colDef for the column name * @param {string} name column.field */ Grid.prototype.getColDef = function getColDef(name) { var colDefs = this.options.columnDefs.filter(function (colDef) { return colDef.name === name; }); return colDefs.length > 0 ? colDefs[0] : null; }; /** * @ngdoc function * @name assignTypes * @methodOf ui.grid.class:Grid * @description uses the first row of data to assign colDef.type for any types not defined. */ /** * @ngdoc property * @name type * @propertyOf ui.grid.class:GridOptions.columnDef * @description the type of the column, used in sorting. If not provided then the * grid will guess the type. Add this only if the grid guessing is not to your * satisfaction. One of: * - 'string' * - 'boolean' * - 'number' * - 'date' * - 'object' * - 'numberStr' * Note that if you choose date, your dates should be in a javascript date type * */ Grid.prototype.assignTypes = function(){ var self = this; self.options.columnDefs.forEach(function (colDef, index) { //Assign colDef type if not specified if (!colDef.type) { var col = new GridColumn(colDef, index, self); var firstRow = self.rows.length > 0 ? self.rows[0] : null; if (firstRow) { colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col)); } else { colDef.type = 'string'; } } }); }; /** * @ngdoc function * @name isRowHeaderColumn * @methodOf ui.grid.class:Grid * @description returns true if the column is a row Header * @param {object} column column */ Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) { return this.rowHeaderColumns.indexOf(column) !== -1; }; /** * @ngdoc function * @name addRowHeaderColumn * @methodOf ui.grid.class:Grid * @description adds a row header column to the grid * @param {object} column def */ Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef) { var self = this; var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self); rowHeaderCol.isRowHeader = true; if (self.isRTL()) { self.createRightContainer(); rowHeaderCol.renderContainer = 'right'; } else { self.createLeftContainer(); rowHeaderCol.renderContainer = 'left'; } // relies on the default column builder being first in array, as it is instantiated // as part of grid creation self.columnBuilders[0](colDef,rowHeaderCol,self.options) .then(function(){ rowHeaderCol.enableFiltering = false; rowHeaderCol.enableSorting = false; rowHeaderCol.enableHiding = false; self.rowHeaderColumns.push(rowHeaderCol); self.buildColumns() .then( function() { self.preCompileCellTemplates(); self.queueGridRefresh(); }); }); }; /** * @ngdoc function * @name getOnlyDataColumns * @methodOf ui.grid.class:Grid * @description returns all columns except for rowHeader columns */ Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() { var self = this; var cols = []; self.columns.forEach(function (col) { if (self.rowHeaderColumns.indexOf(col) === -1) { cols.push(col); } }); return cols; }; /** * @ngdoc function * @name buildColumns * @methodOf ui.grid.class:Grid * @description creates GridColumn objects from the columnDefinition. Calls each registered * columnBuilder to further process the column * @param {object} options An object contains options to use when building columns * * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions. * * @returns {Promise} a promise to load any needed column resources */ Grid.prototype.buildColumns = function buildColumns(opts) { var options = { orderByColumnDefs: false }; angular.extend(options, opts); // gridUtil.logDebug('buildColumns'); var self = this; var builderPromises = []; var headerOffset = self.rowHeaderColumns.length; var i; // Remove any columns for which a columnDef cannot be found // Deliberately don't use forEach, as it doesn't like splice being called in the middle // Also don't cache columns.length, as it will change during this operation for (i = 0; i < self.columns.length; i++){ if (!self.getColDef(self.columns[i].name)) { self.columns.splice(i, 1); i--; } } //add row header columns to the grid columns array _after_ columns without columnDefs have been removed self.rowHeaderColumns.forEach(function (rowHeaderColumn) { self.columns.unshift(rowHeaderColumn); }); // look at each column def, and update column properties to match. If the column def // doesn't have a column, then splice in a new gridCol self.options.columnDefs.forEach(function (colDef, index) { self.preprocessColDef(colDef); var col = self.getColumn(colDef.name); if (!col) { col = new GridColumn(colDef, gridUtil.nextUid(), self); self.columns.splice(index + headerOffset, 0, col); } else { // tell updateColumnDef that the column was pre-existing col.updateColumnDef(colDef, false); } self.columnBuilders.forEach(function (builder) { builderPromises.push(builder.call(self, colDef, col, self.options)); }); }); /*** Reorder columns if necessary ***/ if (!!options.orderByColumnDefs) { // Create a shallow copy of the columns as a cache var columnCache = self.columns.slice(0); // We need to allow for the "row headers" when mapping from the column defs array to the columns array // If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0] // Go through all the column defs, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result var len = Math.min(self.options.columnDefs.length, self.columns.length); for (i = 0; i < len; i++) { // If the column at this index has a different name than the column at the same index in the column defs... if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) { // Replace the one in the cache with the appropriate column columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name); } else { // Otherwise just copy over the one from the initial columns columnCache[i + headerOffset] = self.columns[i + headerOffset]; } } // Empty out the columns array, non-destructively self.columns.length = 0; // And splice in the updated, ordered columns from the cache Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache)); } return $q.all(builderPromises).then(function(){ if (self.rows.length > 0){ self.assignTypes(); } }); }; /** * @ngdoc function * @name preCompileCellTemplates * @methodOf ui.grid.class:Grid * @description precompiles all cell templates */ Grid.prototype.preCompileCellTemplates = function() { var self = this; var preCompileTemplate = function( col ) { var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col)); html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var compiledElementFn = $compile(html); col.compiledElementFn = compiledElementFn; if (col.compiledElementFnDefer) { col.compiledElementFnDefer.resolve(col.compiledElementFn); } }; this.columns.forEach(function (col) { if ( col.cellTemplate ){ preCompileTemplate( col ); } else if ( col.cellTemplatePromise ){ col.cellTemplatePromise.then( function() { preCompileTemplate( col ); }); } }); }; /** * @ngdoc function * @name getGridQualifiedColField * @methodOf ui.grid.class:Grid * @description Returns the $parse-able accessor for a column within its $scope * @param {GridColumn} col col object */ Grid.prototype.getQualifiedColField = function (col) { return 'row.entity.' + gridUtil.preEval(col.field); }; /** * @ngdoc function * @name createLeftContainer * @methodOf ui.grid.class:Grid * @description creates the left render container if it doesn't already exist */ Grid.prototype.createLeftContainer = function() { if (!this.hasLeftContainer()) { this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true }); } }; /** * @ngdoc function * @name createRightContainer * @methodOf ui.grid.class:Grid * @description creates the right render container if it doesn't already exist */ Grid.prototype.createRightContainer = function() { if (!this.hasRightContainer()) { this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true }); } }; /** * @ngdoc function * @name hasLeftContainer * @methodOf ui.grid.class:Grid * @description returns true if leftContainer exists */ Grid.prototype.hasLeftContainer = function() { return this.renderContainers.left !== undefined; }; /** * @ngdoc function * @name hasLeftContainer * @methodOf ui.grid.class:Grid * @description returns true if rightContainer exists */ Grid.prototype.hasRightContainer = function() { return this.renderContainers.right !== undefined; }; /** * undocumented function * @name preprocessColDef * @methodOf ui.grid.class:Grid * @description defaults the name property from field to maintain backwards compatibility with 2.x * validates that name or field is present */ Grid.prototype.preprocessColDef = function preprocessColDef(colDef) { var self = this; if (!colDef.field && !colDef.name) { throw new Error('colDef.name or colDef.field property is required'); } //maintain backwards compatibility with 2.x //field was required in 2.x. now name is required if (colDef.name === undefined && colDef.field !== undefined) { // See if the column name already exists: var newName = colDef.field, counter = 2; while (self.getColumn(newName)) { newName = colDef.field + counter.toString(); counter++; } colDef.name = newName; } }; // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) { var self = this; var t = []; for (var i = 0; i < n.length; i++) { var nV = nAccessor ? n[i][nAccessor] : n[i]; var found = false; for (var j = 0; j < o.length; j++) { var oV = oAccessor ? o[j][oAccessor] : o[j]; if (self.options.rowEquality(nV, oV)) { found = true; break; } } if (!found) { t.push(nV); } } return t; }; /** * @ngdoc function * @name getRow * @methodOf ui.grid.class:Grid * @description returns the GridRow that contains the rowEntity * @param {object} rowEntity the gridOptions.data array element instance * @param {array} rows [optional] the rows to look in - if not provided then * looks in grid.rows */ Grid.prototype.getRow = function getRow(rowEntity, lookInRows) { var self = this; lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows; var rows = lookInRows.filter(function (row) { return self.options.rowEquality(row.entity, rowEntity); }); return rows.length > 0 ? rows[0] : null; }; /** * @ngdoc function * @name modifyRows * @methodOf ui.grid.class:Grid * @description creates or removes GridRow objects from the newRawData array. Calls each registered * rowBuilder to further process the row * * This method aims to achieve three things: * 1. the resulting rows array is in the same order as the newRawData, we'll call * rowsProcessors immediately after to sort the data anyway * 2. if we have row hashing available, we try to use the rowHash to find the row * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected * * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates * the newRows and newHash * * ``` * newRawData.forEach newEntity * if (hashing enabled) * check oldHash for newEntity * else * look for old row directly in oldRows * if !oldRowFound // must be a new row * create newRow * append to the newRows and add to newHash * run the processors * * Rows are identified using the hashKey if configured. If not configured, then rows * are identified using the gridOptions.rowEquality function */ Grid.prototype.modifyRows = function modifyRows(newRawData) { var self = this; var oldRows = self.rows.slice(0); var oldRowHash = self.rowHashMap || self.createRowHashMap(); self.rowHashMap = self.createRowHashMap(); self.rows.length = 0; newRawData.forEach( function( newEntity, i ) { var newRow; if ( self.options.enableRowHashing ){ // if hashing is enabled, then this row will be in the hash if we already know about it newRow = oldRowHash.get( newEntity ); } else { // otherwise, manually search the oldRows to see if we can find this row newRow = self.getRow(newEntity, oldRows); } // if we didn't find the row, it must be new, so create it if ( !newRow ){ newRow = self.processRowBuilders(new GridRow(newEntity, i, self)); } self.rows.push( newRow ); self.rowHashMap.put( newEntity, newRow ); }); self.assignTypes(); var p1 = $q.when(self.processRowsProcessors(self.rows)) .then(function (renderableRows) { return self.setVisibleRows(renderableRows); }); var p2 = $q.when(self.processColumnsProcessors(self.columns)) .then(function (renderableColumns) { return self.setVisibleColumns(renderableColumns); }); return $q.all([p1, p2]); }; /** * Private Undocumented Method * @name addRows * @methodOf ui.grid.class:Grid * @description adds the newRawData array of rows to the grid and calls all registered * rowBuilders. this keyword will reference the grid */ Grid.prototype.addRows = function addRows(newRawData) { var self = this; var existingRowCount = self.rows.length; for (var i = 0; i < newRawData.length; i++) { var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self)); if (self.options.enableRowHashing) { var found = self.rowHashMap.get(newRow.entity); if (found) { found.row = newRow; } } self.rows.push(newRow); } }; /** * @ngdoc function * @name processRowBuilders * @methodOf ui.grid.class:Grid * @description processes all RowBuilders for the gridRow * @param {GridRow} gridRow reference to gridRow * @returns {GridRow} the gridRow with all additional behavior added */ Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) { var self = this; self.rowBuilders.forEach(function (builder) { builder.call(self, gridRow, self.options); }); return gridRow; }; /** * @ngdoc function * @name registerStyleComputation * @methodOf ui.grid.class:Grid * @description registered a styleComputation function * * If the function returns a value it will be appended into the grid's `<style>` block * @param {function($scope)} styleComputation function */ Grid.prototype.registerStyleComputation = function registerStyleComputation(styleComputationInfo) { this.styleComputations.push(styleComputationInfo); }; // NOTE (c0bra): We already have rowBuilders. I think these do exactly the same thing... // Grid.prototype.registerRowFilter = function(filter) { // // TODO(c0bra): validate filter? // this.rowFilters.push(filter); // }; // Grid.prototype.removeRowFilter = function(filter) { // var idx = this.rowFilters.indexOf(filter); // if (typeof(idx) !== 'undefined' && idx !== undefined) { // this.rowFilters.slice(idx, 1); // } // }; // Grid.prototype.processRowFilters = function(rows) { // var self = this; // self.rowFilters.forEach(function (filter) { // filter.call(self, rows); // }); // }; /** * @ngdoc function * @name registerRowsProcessor * @methodOf ui.grid.class:Grid * @description * * Register a "rows processor" function. When the rows are updated, * the grid calls each registered "rows processor", which has a chance * to alter the set of rows (sorting, etc) as long as the count is not * modified. * * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated rows list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier. * * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) * */ Grid.prototype.registerRowsProcessor = function registerRowsProcessor(processor, priority) { if (!angular.isFunction(processor)) { throw 'Attempt to register non-function rows processor: ' + processor; } this.rowsProcessors.push({processor: processor, priority: priority}); this.rowsProcessors.sort(function sortByPriority( a, b ){ return a.priority - b.priority; }); }; /** * @ngdoc function * @name removeRowsProcessor * @methodOf ui.grid.class:Grid * @param {function(renderableRows)} rows processor function * @description Remove a registered rows processor */ Grid.prototype.removeRowsProcessor = function removeRowsProcessor(processor) { var idx = -1; this.rowsProcessors.forEach(function(rowsProcessor, index){ if ( rowsProcessor.processor === processor ){ idx = index; } }); if ( idx !== -1 ) { this.rowsProcessors.splice(idx, 1); } }; /** * Private Undocumented Method * @name processRowsProcessors * @methodOf ui.grid.class:Grid * @param {Array[GridRow]} The array of "renderable" rows * @param {Array[GridColumn]} The array of columns * @description Run all the registered rows processors on the array of renderable rows */ Grid.prototype.processRowsProcessors = function processRowsProcessors(renderableRows) { var self = this; // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order var myRenderableRows = renderableRows.slice(0); // Return myRenderableRows with no processing if we have no rows processors if (self.rowsProcessors.length === 0) { return $q.when(myRenderableRows); } // Counter for iterating through rows processors var i = 0; // Promise for when we're done with all the processors var finished = $q.defer(); // This function will call the processor in self.rowsProcessors at index 'i', and then // when done will call the next processor in the list, using the output from the processor // at i as the argument for 'renderedRowsToProcess' on the next iteration. // // If we're at the end of the list of processors, we resolve our 'finished' callback with // the result. function startProcessor(i, renderedRowsToProcess) { // Get the processor at 'i' var processor = self.rowsProcessors[i].processor; // Call the processor, passing in the rows to process and the current columns // (note: it's wrapped in $q.when() in case the processor does not return a promise) return $q.when( processor.call(self, renderedRowsToProcess, self.columns) ) .then(function handleProcessedRows(processedRows) { // Check for errors if (!processedRows) { throw "Processor at index " + i + " did not return a set of renderable rows"; } if (!angular.isArray(processedRows)) { throw "Processor at index " + i + " did not return an array"; } // Processor is done, increment the counter i++; // If we're not done with the processors, call the next one if (i <= self.rowsProcessors.length - 1) { return startProcessor(i, processedRows); } // We're done! Resolve the 'finished' promise else { finished.resolve(processedRows); } }); } // Start on the first processor startProcessor(0, myRenderableRows); return finished.promise; }; Grid.prototype.setVisibleRows = function setVisibleRows(rows) { var self = this; // Reset all the render container row caches for (var i in self.renderContainers) { var container = self.renderContainers[i]; container.canvasHeightShouldUpdate = true; if ( typeof(container.visibleRowCache) === 'undefined' ){ container.visibleRowCache = []; } else { container.visibleRowCache.length = 0; } } // rows.forEach(function (row) { for (var ri = 0; ri < rows.length; ri++) { var row = rows[ri]; var targetContainer = (typeof(row.renderContainer) !== 'undefined' && row.renderContainer) ? row.renderContainer : 'body'; // If the row is visible if (row.visible) { self.renderContainers[targetContainer].visibleRowCache.push(row); } } self.api.core.raise.rowsRendered(this.api); }; /** * @ngdoc function * @name registerColumnsProcessor * @methodOf ui.grid.class:Grid * @param {function(renderedColumnsToProcess, rows)} columnProcessor column processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and * which must return an updated renderedColumnsToProcess which can be passed to the next processor * in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier. * * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) * @description Register a "columns processor" function. When the columns are updated, the grid calls each registered "columns processor", which has a chance to alter the set of columns, as long as the count is not modified. */ Grid.prototype.registerColumnsProcessor = function registerColumnsProcessor(processor, priority) { if (!angular.isFunction(processor)) { throw 'Attempt to register non-function rows processor: ' + processor; } this.columnsProcessors.push({processor: processor, priority: priority}); this.columnsProcessors.sort(function sortByPriority( a, b ){ return a.priority - b.priority; }); }; Grid.prototype.removeColumnsProcessor = function removeColumnsProcessor(processor) { var idx = this.columnsProcessors.indexOf(processor); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.columnsProcessors.splice(idx, 1); } }; Grid.prototype.processColumnsProcessors = function processColumnsProcessors(renderableColumns) { var self = this; // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order var myRenderableColumns = renderableColumns.slice(0); // Return myRenderableRows with no processing if we have no rows processors if (self.columnsProcessors.length === 0) { return $q.when(myRenderableColumns); } // Counter for iterating through rows processors var i = 0; // Promise for when we're done with all the processors var finished = $q.defer(); // This function will call the processor in self.rowsProcessors at index 'i', and then // when done will call the next processor in the list, using the output from the processor // at i as the argument for 'renderedRowsToProcess' on the next iteration. // // If we're at the end of the list of processors, we resolve our 'finished' callback with // the result. function startProcessor(i, renderedColumnsToProcess) { // Get the processor at 'i' var processor = self.columnsProcessors[i].processor; // Call the processor, passing in the rows to process and the current columns // (note: it's wrapped in $q.when() in case the processor does not return a promise) return $q.when( processor.call(self, renderedColumnsToProcess, self.rows) ) .then(function handleProcessedRows(processedColumns) { // Check for errors if (!processedColumns) { throw "Processor at index " + i + " did not return a set of renderable rows"; } if (!angular.isArray(processedColumns)) { throw "Processor at index " + i + " did not return an array"; } // Processor is done, increment the counter i++; // If we're not done with the processors, call the next one if (i <= self.columnsProcessors.length - 1) { return startProcessor(i, myRenderableColumns); } // We're done! Resolve the 'finished' promise else { finished.resolve(myRenderableColumns); } }); } // Start on the first processor startProcessor(0, myRenderableColumns); return finished.promise; }; Grid.prototype.setVisibleColumns = function setVisibleColumns(columns) { // gridUtil.logDebug('setVisibleColumns'); var self = this; // Reset all the render container row caches for (var i in self.renderContainers) { var container = self.renderContainers[i]; container.visibleColumnCache.length = 0; } for (var ci = 0; ci < columns.length; ci++) { var column = columns[ci]; // If the column is visible if (column.visible) { // If the column has a container specified if (typeof(column.renderContainer) !== 'undefined' && column.renderContainer) { self.renderContainers[column.renderContainer].visibleColumnCache.push(column); } // If not, put it into the body container else { self.renderContainers.body.visibleColumnCache.push(column); } } } }; /** * @ngdoc function * @name handleWindowResize * @methodOf ui.grid.class:Grid * @description Triggered when the browser window resizes; automatically resizes the grid */ Grid.prototype.handleWindowResize = function handleWindowResize($event) { var self = this; self.gridWidth = gridUtil.elementWidth(self.element); self.gridHeight = gridUtil.elementHeight(self.element); self.queueRefresh(); }; /** * @ngdoc function * @name queueRefresh * @methodOf ui.grid.class:Grid * @description queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue */ Grid.prototype.queueRefresh = function queueRefresh() { var self = this; if (self.refreshCanceller) { $timeout.cancel(self.refreshCanceller); } self.refreshCanceller = $timeout(function () { self.refreshCanvas(true); }); self.refreshCanceller.then(function () { self.refreshCanceller = null; }); return self.refreshCanceller; }; /** * @ngdoc function * @name queueGridRefresh * @methodOf ui.grid.class:Grid * @description queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue */ Grid.prototype.queueGridRefresh = function queueGridRefresh() { var self = this; if (self.gridRefreshCanceller) { $timeout.cancel(self.gridRefreshCanceller); } self.gridRefreshCanceller = $timeout(function () { self.refresh(true); }); self.gridRefreshCanceller.then(function () { self.gridRefreshCanceller = null; }); return self.gridRefreshCanceller; }; /** * @ngdoc function * @name updateCanvasHeight * @methodOf ui.grid.class:Grid * @description flags all render containers to update their canvas height */ Grid.prototype.updateCanvasHeight = function updateCanvasHeight() { var self = this; for (var containerId in self.renderContainers) { if (self.renderContainers.hasOwnProperty(containerId)) { var container = self.renderContainers[containerId]; container.canvasHeightShouldUpdate = true; } } }; /** * @ngdoc function * @name buildStyles * @methodOf ui.grid.class:Grid * @description calls each styleComputation function */ // TODO: this used to take $scope, but couldn't see that it was used Grid.prototype.buildStyles = function buildStyles() { // gridUtil.logDebug('buildStyles'); var self = this; self.customStyles = ''; self.styleComputations .sort(function(a, b) { if (a.priority === null) { return 1; } if (b.priority === null) { return -1; } if (a.priority === null && b.priority === null) { return 0; } return a.priority - b.priority; }) .forEach(function (compInfo) { // this used to provide $scope as a second parameter, but I couldn't find any // style builders that used it, so removed it as part of moving to grid from controller var ret = compInfo.func.call(self); if (angular.isString(ret)) { self.customStyles += '\n' + ret; } }); }; Grid.prototype.minColumnsToRender = function minColumnsToRender() { var self = this; var viewport = this.getViewportWidth(); var min = 0; var totalWidth = 0; self.columns.forEach(function(col, i) { if (totalWidth < viewport) { totalWidth += col.drawnWidth; min++; } else { var currWidth = 0; for (var j = i; j >= i - min; j--) { currWidth += self.columns[j].drawnWidth; } if (currWidth < viewport) { min++; } } }); return min; }; Grid.prototype.getBodyHeight = function getBodyHeight() { // Start with the viewportHeight var bodyHeight = this.getViewportHeight(); // Add the horizontal scrollbar height if there is one //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) { // bodyHeight = bodyHeight + this.horizontalScrollbarHeight; //} return bodyHeight; }; // NOTE: viewport drawable height is the height of the grid minus the header row height (including any border) // TODO(c0bra): account for footer height Grid.prototype.getViewportHeight = function getViewportHeight() { var self = this; var viewPortHeight = this.gridHeight - this.headerHeight - this.footerHeight; // Account for native horizontal scrollbar, if present //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) { // viewPortHeight = viewPortHeight - this.horizontalScrollbarHeight; //} var adjustment = self.getViewportAdjustment(); viewPortHeight = viewPortHeight + adjustment.height; //gridUtil.logDebug('viewPortHeight', viewPortHeight); return viewPortHeight; }; Grid.prototype.getViewportWidth = function getViewportWidth() { var self = this; var viewPortWidth = this.gridWidth; //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth - this.verticalScrollbarWidth; //} var adjustment = self.getViewportAdjustment(); viewPortWidth = viewPortWidth + adjustment.width; //gridUtil.logDebug('getviewPortWidth', viewPortWidth); return viewPortWidth; }; Grid.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() { var viewPortWidth = this.getViewportWidth(); //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth + this.verticalScrollbarWidth; //} return viewPortWidth; }; Grid.prototype.addVerticalScrollSync = function (containerId, callBackFn) { this.verticalScrollSyncCallBackFns[containerId] = callBackFn; }; Grid.prototype.addHorizontalScrollSync = function (containerId, callBackFn) { this.horizontalScrollSyncCallBackFns[containerId] = callBackFn; }; /** * Scroll needed containers by calling their ScrollSyncs * @param sourceContainerId the containerId that has already set it's top/left. * can be empty string which means all containers need to set top/left * @param scrollEvent */ Grid.prototype.scrollContainers = function (sourceContainerId, scrollEvent) { if (scrollEvent.y) { //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left) var verts = ['body','left', 'right']; this.flagScrollingVertically(scrollEvent); if (sourceContainerId === 'body') { verts = ['left', 'right']; } else if (sourceContainerId === 'left') { verts = ['body', 'right']; } else if (sourceContainerId === 'right') { verts = ['body', 'left']; } for (var i = 0; i < verts.length; i++) { var id = verts[i]; if (this.verticalScrollSyncCallBackFns[id]) { this.verticalScrollSyncCallBackFns[id](scrollEvent); } } } if (scrollEvent.x) { //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left) var horizs = ['body','bodyheader', 'bodyfooter']; this.flagScrollingHorizontally(scrollEvent); if (sourceContainerId === 'body') { horizs = ['bodyheader', 'bodyfooter']; } for (var j = 0; j < horizs.length; j++) { var idh = horizs[j]; if (this.horizontalScrollSyncCallBackFns[idh]) { this.horizontalScrollSyncCallBackFns[idh](scrollEvent); } } } }; Grid.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) { this.viewportAdjusters.push(func); }; Grid.prototype.removeViewportAdjuster = function registerViewportAdjuster(func) { var idx = this.viewportAdjusters.indexOf(func); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.viewportAdjusters.splice(idx, 1); } }; Grid.prototype.getViewportAdjustment = function getViewportAdjustment() { var self = this; var adjustment = { height: 0, width: 0 }; self.viewportAdjusters.forEach(function (func) { adjustment = func.call(this, adjustment); }); return adjustment; }; Grid.prototype.getVisibleRowCount = function getVisibleRowCount() { // var count = 0; // this.rows.forEach(function (row) { // if (row.visible) { // count++; // } // }); // return this.visibleRowCache.length; return this.renderContainers.body.visibleRowCache.length; }; Grid.prototype.getVisibleRows = function getVisibleRows() { return this.renderContainers.body.visibleRowCache; }; Grid.prototype.getVisibleColumnCount = function getVisibleColumnCount() { // var count = 0; // this.rows.forEach(function (row) { // if (row.visible) { // count++; // } // }); // return this.visibleRowCache.length; return this.renderContainers.body.visibleColumnCache.length; }; Grid.prototype.searchRows = function searchRows(renderableRows) { return rowSearcher.search(this, renderableRows, this.columns); }; Grid.prototype.sortByColumn = function sortByColumn(renderableRows) { return rowSorter.sort(this, renderableRows, this.columns); }; /** * @ngdoc function * @name getCellValue * @methodOf ui.grid.class:Grid * @description Gets the value of a cell for a particular row and column * @param {GridRow} row Row to access * @param {GridColumn} col Column to access */ Grid.prototype.getCellValue = function getCellValue(row, col){ if ( typeof(row.entity[ '$$' + col.uid ]) !== 'undefined' ) { return row.entity[ '$$' + col.uid].rendered; } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined' ){ return row.entity[col.field]; } else { if (!col.cellValueGetterCache) { col.cellValueGetterCache = $parse(row.getEntityQualifiedColField(col)); } return col.cellValueGetterCache(row); } }; /** * @ngdoc function * @name getCellDisplayValue * @methodOf ui.grid.class:Grid * @description Gets the displayed value of a cell after applying any the `cellFilter` * @param {GridRow} row Row to access * @param {GridColumn} col Column to access */ Grid.prototype.getCellDisplayValue = function getCellDisplayValue(row, col) { if ( !col.cellDisplayGetterCache ) { var custom_filter = col.cellFilter ? " | " + col.cellFilter : ""; if (typeof(row.entity['$$' + col.uid]) !== 'undefined') { col.cellDisplayGetterCache = $parse(row.entity['$$' + col.uid].rendered + custom_filter); } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined') { col.cellDisplayGetterCache = $parse(row.entity[col.field] + custom_filter); } else { col.cellDisplayGetterCache = $parse(row.getEntityQualifiedColField(col) + custom_filter); } } return col.cellDisplayGetterCache(row); }; Grid.prototype.getNextColumnSortPriority = function getNextColumnSortPriority() { var self = this, p = 0; self.columns.forEach(function (col) { if (col.sort && col.sort.priority && col.sort.priority > p) { p = col.sort.priority; } }); return p + 1; }; /** * @ngdoc function * @name resetColumnSorting * @methodOf ui.grid.class:Grid * @description Return the columns that the grid is currently being sorted by * @param {GridColumn} [excludedColumn] Optional GridColumn to exclude from having its sorting reset */ Grid.prototype.resetColumnSorting = function resetColumnSorting(excludeCol) { var self = this; self.columns.forEach(function (col) { if (col !== excludeCol && !col.suppressRemoveSort) { col.sort = {}; } }); }; /** * @ngdoc function * @name getColumnSorting * @methodOf ui.grid.class:Grid * @description Return the columns that the grid is currently being sorted by * @returns {Array[GridColumn]} An array of GridColumn objects */ Grid.prototype.getColumnSorting = function getColumnSorting() { var self = this; var sortedCols = [], myCols; // Iterate through all the columns, sorted by priority // Make local copy of column list, because sorting is in-place and we do not want to // change the original sequence of columns myCols = self.columns.slice(0); myCols.sort(rowSorter.prioritySort).forEach(function (col) { if (col.sort && typeof(col.sort.direction) !== 'undefined' && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) { sortedCols.push(col); } }); return sortedCols; }; /** * @ngdoc function * @name sortColumn * @methodOf ui.grid.class:Grid * @description Set the sorting on a given column, optionally resetting any existing sorting on the Grid. * Emits the sortChanged event whenever the sort criteria are changed. * @param {GridColumn} column Column to set the sorting on * @param {uiGridConstants.ASC|uiGridConstants.DESC} [direction] Direction to sort by, either descending or ascending. * If not provided, the column will iterate through the sort directions: ascending, descending, unsorted. * @param {boolean} [add] Add this column to the sorting. If not provided or set to `false`, the Grid will reset any existing sorting and sort * by this column only * @returns {Promise} A resolved promise that supplies the column. */ Grid.prototype.sortColumn = function sortColumn(column, directionOrAdd, add) { var self = this, direction = null; if (typeof(column) === 'undefined' || !column) { throw new Error('No column parameter provided'); } // Second argument can either be a direction or whether to add this column to the existing sort. // If it's a boolean, it's an add, otherwise, it's a direction if (typeof(directionOrAdd) === 'boolean') { add = directionOrAdd; } else { direction = directionOrAdd; } if (!add) { self.resetColumnSorting(column); column.sort.priority = 0; // Get the actual priority since there may be columns which have suppressRemoveSort set column.sort.priority = self.getNextColumnSortPriority(); } else if (!column.sort.priority){ column.sort.priority = self.getNextColumnSortPriority(); } if (!direction) { // Figure out the sort direction if (column.sort.direction && column.sort.direction === uiGridConstants.ASC) { column.sort.direction = uiGridConstants.DESC; } else if (column.sort.direction && column.sort.direction === uiGridConstants.DESC) { if ( column.colDef && column.suppressRemoveSort ){ column.sort.direction = uiGridConstants.ASC; } else { column.sort = {}; } } else { column.sort.direction = uiGridConstants.ASC; } } else { column.sort.direction = direction; } self.api.core.raise.sortChanged( self, self.getColumnSorting() ); return $q.when(column); }; /** * communicate to outside world that we are done with initial rendering */ Grid.prototype.renderingComplete = function(){ if (angular.isFunction(this.options.onRegisterApi)) { this.options.onRegisterApi(this.api); } this.api.core.raise.renderingComplete( this.api ); }; Grid.prototype.createRowHashMap = function createRowHashMap() { var self = this; var hashMap = new RowHashMap(); hashMap.grid = self; return hashMap; }; /** * @ngdoc function * @name refresh * @methodOf ui.grid.class:Grid * @description Refresh the rendered grid on screen. * @param {boolean} [rowsAltered] Optional flag for refreshing when the number of rows has changed. */ Grid.prototype.refresh = function refresh(rowsAltered) { var self = this; var p1 = self.processRowsProcessors(self.rows).then(function (renderableRows) { self.setVisibleRows(renderableRows); }); var p2 = self.processColumnsProcessors(self.columns).then(function (renderableColumns) { self.setVisibleColumns(renderableColumns); }); return $q.all([p1, p2]).then(function () { self.redrawInPlace(rowsAltered); self.refreshCanvas(true); }); }; /** * @ngdoc function * @name refreshRows * @methodOf ui.grid.class:Grid * @description Refresh the rendered rows on screen? Note: not functional at present * @returns {promise} promise that is resolved when render completes? * */ Grid.prototype.refreshRows = function refreshRows() { var self = this; return self.processRowsProcessors(self.rows) .then(function (renderableRows) { self.setVisibleRows(renderableRows); self.redrawInPlace(); self.refreshCanvas( true ); }); }; /** * @ngdoc function * @name refreshCanvas * @methodOf ui.grid.class:Grid * @description Builds all styles and recalculates much of the grid sizing * @param {object} buildStyles optional parameter. Use TBD * @returns {promise} promise that is resolved when the canvas * has been refreshed * */ Grid.prototype.refreshCanvas = function(buildStyles) { var self = this; if (buildStyles) { self.buildStyles(); } var p = $q.defer(); // Get all the header heights var containerHeadersToRecalc = []; for (var containerId in self.renderContainers) { if (self.renderContainers.hasOwnProperty(containerId)) { var container = self.renderContainers[containerId]; // Skip containers that have no canvasWidth set yet if (container.canvasWidth === null || isNaN(container.canvasWidth)) { continue; } if (container.header || container.headerCanvas) { container.explicitHeaderHeight = container.explicitHeaderHeight || null; container.explicitHeaderCanvasHeight = container.explicitHeaderCanvasHeight || null; containerHeadersToRecalc.push(container); } } } /* * * Here we loop through the headers, measuring each element as well as any header "canvas" it has within it. * * If any header is less than the largest header height, it will be resized to that so that we don't have headers * with different heights, which looks like a rendering problem * * We'll do the same thing with the header canvases, and give the header CELLS an explicit height if their canvas * is smaller than the largest canvas height. That was header cells without extra controls like filtering don't * appear shorter than other cells. * */ if (containerHeadersToRecalc.length > 0) { // Build the styles without the explicit header heights if (buildStyles) { self.buildStyles(); } // Putting in a timeout as it's not calculating after the grid element is rendered and filled out $timeout(function() { // var oldHeaderHeight = self.grid.headerHeight; // self.grid.headerHeight = gridUtil.outerElementHeight(self.header); var rebuildStyles = false; // Get all the header heights var maxHeaderHeight = 0; var maxHeaderCanvasHeight = 0; var i, container; var getHeight = function(oldVal, newVal){ if ( oldVal !== newVal){ rebuildStyles = true; } return newVal; }; for (i = 0; i < containerHeadersToRecalc.length; i++) { container = containerHeadersToRecalc[i]; // Skip containers that have no canvasWidth set yet if (container.canvasWidth === null || isNaN(container.canvasWidth)) { continue; } if (container.header) { var headerHeight = container.headerHeight = getHeight(container.headerHeight, parseInt(gridUtil.outerElementHeight(container.header), 10)); // Get the "inner" header height, that is the height minus the top and bottom borders, if present. We'll use it to make sure all the headers have a consistent height var topBorder = gridUtil.getBorderSize(container.header, 'top'); var bottomBorder = gridUtil.getBorderSize(container.header, 'bottom'); var innerHeaderHeight = parseInt(headerHeight - topBorder - bottomBorder, 10); innerHeaderHeight = innerHeaderHeight < 0 ? 0 : innerHeaderHeight; container.innerHeaderHeight = innerHeaderHeight; // If the header doesn't have an explicit height set, save the largest header height for use later // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly if (!container.explicitHeaderHeight && innerHeaderHeight > maxHeaderHeight) { maxHeaderHeight = innerHeaderHeight; } } if (container.headerCanvas) { var headerCanvasHeight = container.headerCanvasHeight = getHeight(container.headerCanvasHeight, parseInt(gridUtil.outerElementHeight(container.headerCanvas), 10)); // If the header doesn't have an explicit canvas height, save the largest header canvas height for use later // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly if (!container.explicitHeaderCanvasHeight && headerCanvasHeight > maxHeaderCanvasHeight) { maxHeaderCanvasHeight = headerCanvasHeight; } } } // Go through all the headers for (i = 0; i < containerHeadersToRecalc.length; i++) { container = containerHeadersToRecalc[i]; /* If: 1. We have a max header height 2. This container has a header height defined 3. And either this container has an explicit header height set, OR its header height is less than the max then: Give this container's header an explicit height so it will line up with the tallest header */ if ( maxHeaderHeight > 0 && typeof(container.headerHeight) !== 'undefined' && container.headerHeight !== null && (container.explicitHeaderHeight || container.headerHeight < maxHeaderHeight) ) { container.explicitHeaderHeight = getHeight(container.explicitHeaderHeight, maxHeaderHeight); } // Do the same as above except for the header canvas if ( maxHeaderCanvasHeight > 0 && typeof(container.headerCanvasHeight) !== 'undefined' && container.headerCanvasHeight !== null && (container.explicitHeaderCanvasHeight || container.headerCanvasHeight < maxHeaderCanvasHeight) ) { container.explicitHeaderCanvasHeight = getHeight(container.explicitHeaderCanvasHeight, maxHeaderCanvasHeight); } } // Rebuild styles if the header height has changed // The header height is used in body/viewport calculations and those are then used in other styles so we need it to be available if (buildStyles && rebuildStyles) { self.buildStyles(); } p.resolve(); }); } else { // Timeout still needs to be here to trigger digest after styles have been rebuilt $timeout(function() { p.resolve(); }); } return p.promise; }; /** * @ngdoc function * @name redrawCanvas * @methodOf ui.grid.class:Grid * @description Redraw the rows and columns based on our current scroll position * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be recalculated * */ Grid.prototype.redrawInPlace = function redrawInPlace(rowsAdded) { // gridUtil.logDebug('redrawInPlace'); var self = this; for (var i in self.renderContainers) { var container = self.renderContainers[i]; // gridUtil.logDebug('redrawing container', i); if (rowsAdded) { container.adjustRows(container.prevScrollTop, null); container.adjustColumns(container.prevScrollLeft, null); } else { container.adjustRows(null, container.prevScrolltopPercentage); container.adjustColumns(null, container.prevScrollleftPercentage); } } }; /** * @ngdoc function * @name hasLeftContainerColumns * @methodOf ui.grid.class:Grid * @description returns true if leftContainer has columns */ Grid.prototype.hasLeftContainerColumns = function () { return this.hasLeftContainer() && this.renderContainers.left.renderedColumns.length > 0; }; /** * @ngdoc function * @name hasRightContainerColumns * @methodOf ui.grid.class:Grid * @description returns true if rightContainer has columns */ Grid.prototype.hasRightContainerColumns = function () { return this.hasRightContainer() && this.renderContainers.right.renderedColumns.length > 0; }; /** * @ngdoc method * @methodOf ui.grid.class:Grid * @name scrollToIfNecessary * @description Scrolls the grid to make a certain row and column combo visible, * in the case that it is not completely visible on the screen already. * @param {GridRow} gridRow row to make visible * @param {GridCol} gridCol column to make visible * @returns {promise} a promise that is resolved when scrolling is complete */ Grid.prototype.scrollToIfNecessary = function (gridRow, gridCol) { var self = this; var scrollEvent = new ScrollEvent(self, 'uiGrid.scrollToIfNecessary'); // Alias the visible row and column caches var visRowCache = self.renderContainers.body.visibleRowCache; var visColCache = self.renderContainers.body.visibleColumnCache; /*-- Get the top, left, right, and bottom "scrolled" edges of the grid --*/ // The top boundary is the current Y scroll position PLUS the header height, because the header can obscure rows when the grid is scrolled downwards var topBound = self.renderContainers.body.prevScrollTop + self.headerHeight; // Don't the let top boundary be less than 0 topBound = (topBound < 0) ? 0 : topBound; // The left boundary is the current X scroll position var leftBound = self.renderContainers.body.prevScrollLeft; // The bottom boundary is the current Y scroll position, plus the height of the grid, but minus the header height. // Basically this is the viewport height added on to the scroll position var bottomBound = self.renderContainers.body.prevScrollTop + self.gridHeight - self.renderContainers.body.headerHeight - self.footerHeight - self.scrollbarWidth; // If there's a horizontal scrollbar, remove its height from the bottom boundary, otherwise we'll be letting it obscure rows //if (self.horizontalScrollbarHeight) { // bottomBound = bottomBound - self.horizontalScrollbarHeight; //} // The right position is the current X scroll position minus the grid width var rightBound = self.renderContainers.body.prevScrollLeft + Math.ceil(self.gridWidth); // If there's a vertical scrollbar, subtract it from the right boundary or we'll allow it to obscure cells //if (self.verticalScrollbarWidth) { // rightBound = rightBound - self.verticalScrollbarWidth; //} // We were given a row to scroll to if (gridRow !== null) { // This is the index of the row we want to scroll to, within the list of rows that can be visible var seekRowIndex = visRowCache.indexOf(gridRow); // Total vertical scroll length of the grid var scrollLength = (self.renderContainers.body.getCanvasHeight() - self.renderContainers.body.getViewportHeight()); // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row //if (self.horizontalScrollbarHeight && self.horizontalScrollbarHeight > 0) { // scrollLength = scrollLength + self.horizontalScrollbarHeight; //} // This is the minimum amount of pixels we need to scroll vertical in order to see this row. var pixelsToSeeRow = ((seekRowIndex + 1) * self.options.rowHeight); // Don't let the pixels required to see the row be less than zero pixelsToSeeRow = (pixelsToSeeRow < 0) ? 0 : pixelsToSeeRow; var scrollPixels, percentage; // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self... if (pixelsToSeeRow < topBound) { // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\ // to get the full position we need scrollPixels = self.renderContainers.body.prevScrollTop - (topBound - pixelsToSeeRow); // Turn the scroll position into a percentage and make it an argument for a scroll event percentage = scrollPixels / scrollLength; scrollEvent.y = { percentage: percentage }; } // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self... else if (pixelsToSeeRow > bottomBound) { // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position // to get the full position we need scrollPixels = pixelsToSeeRow - bottomBound + self.renderContainers.body.prevScrollTop; // Turn the scroll position into a percentage and make it an argument for a scroll event percentage = scrollPixels / scrollLength; scrollEvent.y = { percentage: percentage }; } } // We were given a column to scroll to if (gridCol !== null) { // This is the index of the row we want to scroll to, within the list of rows that can be visible var seekColumnIndex = visColCache.indexOf(gridCol); // Total vertical scroll length of the grid var horizScrollLength = (self.renderContainers.body.getCanvasWidth() - self.renderContainers.body.getViewportWidth()); // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row // if (self.verticalScrollbarWidth && self.verticalScrollbarWidth > 0) { // horizScrollLength = horizScrollLength + self.verticalScrollbarWidth; // } // This is the minimum amount of pixels we need to scroll vertical in order to see this column var columnLeftEdge = 0; for (var i = 0; i < seekColumnIndex; i++) { var col = visColCache[i]; columnLeftEdge += col.drawnWidth; } columnLeftEdge = (columnLeftEdge < 0) ? 0 : columnLeftEdge; var columnRightEdge = columnLeftEdge + gridCol.drawnWidth; // Don't let the pixels required to see the column be less than zero columnRightEdge = (columnRightEdge < 0) ? 0 : columnRightEdge; var horizScrollPixels, horizPercentage; // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self... if (columnLeftEdge < leftBound) { // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\ // to get the full position we need horizScrollPixels = self.renderContainers.body.prevScrollLeft - (leftBound - columnLeftEdge); // Turn the scroll position into a percentage and make it an argument for a scroll event horizPercentage = horizScrollPixels / horizScrollLength; horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage; scrollEvent.x = { percentage: horizPercentage }; } // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self... else if (columnRightEdge > rightBound) { // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position // to get the full position we need horizScrollPixels = columnRightEdge - rightBound + self.renderContainers.body.prevScrollLeft; // Turn the scroll position into a percentage and make it an argument for a scroll event horizPercentage = horizScrollPixels / horizScrollLength; horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage; scrollEvent.x = { percentage: horizPercentage }; } } var deferred = $q.defer(); // If we need to scroll on either the x or y axes, fire a scroll event if (scrollEvent.y || scrollEvent.x) { scrollEvent.withDelay = false; self.scrollContainers('',scrollEvent); var dereg = self.api.core.on.scrollEnd(null,function() { deferred.resolve(scrollEvent); dereg(); }); } else { deferred.resolve(); } return deferred.promise; }; /** * @ngdoc method * @methodOf ui.grid.class:Grid * @name scrollTo * @description Scroll the grid such that the specified * row and column is in view * @param {object} rowEntity gridOptions.data[] array instance to make visible * @param {object} colDef to make visible * @returns {promise} a promise that is resolved after any scrolling is finished */ Grid.prototype.scrollTo = function (rowEntity, colDef) { var gridRow = null, gridCol = null; if (rowEntity !== null && typeof(rowEntity) !== 'undefined' ) { gridRow = this.getRow(rowEntity); } if (colDef !== null && typeof(colDef) !== 'undefined' ) { gridCol = this.getColumn(colDef.name ? colDef.name : colDef.field); } return this.scrollToIfNecessary(gridRow, gridCol); }; /** * @ngdoc function * @name clearAllFilters * @methodOf ui.grid.class:Grid * @description Clears all filters and optionally refreshes the visible rows. * @param {object} refreshRows Defaults to true. * @param {object} clearConditions Defaults to false. * @param {object} clearFlags Defaults to false. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. */ Grid.prototype.clearAllFilters = function clearAllFilters(refreshRows, clearConditions, clearFlags) { // Default `refreshRows` to true because it will be the most commonly desired behaviour. if (refreshRows === undefined) { refreshRows = true; } if (clearConditions === undefined) { clearConditions = false; } if (clearFlags === undefined) { clearFlags = false; } this.columns.forEach(function(column) { column.filters.forEach(function(filter) { filter.term = undefined; if (clearConditions) { filter.condition = undefined; } if (clearFlags) { filter.flags = undefined; } }); }); if (refreshRows) { return this.refreshRows(); } }; // Blatantly stolen from Angular as it isn't exposed (yet? 2.0?) function RowHashMap() {} RowHashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[this.grid.options.rowIdentity(key)] = value; }, /** * @param key * @returns {Object} the value for the key */ get: function(key) { return this[this.grid.options.rowIdentity(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = this.grid.options.rowIdentity(key)]; delete this[key]; return value; } }; return Grid; }]); })(); (function () { angular.module('ui.grid') .factory('GridApi', ['$q', '$rootScope', 'gridUtil', 'uiGridConstants', 'GridRow', 'uiGridGridMenuService', function ($q, $rootScope, gridUtil, uiGridConstants, GridRow, uiGridGridMenuService) { /** * @ngdoc function * @name ui.grid.class:GridApi * @description GridApi provides the ability to register public methods events inside the grid and allow * for other components to use the api via featureName.raise.methodName and featureName.on.eventName(function(args){}. * <br/> * To listen to events, you must add a callback to gridOptions.onRegisterApi * <pre> * $scope.gridOptions.onRegisterApi = function(gridApi){ * gridApi.cellNav.on.navigate($scope,function(newRowCol, oldRowCol){ * $log.log('navigation event'); * }); * }; * </pre> * @param {object} grid grid that owns api */ var GridApi = function GridApi(grid) { this.grid = grid; this.listeners = []; /** * @ngdoc function * @name renderingComplete * @methodOf ui.grid.core.api:PublicApi * @description Rendering is complete, called at the same * time as `onRegisterApi`, but provides a way to obtain * that same event within features without stopping end * users from getting at the onRegisterApi method. * * Included in gridApi so that it's always there - otherwise * there is still a timing problem with when a feature can * call this. * * @param {GridApi} gridApi the grid api, as normally * returned in the onRegisterApi method * * @example * <pre> * gridApi.core.on.renderingComplete( grid ); * </pre> */ this.registerEvent( 'core', 'renderingComplete' ); /** * @ngdoc event * @name filterChanged * @eventOf ui.grid.core.api:PublicApi * @description is raised after the filter is changed. The nature * of the watch expression doesn't allow notification of what changed, * so the receiver of this event will need to re-extract the filter * conditions from the columns. * */ this.registerEvent( 'core', 'filterChanged' ); /** * @ngdoc function * @name setRowInvisible * @methodOf ui.grid.core.api:PublicApi * @description Sets an override on the row to make it always invisible, * which will override any filtering or other visibility calculations. * If the row is currently visible then sets it to invisible and calls * both grid refresh and emits the rowsVisibleChanged event * @param {object} rowEntity gridOptions.data[] array instance */ this.registerMethod( 'core', 'setRowInvisible', GridRow.prototype.setRowInvisible ); /** * @ngdoc function * @name clearRowInvisible * @methodOf ui.grid.core.api:PublicApi * @description Clears any override on visibility for the row so that it returns to * using normal filtering and other visibility calculations. * If the row is currently invisible then sets it to visible and calls * both grid refresh and emits the rowsVisibleChanged event * TODO: if a filter is active then we can't just set it to visible? * @param {object} rowEntity gridOptions.data[] array instance */ this.registerMethod( 'core', 'clearRowInvisible', GridRow.prototype.clearRowInvisible ); /** * @ngdoc function * @name getVisibleRows * @methodOf ui.grid.core.api:PublicApi * @description Returns all visible rows * @param {Grid} grid the grid you want to get visible rows from * @returns {array} an array of gridRow */ this.registerMethod( 'core', 'getVisibleRows', this.grid.getVisibleRows ); /** * @ngdoc event * @name rowsVisibleChanged * @eventOf ui.grid.core.api:PublicApi * @description is raised after the rows that are visible * change. The filtering is zero-based, so it isn't possible * to say which rows changed (unlike in the selection feature). * We can plausibly know which row was changed when setRowInvisible * is called, but in that situation the user already knows which row * they changed. When a filter runs we don't know what changed, * and that is the one that would have been useful. * */ this.registerEvent( 'core', 'rowsVisibleChanged' ); /** * @ngdoc event * @name rowsRendered * @eventOf ui.grid.core.api:PublicApi * @description is raised after the cache of visible rows is changed. */ this.registerEvent( 'core', 'rowsRendered' ); /** * @ngdoc event * @name scrollBegin * @eventOf ui.grid.core.api:PublicApi * @description is raised when scroll begins. Is throttled, so won't be raised too frequently */ this.registerEvent( 'core', 'scrollBegin' ); /** * @ngdoc event * @name scrollEnd * @eventOf ui.grid.core.api:PublicApi * @description is raised when scroll has finished. Is throttled, so won't be raised too frequently */ this.registerEvent( 'core', 'scrollEnd' ); /** * @ngdoc event * @name canvasHeightChanged * @eventOf ui.grid.core.api:PublicApi * @description is raised when the canvas height has changed * <br/> * arguments: oldHeight, newHeight */ this.registerEvent( 'core', 'canvasHeightChanged'); }; /** * @ngdoc function * @name ui.grid.class:suppressEvents * @methodOf ui.grid.class:GridApi * @description Used to execute a function while disabling the specified event listeners. * Disables the listenerFunctions, executes the callbackFn, and then enables * the listenerFunctions again * @param {object} listenerFuncs listenerFunc or array of listenerFuncs to suppress. These must be the same * functions that were used in the .on.eventName method * @param {object} callBackFn function to execute * @example * <pre> * var navigate = function (newRowCol, oldRowCol){ * //do something on navigate * } * * gridApi.cellNav.on.navigate(scope,navigate); * * * //call the scrollTo event and suppress our navigate listener * //scrollTo will still raise the event for other listeners * gridApi.suppressEvents(navigate, function(){ * gridApi.cellNav.scrollTo(aRow, aCol); * }); * * </pre> */ GridApi.prototype.suppressEvents = function (listenerFuncs, callBackFn) { var self = this; var listeners = angular.isArray(listenerFuncs) ? listenerFuncs : [listenerFuncs]; //find all registered listeners var foundListeners = self.listeners.filter(function(listener) { return listeners.some(function(l) { return listener.handler === l; }); }); //deregister all the listeners foundListeners.forEach(function(l){ l.dereg(); }); callBackFn(); //reregister all the listeners foundListeners.forEach(function(l){ l.dereg = registerEventWithAngular(l.eventId, l.handler, self.grid, l._this); }); }; /** * @ngdoc function * @name registerEvent * @methodOf ui.grid.class:GridApi * @description Registers a new event for the given feature. The event will get a * .raise and .on prepended to it * <br> * .raise.eventName() - takes no arguments * <br/> * <br/> * .on.eventName(scope, callBackFn, _this) * <br/> * scope - a scope reference to add a deregister call to the scopes .$on('destroy'). Scope is optional and can be a null value, * but in this case you must deregister it yourself via the returned deregister function * <br/> * callBackFn - The function to call * <br/> * _this - optional this context variable for callbackFn. If omitted, grid.api will be used for the context * <br/> * .on.eventName returns a dereg funtion that will remove the listener. It's not necessary to use it as the listener * will be removed when the scope is destroyed. * @param {string} featureName name of the feature that raises the event * @param {string} eventName name of the event */ GridApi.prototype.registerEvent = function (featureName, eventName) { var self = this; if (!self[featureName]) { self[featureName] = {}; } var feature = self[featureName]; if (!feature.on) { feature.on = {}; feature.raise = {}; } var eventId = self.grid.id + featureName + eventName; // gridUtil.logDebug('Creating raise event method ' + featureName + '.raise.' + eventName); feature.raise[eventName] = function () { $rootScope.$emit.apply($rootScope, [eventId].concat(Array.prototype.slice.call(arguments))); }; // gridUtil.logDebug('Creating on event method ' + featureName + '.on.' + eventName); feature.on[eventName] = function (scope, handler, _this) { if ( scope !== null && typeof(scope.$on) === 'undefined' ){ gridUtil.logError('asked to listen on ' + featureName + '.on.' + eventName + ' but scope wasn\'t passed in the input parameters. It is legitimate to pass null, but you\'ve passed something else, so you probably forgot to provide scope rather than did it deliberately, not registering'); return; } var deregAngularOn = registerEventWithAngular(eventId, handler, self.grid, _this); //track our listener so we can turn off and on var listener = {handler: handler, dereg: deregAngularOn, eventId: eventId, scope: scope, _this:_this}; self.listeners.push(listener); var removeListener = function(){ listener.dereg(); var index = self.listeners.indexOf(listener); self.listeners.splice(index,1); }; //destroy tracking when scope is destroyed if (scope) { scope.$on('$destroy', function() { removeListener(); }); } return removeListener; }; }; function registerEventWithAngular(eventId, handler, grid, _this) { return $rootScope.$on(eventId, function (event) { var args = Array.prototype.slice.call(arguments); args.splice(0, 1); //remove evt argument handler.apply(_this ? _this : grid.api, args); }); } /** * @ngdoc function * @name registerEventsFromObject * @methodOf ui.grid.class:GridApi * @description Registers features and events from a simple objectMap. * eventObjectMap must be in this format (multiple features allowed) * <pre> * {featureName: * { * eventNameOne:function(args){}, * eventNameTwo:function(args){} * } * } * </pre> * @param {object} eventObjectMap map of feature/event names */ GridApi.prototype.registerEventsFromObject = function (eventObjectMap) { var self = this; var features = []; angular.forEach(eventObjectMap, function (featProp, featPropName) { var feature = {name: featPropName, events: []}; angular.forEach(featProp, function (prop, propName) { feature.events.push(propName); }); features.push(feature); }); features.forEach(function (feature) { feature.events.forEach(function (event) { self.registerEvent(feature.name, event); }); }); }; /** * @ngdoc function * @name registerMethod * @methodOf ui.grid.class:GridApi * @description Registers a new event for the given feature * @param {string} featureName name of the feature * @param {string} methodName name of the method * @param {object} callBackFn function to execute * @param {object} _this binds callBackFn 'this' to _this. Defaults to gridApi.grid */ GridApi.prototype.registerMethod = function (featureName, methodName, callBackFn, _this) { if (!this[featureName]) { this[featureName] = {}; } var feature = this[featureName]; feature[methodName] = gridUtil.createBoundedWrapper(_this || this.grid, callBackFn); }; /** * @ngdoc function * @name registerMethodsFromObject * @methodOf ui.grid.class:GridApi * @description Registers features and methods from a simple objectMap. * eventObjectMap must be in this format (multiple features allowed) * <br> * {featureName: * { * methodNameOne:function(args){}, * methodNameTwo:function(args){} * } * @param {object} eventObjectMap map of feature/event names * @param {object} _this binds this to _this for all functions. Defaults to gridApi.grid */ GridApi.prototype.registerMethodsFromObject = function (methodMap, _this) { var self = this; var features = []; angular.forEach(methodMap, function (featProp, featPropName) { var feature = {name: featPropName, methods: []}; angular.forEach(featProp, function (prop, propName) { feature.methods.push({name: propName, fn: prop}); }); features.push(feature); }); features.forEach(function (feature) { feature.methods.forEach(function (method) { self.registerMethod(feature.name, method.name, method.fn, _this); }); }); }; return GridApi; }]); })(); (function(){ angular.module('ui.grid') .factory('GridColumn', ['gridUtil', 'uiGridConstants', 'i18nService', function(gridUtil, uiGridConstants, i18nService) { /** * ****************************************************************************************** * PaulL1: Ugly hack here in documentation. These properties are clearly properties of GridColumn, * and need to be noted as such for those extending and building ui-grid itself. * However, from an end-developer perspective, they interact with all these through columnDefs, * and they really need to be documented there. I feel like they're relatively static, and * I can't find an elegant way for ngDoc to reference to both....so I've duplicated each * comment block. Ugh. * */ /** * @ngdoc property * @name name * @propertyOf ui.grid.class:GridColumn * @description (mandatory) each column should have a name, although for backward * compatibility with 2.x name can be omitted if field is present * */ /** * @ngdoc property * @name name * @propertyOf ui.grid.class:GridOptions.columnDef * @description (mandatory) each column should have a name, although for backward * compatibility with 2.x name can be omitted if field is present * */ /** * @ngdoc property * @name displayName * @propertyOf ui.grid.class:GridColumn * @description Column name that will be shown in the header. If displayName is not * provided then one is generated using the name. * */ /** * @ngdoc property * @name displayName * @propertyOf ui.grid.class:GridOptions.columnDef * @description Column name that will be shown in the header. If displayName is not * provided then one is generated using the name. * */ /** * @ngdoc property * @name field * @propertyOf ui.grid.class:GridColumn * @description field must be provided if you wish to bind to a * property in the data source. Should be an angular expression that evaluates against grid.options.data * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>. * See the angular docs on binding expressions. * */ /** * @ngdoc property * @name field * @propertyOf ui.grid.class:GridOptions.columnDef * @description field must be provided if you wish to bind to a * property in the data source. Should be an angular expression that evaluates against grid.options.data * array element. Can be a complex expression: <code>employee.address.city</code>, or can be a function: <code>employee.getFullAddress()</code>. * See the angular docs on binding expressions. * */ /** * @ngdoc property * @name filter * @propertyOf ui.grid.class:GridColumn * @description Filter on this column. * @example * <pre>{ term: 'text', condition: uiGridConstants.filter.STARTS_WITH, placeholder: 'type to filter...', flags: { caseSensitive: false }, type: uiGridConstants.filter.SELECT, [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] }</pre> * */ /** * @ngdoc object * @name ui.grid.class:GridColumn * @description Represents the viewModel for each column. Any state or methods needed for a Grid Column * are defined on this prototype * @param {ColumnDef} colDef the column def to associate with this column * @param {number} uid the unique and immutable uid we'd like to allocate to this column * @param {Grid} grid the grid we'd like to create this column in */ function GridColumn(colDef, uid, grid) { var self = this; self.grid = grid; self.uid = uid; self.updateColumnDef(colDef, true); /** * @ngdoc function * @name hideColumn * @methodOf ui.grid.class:GridColumn * @description Hides the column by setting colDef.visible = false */ GridColumn.prototype.hideColumn = function() { this.colDef.visible = false; }; self.aggregationValue = undefined; // The footer cell registers to listen for the rowsRendered event, and calls this. Needed to be // in something with a scope so that the dereg would get called self.updateAggregationValue = function() { // gridUtil.logDebug('getAggregationValue for Column ' + self.colDef.name); /** * @ngdoc property * @name aggregationType * @propertyOf ui.grid.class:GridOptions.columnDef * @description The aggregation that you'd like to show in the columnFooter for this * column. Valid values are in uiGridConstants, and currently include `uiGridConstants.aggregationTypes.count`, * `uiGridConstants.aggregationTypes.sum`, `uiGridConstants.aggregationTypes.avg`, `uiGridConstants.aggregationTypes.min`, * `uiGridConstants.aggregationTypes.max`. * * You can also provide a function as the aggregation type, in this case your function needs to accept the full * set of visible rows, and return a value that should be shown */ if (!self.aggregationType) { self.aggregationValue = undefined; return; } var result = 0; var visibleRows = self.grid.getVisibleRows(); var cellValues = function(){ var values = []; visibleRows.forEach(function (row) { var cellValue = self.grid.getCellValue(row, self); var cellNumber = Number(cellValue); if (!isNaN(cellNumber)) { values.push(cellNumber); } }); return values; }; if (angular.isFunction(self.aggregationType)) { self.aggregationValue = self.aggregationType(visibleRows, self); } else if (self.aggregationType === uiGridConstants.aggregationTypes.count) { self.aggregationValue = self.grid.getVisibleRowCount(); } else if (self.aggregationType === uiGridConstants.aggregationTypes.sum) { cellValues().forEach(function (value) { result += value; }); self.aggregationValue = result; } else if (self.aggregationType === uiGridConstants.aggregationTypes.avg) { cellValues().forEach(function (value) { result += value; }); result = result / cellValues().length; self.aggregationValue = result; } else if (self.aggregationType === uiGridConstants.aggregationTypes.min) { self.aggregationValue = Math.min.apply(null, cellValues()); } else if (self.aggregationType === uiGridConstants.aggregationTypes.max) { self.aggregationValue = Math.max.apply(null, cellValues()); } else { self.aggregationValue = '\u00A0'; } }; // var throttledUpdateAggregationValue = gridUtil.throttle(updateAggregationValue, self.grid.options.aggregationCalcThrottle, { trailing: true, context: self.name }); /** * @ngdoc function * @name getAggregationValue * @methodOf ui.grid.class:GridColumn * @description gets the aggregation value based on the aggregation type for this column. * Debounced using scrollDebounce option setting */ this.getAggregationValue = function() { // if (!self.grid.isScrollingVertically && !self.grid.isScrollingHorizontally) { // throttledUpdateAggregationValue(); // } return self.aggregationValue; }; } /** * @ngdoc method * @methodOf ui.grid.class:GridColumn * @name setPropertyOrDefault * @description Sets a property on the column using the passed in columnDef, and * setting the defaultValue if the value cannot be found on the colDef * @param {ColumnDef} colDef the column def to look in for the property value * @param {string} propName the property name we'd like to set * @param {object} defaultValue the value to use if the colDef doesn't provide the setting */ GridColumn.prototype.setPropertyOrDefault = function (colDef, propName, defaultValue) { var self = this; // Use the column definition filter if we were passed it if (typeof(colDef[propName]) !== 'undefined' && colDef[propName]) { self[propName] = colDef[propName]; } // Otherwise use our own if it's set else if (typeof(self[propName]) !== 'undefined') { self[propName] = self[propName]; } // Default to empty object for the filter else { self[propName] = defaultValue ? defaultValue : {}; } }; /** * @ngdoc property * @name width * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets the column width. Can be either * a number or a percentage, or an * for auto. * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', width: 100}, * { field: 'field2', width: '20%'}, * { field: 'field3', width: '*' }]; </pre> * */ /** * @ngdoc property * @name minWidth * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets the minimum column width. Should be a number. * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', minWidth: 100}]; </pre> * */ /** * @ngdoc property * @name maxWidth * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets the maximum column width. Should be a number. * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', maxWidth: 100}]; </pre> * */ /** * @ngdoc property * @name visible * @propertyOf ui.grid.class:GridOptions.columnDef * @description sets whether or not the column is visible * </br>Default is true * @example * <pre> $scope.gridOptions.columnDefs = [ * { field: 'field1', visible: true}, * { field: 'field2', visible: false } * ]; </pre> * */ /** * @ngdoc property * @name sort * @propertyOf ui.grid.class:GridOptions.columnDef * @description An object of sort information, attributes are: * * - direction: values are uiGridConstants.ASC or uiGridConstants.DESC * - ignoreSort: if set to true this sort is ignored (used by tree to manipulate the sort functionality) * @example * <pre> $scope.gridOptions.columnDefs = [ { field: 'field1', sort: { direction: uiGridConstants.ASC, ignoreSort: true }}] </pre> */ /** * @ngdoc property * @name sortingAlgorithm * @propertyOf ui.grid.class:GridColumn * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function. * */ /** * @ngdoc property * @name sortingAlgorithm * @propertyOf ui.grid.class:GridOptions.columnDef * @description Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function. * */ /** * @ngdoc array * @name filters * @propertyOf ui.grid.class:GridOptions.columnDef * @description Specify multiple filter fields. * @example * <pre>$scope.gridOptions.columnDefs = [ * { * field: 'field1', filters: [ * { * term: 'aa', * condition: uiGridConstants.filter.STARTS_WITH, * placeholder: 'starts with...', * flags: { caseSensitive: false }, * type: uiGridConstants.filter.SELECT, * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] * }, * { * condition: uiGridConstants.filter.ENDS_WITH, * placeholder: 'ends with...' * } * ] * } * ]; </pre> * * */ /** * @ngdoc array * @name filters * @propertyOf ui.grid.class:GridColumn * @description Filters for this column. Includes 'term' property bound to filter input elements. * @example * <pre>[ * { * term: 'foo', // ngModel for <input> * condition: uiGridConstants.filter.STARTS_WITH, * placeholder: 'starts with...', * flags: { caseSensitive: false }, * type: uiGridConstants.filter.SELECT, * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ] * }, * { * term: 'baz', * condition: uiGridConstants.filter.ENDS_WITH, * placeholder: 'ends with...' * } * ] </pre> * * */ /** * @ngdoc array * @name menuItems * @propertyOf ui.grid.class:GridOptions.columnDef * @description used to add menu items to a column. Refer to the tutorial on this * functionality. A number of settings are supported: * * - title: controls the title that is displayed in the menu * - icon: the icon shown alongside that title * - action: the method to call when the menu is clicked * - shown: a function to evaluate to determine whether or not to show the item * - active: a function to evaluate to determine whether or not the item is currently selected * - context: context to pass to the action function, available in this.context in your handler * - leaveOpen: if set to true, the menu should stay open after the action, defaults to false * @example * <pre> $scope.gridOptions.columnDefs = [ * { field: 'field1', menuItems: [ * { * title: 'Outer Scope Alert', * icon: 'ui-grid-icon-info-circled', * action: function($event) { * this.context.blargh(); // $scope.blargh() would work too, this is just an example * }, * shown: function() { return true; }, * active: function() { return true; }, * context: $scope * }, * { * title: 'Grid ID', * action: function() { * alert('Grid ID: ' + this.grid.id); * } * } * ] }]; </pre> * */ /** * @ngdoc method * @methodOf ui.grid.class:GridColumn * @name updateColumnDef * @description Moves settings from the columnDef down onto the column, * and sets properties as appropriate * @param {ColumnDef} colDef the column def to look in for the property value * @param {boolean} isNew whether the column is being newly created, if not * we're updating an existing column, and some items such as the sort shouldn't * be copied down */ GridColumn.prototype.updateColumnDef = function(colDef, isNew) { var self = this; self.colDef = colDef; if (colDef.name === undefined) { throw new Error('colDef.name is required for column at index ' + self.grid.options.columnDefs.indexOf(colDef)); } self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName; var colDefWidth = colDef.width; var parseErrorMsg = "Cannot parse column width '" + colDefWidth + "' for column named '" + colDef.name + "'"; if (!angular.isString(colDefWidth) && !angular.isNumber(colDefWidth)) { self.width = '*'; } else if (angular.isString(colDefWidth)) { // See if it ends with a percent if (gridUtil.endsWith(colDefWidth, '%')) { // If so we should be able to parse the non-percent-sign part to a number var percentStr = colDefWidth.replace(/%/g, ''); var percent = parseInt(percentStr, 10); if (isNaN(percent)) { throw new Error(parseErrorMsg); } self.width = colDefWidth; } // And see if it's a number string else if (colDefWidth.match(/^(\d+)$/)) { self.width = parseInt(colDefWidth.match(/^(\d+)$/)[1], 10); } // Otherwise it should be a string of asterisks else if (colDefWidth.match(/^\*+$/)) { self.width = colDefWidth; } // No idea, throw an Error else { throw new Error(parseErrorMsg); } } // Is a number, use it as the width else { self.width = colDefWidth; } self.minWidth = !colDef.minWidth ? 30 : colDef.minWidth; self.maxWidth = !colDef.maxWidth ? 9000 : colDef.maxWidth; //use field if it is defined; name if it is not self.field = (colDef.field === undefined) ? colDef.name : colDef.field; if ( typeof( self.field ) !== 'string' ){ gridUtil.logError( 'Field is not a string, this is likely to break the code, Field is: ' + self.field ); } self.name = colDef.name; // Use colDef.displayName as long as it's not undefined, otherwise default to the field name self.displayName = (colDef.displayName === undefined) ? gridUtil.readableColumnName(colDef.name) : colDef.displayName; //self.originalIndex = index; self.aggregationType = angular.isDefined(colDef.aggregationType) ? colDef.aggregationType : null; self.footerCellTemplate = angular.isDefined(colDef.footerCellTemplate) ? colDef.footerCellTemplate : null; /** * @ngdoc property * @name cellTooltip * @propertyOf ui.grid.class:GridOptions.columnDef * @description Whether or not to show a tooltip when a user hovers over the cell. * If set to false, no tooltip. If true, the cell value is shown in the tooltip (useful * if you have long values in your cells), if a function then that function is called * passing in the row and the col `cellTooltip( row, col )`, and the return value is shown in the tooltip, * if it is a static string then displays that static string. * * Defaults to false * */ if ( typeof(colDef.cellTooltip) === 'undefined' || colDef.cellTooltip === false ) { self.cellTooltip = false; } else if ( colDef.cellTooltip === true ){ self.cellTooltip = function(row, col) { return self.grid.getCellValue( row, col ); }; } else if (typeof(colDef.cellTooltip) === 'function' ){ self.cellTooltip = colDef.cellTooltip; } else { self.cellTooltip = function ( row, col ){ return col.colDef.cellTooltip; }; } /** * @ngdoc property * @name headerTooltip * @propertyOf ui.grid.class:GridOptions.columnDef * @description Whether or not to show a tooltip when a user hovers over the header cell. * If set to false, no tooltip. If true, the displayName is shown in the tooltip (useful * if you have long values in your headers), if a function then that function is called * passing in the row and the col `headerTooltip( col )`, and the return value is shown in the tooltip, * if a static string then shows that static string. * * Defaults to false * */ if ( typeof(colDef.headerTooltip) === 'undefined' || colDef.headerTooltip === false ) { self.headerTooltip = false; } else if ( colDef.headerTooltip === true ){ self.headerTooltip = function(col) { return col.displayName; }; } else if (typeof(colDef.headerTooltip) === 'function' ){ self.headerTooltip = colDef.headerTooltip; } else { self.headerTooltip = function ( col ) { return col.colDef.headerTooltip; }; } /** * @ngdoc property * @name footerCellClass * @propertyOf ui.grid.class:GridOptions.columnDef * @description footerCellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name * */ self.footerCellClass = colDef.footerCellClass; /** * @ngdoc property * @name cellClass * @propertyOf ui.grid.class:GridOptions.columnDef * @description cellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name * */ self.cellClass = colDef.cellClass; /** * @ngdoc property * @name headerCellClass * @propertyOf ui.grid.class:GridOptions.columnDef * @description headerCellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) that returns a class name * */ self.headerCellClass = colDef.headerCellClass; /** * @ngdoc property * @name cellFilter * @propertyOf ui.grid.class:GridOptions.columnDef * @description cellFilter is a filter to apply to the content of each cell * @example * <pre> * gridOptions.columnDefs[0].cellFilter = 'date' * */ self.cellFilter = colDef.cellFilter ? colDef.cellFilter : ""; /** * @ngdoc boolean * @name sortCellFiltered * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before * sorting the data. Note that when using this option uiGrid will assume that the displayed value is * a string, and use the {@link ui.grid.class:RowSorter#sortAlpha sortAlpha} `sortFn`. It is possible * to return a non-string value from an angularjs filter, in which case you should define a {@link ui.grid.class:GridOptions.columnDef#sortingAlgorithm sortingAlgorithm} * for the column which hanldes the returned type. You may specify one of the `sortingAlgorithms` * found in the {@link ui.grid.RowSorter rowSorter} service. */ self.sortCellFiltered = colDef.sortCellFiltered ? true : false; /** * @ngdoc boolean * @name filterCellFiltered * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) False by default. When `true` uiGrid will apply the cellFilter before * applying "search" `filters`. */ self.filterCellFiltered = colDef.filterCellFiltered ? true : false; /** * @ngdoc property * @name headerCellFilter * @propertyOf ui.grid.class:GridOptions.columnDef * @description headerCellFilter is a filter to apply to the content of the column header * @example * <pre> * gridOptions.columnDefs[0].headerCellFilter = 'translate' * */ self.headerCellFilter = colDef.headerCellFilter ? colDef.headerCellFilter : ""; /** * @ngdoc property * @name footerCellFilter * @propertyOf ui.grid.class:GridOptions.columnDef * @description footerCellFilter is a filter to apply to the content of the column footer * @example * <pre> * gridOptions.columnDefs[0].footerCellFilter = 'date' * */ self.footerCellFilter = colDef.footerCellFilter ? colDef.footerCellFilter : ""; self.visible = gridUtil.isNullOrUndefined(colDef.visible) || colDef.visible; self.headerClass = colDef.headerClass; //self.cursor = self.sortable ? 'pointer' : 'default'; // Turn on sorting by default self.enableSorting = typeof(colDef.enableSorting) !== 'undefined' ? colDef.enableSorting : true; self.sortingAlgorithm = colDef.sortingAlgorithm; /** * @ngdoc boolean * @name suppressRemoveSort * @propertyOf ui.grid.class:GridOptions.columnDef * @description (optional) False by default. When enabled, this setting hides the removeSort option * in the menu, and prevents users from manually removing the sort */ if ( typeof(self.suppressRemoveSort) === 'undefined'){ self.suppressRemoveSort = typeof(colDef.suppressRemoveSort) !== 'undefined' ? colDef.suppressRemoveSort : false; } /** * @ngdoc property * @name enableFiltering * @propertyOf ui.grid.class:GridOptions.columnDef * @description turn off filtering for an individual column, where * you've turned on filtering for the overall grid * @example * <pre> * gridOptions.columnDefs[0].enableFiltering = false; * */ // Turn on filtering by default (it's disabled by default at the Grid level) self.enableFiltering = typeof(colDef.enableFiltering) !== 'undefined' ? colDef.enableFiltering : true; // self.menuItems = colDef.menuItems; self.setPropertyOrDefault(colDef, 'menuItems', []); // Use the column definition sort if we were passed it, but only if this is a newly added column if ( isNew ){ self.setPropertyOrDefault(colDef, 'sort'); } // Set up default filters array for when one is not provided. // In other words, this (in column def): // // filter: { term: 'something', flags: {}, condition: [CONDITION] } // // is just shorthand for this: // // filters: [{ term: 'something', flags: {}, condition: [CONDITION] }] // var defaultFilters = []; if (colDef.filter) { defaultFilters.push(colDef.filter); } else if ( colDef.filters ){ defaultFilters = colDef.filters; } else { // Add an empty filter definition object, which will // translate to a guessed condition and no pre-populated // value for the filter <input>. defaultFilters.push({}); } /** * @ngdoc property * @name filter * @propertyOf ui.grid.class:GridOptions.columnDef * @description Specify a single filter field on this column. * * A filter consists of a condition, a term, and a placeholder: * * - condition defines how rows are chosen as matching the filter term. This can be set to * one of the constants in uiGridConstants.filter, or you can supply a custom filter function * that gets passed the following arguments: [searchTerm, cellValue, row, column]. * - term: If set, the filter field will be pre-populated * with this value. * - placeholder: String that will be set to the `<input>.placeholder` attribute. * - noTerm: set this to true if you have defined a custom function in condition, and * your custom function doesn't require a term (so it can run even when the term is null) * - flags: only flag currently available is `caseSensitive`, set to false if you don't want * case sensitive matching * - type: defaults to uiGridConstants.filter.INPUT, which gives a text box. If set to uiGridConstants.filter.SELECT * then a select box will be shown with options selectOptions * - selectOptions: options in the format `[ { value: 1, label: 'male' }]`. No i18n filter is provided, you need * to perform the i18n on the values before you provide them * - disableCancelFilterButton: defaults to false. If set to true then the 'x' button that cancels/clears the filter * will not be shown. * @example * <pre>$scope.gridOptions.columnDefs = [ * { * field: 'field1', * filter: { * term: 'xx', * condition: uiGridConstants.filter.STARTS_WITH, * placeholder: 'starts with...', * flags: { caseSensitive: false }, * type: uiGridConstants.filter.SELECT, * selectOptions: [ { value: 1, label: 'male' }, { value: 2, label: 'female' } ], * disableCancelFilterButton: true * } * } * ]; </pre> * */ /* /* self.filters = [ { term: 'search term' condition: uiGridConstants.filter.CONTAINS, placeholder: 'my placeholder', flags: { caseSensitive: true } } ] */ // Only set filter if this is a newly added column, if we're updating an existing // column then we don't want to put the default filter back if the user may have already // removed it. // However, we do want to keep the settings if they change, just not the term if ( isNew ) { self.setPropertyOrDefault(colDef, 'filter'); self.setPropertyOrDefault(colDef, 'filters', defaultFilters); } else if ( self.filters.length === defaultFilters.length ) { self.filters.forEach( function( filter, index ){ if (typeof(defaultFilters[index].placeholder) !== 'undefined') { filter.placeholder = defaultFilters[index].placeholder; } if (typeof(defaultFilters[index].flags) !== 'undefined') { filter.flags = defaultFilters[index].flags; } if (typeof(defaultFilters[index].type) !== 'undefined') { filter.type = defaultFilters[index].type; } if (typeof(defaultFilters[index].selectOptions) !== 'undefined') { filter.selectOptions = defaultFilters[index].selectOptions; } }); } // Remove this column from the grid sorting, include inside build columns so has // access to self - all seems a bit dodgy but doesn't work otherwise so have left // as is GridColumn.prototype.unsort = function () { this.sort = {}; self.grid.api.core.raise.sortChanged( self.grid, self.grid.getColumnSorting() ); }; }; /** * @ngdoc function * @name getColClass * @methodOf ui.grid.class:GridColumn * @description Returns the class name for the column * @param {bool} prefixDot if true, will return .className instead of className */ GridColumn.prototype.getColClass = function (prefixDot) { var cls = uiGridConstants.COL_CLASS_PREFIX + this.uid; return prefixDot ? '.' + cls : cls; }; /** * @ngdoc function * @name isPinnedLeft * @methodOf ui.grid.class:GridColumn * @description Returns true if column is in the left render container */ GridColumn.prototype.isPinnedLeft = function () { return this.renderContainer === 'left'; }; /** * @ngdoc function * @name isPinnedRight * @methodOf ui.grid.class:GridColumn * @description Returns true if column is in the right render container */ GridColumn.prototype.isPinnedRight = function () { return this.renderContainer === 'right'; }; /** * @ngdoc function * @name getColClassDefinition * @methodOf ui.grid.class:GridColumn * @description Returns the class definition for th column */ GridColumn.prototype.getColClassDefinition = function () { return ' .grid' + this.grid.id + ' ' + this.getColClass(true) + ' { min-width: ' + this.drawnWidth + 'px; max-width: ' + this.drawnWidth + 'px; }'; }; /** * @ngdoc function * @name getRenderContainer * @methodOf ui.grid.class:GridColumn * @description Returns the render container object that this column belongs to. * * Columns will be default be in the `body` render container if they aren't allocated to one specifically. */ GridColumn.prototype.getRenderContainer = function getRenderContainer() { var self = this; var containerId = self.renderContainer; if (containerId === null || containerId === '' || containerId === undefined) { containerId = 'body'; } return self.grid.renderContainers[containerId]; }; /** * @ngdoc function * @name showColumn * @methodOf ui.grid.class:GridColumn * @description Makes the column visible by setting colDef.visible = true */ GridColumn.prototype.showColumn = function() { this.colDef.visible = true; }; /** * @ngdoc property * @name aggregationHideLabel * @propertyOf ui.grid.class:GridOptions.columnDef * @description defaults to false, if set to true hides the label text * in the aggregation footer, so only the value is displayed. * */ /** * @ngdoc function * @name getAggregationText * @methodOf ui.grid.class:GridColumn * @description Gets the aggregation label from colDef.aggregationLabel if * specified or by using i18n, including deciding whether or not to display * based on colDef.aggregationHideLabel. * * @param {string} label the i18n lookup value to use for the column label * */ GridColumn.prototype.getAggregationText = function () { var self = this; if ( self.colDef.aggregationHideLabel ){ return ''; } else if ( self.colDef.aggregationLabel ) { return self.colDef.aggregationLabel; } else { switch ( self.colDef.aggregationType ){ case uiGridConstants.aggregationTypes.count: return i18nService.getSafeText('aggregation.count'); case uiGridConstants.aggregationTypes.sum: return i18nService.getSafeText('aggregation.sum'); case uiGridConstants.aggregationTypes.avg: return i18nService.getSafeText('aggregation.avg'); case uiGridConstants.aggregationTypes.min: return i18nService.getSafeText('aggregation.min'); case uiGridConstants.aggregationTypes.max: return i18nService.getSafeText('aggregation.max'); default: return ''; } } }; GridColumn.prototype.getCellTemplate = function () { var self = this; return self.cellTemplatePromise; }; GridColumn.prototype.getCompiledElementFn = function () { var self = this; return self.compiledElementFnDefer.promise; }; return GridColumn; }]); })(); (function(){ angular.module('ui.grid') .factory('GridOptions', ['gridUtil','uiGridConstants', function(gridUtil,uiGridConstants) { /** * @ngdoc function * @name ui.grid.class:GridOptions * @description Default GridOptions class. GridOptions are defined by the application developer and overlaid * over this object. Setting gridOptions within your controller is the most common method for an application * developer to configure the behaviour of their ui-grid * * @example To define your gridOptions within your controller: * <pre>$scope.gridOptions = { * data: $scope.myData, * columnDefs: [ * { name: 'field1', displayName: 'pretty display name' }, * { name: 'field2', visible: false } * ] * };</pre> * * You can then use this within your html template, when you define your grid: * <pre>&lt;div ui-grid="gridOptions"&gt;&lt;/div&gt;</pre> * * To provide default options for all of the grids within your application, use an angular * decorator to modify the GridOptions factory. * <pre> * app.config(function($provide){ * $provide.decorator('GridOptions',function($delegate){ * var gridOptions; * gridOptions = angular.copy($delegate); * gridOptions.initialize = function(options) { * var initOptions; * initOptions = $delegate.initialize(options); * initOptions.enableColumnMenus = false; * return initOptions; * }; * return gridOptions; * }); * }); * </pre> */ return { initialize: function( baseOptions ){ /** * @ngdoc function * @name onRegisterApi * @propertyOf ui.grid.class:GridOptions * @description A callback that returns the gridApi once the grid is instantiated, which is * then used to interact with the grid programatically. * * Note that the gridApi.core.renderingComplete event is identical to this * callback, but has the advantage that it can be called from multiple places * if needed * * @example * <pre> * $scope.gridOptions.onRegisterApi = function ( gridApi ) { * $scope.gridApi = gridApi; * $scope.gridApi.selection.selectAllRows( $scope.gridApi.grid ); * }; * </pre> * */ baseOptions.onRegisterApi = baseOptions.onRegisterApi || angular.noop(); /** * @ngdoc object * @name data * @propertyOf ui.grid.class:GridOptions * @description (mandatory) Array of data to be rendered into the grid, providing the data source or data binding for * the grid. * * Most commonly the data is an array of objects, where each object has a number of attributes. * Each attribute automatically becomes a column in your grid. This array could, for example, be sourced from * an angularJS $resource query request. The array can also contain complex objects, refer the binding tutorial * for examples of that. * * The most flexible usage is to set your data on $scope: * * `$scope.data = data;` * * And then direct the grid to resolve whatever is in $scope.data: * * `$scope.gridOptions.data = 'data';` * * This is the most flexible approach as it allows you to replace $scope.data whenever you feel like it without * getting pointer issues. * * Alternatively you can directly set the data array: * * `$scope.gridOptions.data = [ ];` * or * * `$http.get('/data/100.json') * .success(function(data) { * $scope.myData = data; * $scope.gridOptions.data = $scope.myData; * });` * * Where you do this, you need to take care in updating the data - you can't just update `$scope.myData` to some other * array, you need to update $scope.gridOptions.data to point to that new array as well. * */ baseOptions.data = baseOptions.data || []; /** * @ngdoc array * @name columnDefs * @propertyOf ui.grid.class:GridOptions * @description Array of columnDef objects. Only required property is name. * The individual options available in columnDefs are documented in the * {@link ui.grid.class:GridOptions.columnDef columnDef} section * </br>_field property can be used in place of name for backwards compatibility with 2.x_ * @example * * <pre>var columnDefs = [{name:'field1'}, {name:'field2'}];</pre> * */ baseOptions.columnDefs = baseOptions.columnDefs || []; /** * @ngdoc object * @name ui.grid.class:GridOptions.columnDef * @description Definition / configuration of an individual column, which would typically be * one of many column definitions within the gridOptions.columnDefs array * @example * <pre>{name:'field1', field: 'field1', filter: { term: 'xxx' }}</pre> * */ /** * @ngdoc array * @name excludeProperties * @propertyOf ui.grid.class:GridOptions * @description Array of property names in data to ignore when auto-generating column names. Provides the * inverse of columnDefs - columnDefs is a list of columns to include, excludeProperties is a list of columns * to exclude. * * If columnDefs is defined, this will be ignored. * * Defaults to ['$$hashKey'] */ baseOptions.excludeProperties = baseOptions.excludeProperties || ['$$hashKey']; /** * @ngdoc boolean * @name enableRowHashing * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, this setting allows uiGrid to add * `$$hashKey`-type properties (similar to Angular) to elements in the `data` array. This allows * the grid to maintain state while vastly speeding up the process of altering `data` by adding/moving/removing rows. * * Note that this DOES add properties to your data that you may not want, but they are stripped out when using `angular.toJson()`. IF * you do not want this at all you can disable this setting but you will take a performance hit if you are using large numbers of rows * and are altering the data set often. */ baseOptions.enableRowHashing = baseOptions.enableRowHashing !== false; /** * @ngdoc function * @name rowIdentity * @methodOf ui.grid.class:GridOptions * @description This function is used to get and, if necessary, set the value uniquely identifying this row (i.e. if an identity is not present it will set one). * * By default it returns the `$$hashKey` property if it exists. If it doesn't it uses gridUtil.nextUid() to generate one */ baseOptions.rowIdentity = baseOptions.rowIdentity || function rowIdentity(row) { return gridUtil.hashKey(row); }; /** * @ngdoc function * @name getRowIdentity * @methodOf ui.grid.class:GridOptions * @description This function returns the identity value uniquely identifying this row, if one is not present it does not set it. * * By default it returns the `$$hashKey` property but can be overridden to use any property or set of properties you want. */ baseOptions.getRowIdentity = baseOptions.getRowIdentity || function getRowIdentity(row) { return row.$$hashKey; }; /** * @ngdoc property * @name flatEntityAccess * @propertyOf ui.grid.class:GridOptions * @description Set to true if your columns are all related directly to fields in a flat object structure - i.e. * each of your columns associate directly with a propery one each of the entities in your data array. * * In that situation we can avoid all the logic associated with complex binding to functions or to properties of sub-objects, * which can provide a significant speed improvement with large data sets, with filtering and with sorting. * * By default false */ baseOptions.flatEntityAccess = baseOptions.flatEntityAccess === true; /** * @ngdoc property * @name showHeader * @propertyOf ui.grid.class:GridOptions * @description True by default. When set to false, this setting will replace the * standard header template with '<div></div>', resulting in no header being shown. */ baseOptions.showHeader = typeof(baseOptions.showHeader) !== "undefined" ? baseOptions.showHeader : true; /* (NOTE): Don't show this in the docs. We only use it internally * @ngdoc property * @name headerRowHeight * @propertyOf ui.grid.class:GridOptions * @description The height of the header in pixels, defaults to 30 * */ if (!baseOptions.showHeader) { baseOptions.headerRowHeight = 0; } else { baseOptions.headerRowHeight = typeof(baseOptions.headerRowHeight) !== "undefined" ? baseOptions.headerRowHeight : 30; } /** * @ngdoc property * @name rowHeight * @propertyOf ui.grid.class:GridOptions * @description The height of the row in pixels, defaults to 30 * */ baseOptions.rowHeight = baseOptions.rowHeight || 30; /** * @ngdoc integer * @name minRowsToShow * @propertyOf ui.grid.class:GridOptions * @description Minimum number of rows to show when the grid doesn't have a defined height. Defaults to "10". */ baseOptions.minRowsToShow = typeof(baseOptions.minRowsToShow) !== "undefined" ? baseOptions.minRowsToShow : 10; /** * @ngdoc property * @name showGridFooter * @propertyOf ui.grid.class:GridOptions * @description Whether or not to show the footer, defaults to false * The footer display Total Rows and Visible Rows (filtered rows) */ baseOptions.showGridFooter = baseOptions.showGridFooter === true; /** * @ngdoc property * @name showColumnFooter * @propertyOf ui.grid.class:GridOptions * @description Whether or not to show the column footer, defaults to false * The column footer displays column aggregates */ baseOptions.showColumnFooter = baseOptions.showColumnFooter === true; /** * @ngdoc property * @name columnFooterHeight * @propertyOf ui.grid.class:GridOptions * @description The height of the footer rows (column footer and grid footer) in pixels * */ baseOptions.columnFooterHeight = typeof(baseOptions.columnFooterHeight) !== "undefined" ? baseOptions.columnFooterHeight : 30; baseOptions.gridFooterHeight = typeof(baseOptions.gridFooterHeight) !== "undefined" ? baseOptions.gridFooterHeight : 30; baseOptions.columnWidth = typeof(baseOptions.columnWidth) !== "undefined" ? baseOptions.columnWidth : 50; /** * @ngdoc property * @name maxVisibleColumnCount * @propertyOf ui.grid.class:GridOptions * @description Defaults to 200 * */ baseOptions.maxVisibleColumnCount = typeof(baseOptions.maxVisibleColumnCount) !== "undefined" ? baseOptions.maxVisibleColumnCount : 200; /** * @ngdoc property * @name virtualizationThreshold * @propertyOf ui.grid.class:GridOptions * @description Turn virtualization on when number of data elements goes over this number, defaults to 20 */ baseOptions.virtualizationThreshold = typeof(baseOptions.virtualizationThreshold) !== "undefined" ? baseOptions.virtualizationThreshold : 20; /** * @ngdoc property * @name columnVirtualizationThreshold * @propertyOf ui.grid.class:GridOptions * @description Turn virtualization on when number of columns goes over this number, defaults to 10 */ baseOptions.columnVirtualizationThreshold = typeof(baseOptions.columnVirtualizationThreshold) !== "undefined" ? baseOptions.columnVirtualizationThreshold : 10; /** * @ngdoc property * @name excessRows * @propertyOf ui.grid.class:GridOptions * @description Extra rows to to render outside of the viewport, which helps with smoothness of scrolling. * Defaults to 4 */ baseOptions.excessRows = typeof(baseOptions.excessRows) !== "undefined" ? baseOptions.excessRows : 4; /** * @ngdoc property * @name scrollThreshold * @propertyOf ui.grid.class:GridOptions * @description Defaults to 4 */ baseOptions.scrollThreshold = typeof(baseOptions.scrollThreshold) !== "undefined" ? baseOptions.scrollThreshold : 4; /** * @ngdoc property * @name excessColumns * @propertyOf ui.grid.class:GridOptions * @description Extra columns to to render outside of the viewport, which helps with smoothness of scrolling. * Defaults to 4 */ baseOptions.excessColumns = typeof(baseOptions.excessColumns) !== "undefined" ? baseOptions.excessColumns : 4; /** * @ngdoc property * @name horizontalScrollThreshold * @propertyOf ui.grid.class:GridOptions * @description Defaults to 4 */ baseOptions.horizontalScrollThreshold = typeof(baseOptions.horizontalScrollThreshold) !== "undefined" ? baseOptions.horizontalScrollThreshold : 2; /** * @ngdoc property * @name aggregationCalcThrottle * @propertyOf ui.grid.class:GridOptions * @description Default time in milliseconds to throttle aggregation calcuations, defaults to 500ms */ baseOptions.aggregationCalcThrottle = typeof(baseOptions.aggregationCalcThrottle) !== "undefined" ? baseOptions.aggregationCalcThrottle : 500; /** * @ngdoc property * @name wheelScrollThrottle * @propertyOf ui.grid.class:GridOptions * @description Default time in milliseconds to throttle scroll events to, defaults to 70ms */ baseOptions.wheelScrollThrottle = typeof(baseOptions.wheelScrollThrottle) !== "undefined" ? baseOptions.wheelScrollThrottle : 70; /** * @ngdoc property * @name scrollDebounce * @propertyOf ui.grid.class:GridOptions * @description Default time in milliseconds to debounce scroll events, defaults to 300ms */ baseOptions.scrollDebounce = typeof(baseOptions.scrollDebounce) !== "undefined" ? baseOptions.scrollDebounce : 300; /** * @ngdoc boolean * @name enableSorting * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, this setting adds sort * widgets to the column headers, allowing sorting of the data for the entire grid. * Sorting can then be disabled on individual columns using the columnDefs. */ baseOptions.enableSorting = baseOptions.enableSorting !== false; /** * @ngdoc boolean * @name enableFiltering * @propertyOf ui.grid.class:GridOptions * @description False by default. When enabled, this setting adds filter * boxes to each column header, allowing filtering within the column for the entire grid. * Filtering can then be disabled on individual columns using the columnDefs. */ baseOptions.enableFiltering = baseOptions.enableFiltering === true; /** * @ngdoc boolean * @name enableColumnMenus * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, this setting displays a column * menu within each column. */ baseOptions.enableColumnMenus = baseOptions.enableColumnMenus !== false; /** * @ngdoc boolean * @name enableVerticalScrollbar * @propertyOf ui.grid.class:GridOptions * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the vertical scrollbar for the grid. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER */ baseOptions.enableVerticalScrollbar = typeof(baseOptions.enableVerticalScrollbar) !== "undefined" ? baseOptions.enableVerticalScrollbar : uiGridConstants.scrollbars.ALWAYS; /** * @ngdoc boolean * @name enableHorizontalScrollbar * @propertyOf ui.grid.class:GridOptions * @description uiGridConstants.scrollbars.ALWAYS by default. This settings controls the horizontal scrollbar for the grid. * Supported values: uiGridConstants.scrollbars.ALWAYS, uiGridConstants.scrollbars.NEVER */ baseOptions.enableHorizontalScrollbar = typeof(baseOptions.enableHorizontalScrollbar) !== "undefined" ? baseOptions.enableHorizontalScrollbar : uiGridConstants.scrollbars.ALWAYS; /** * @ngdoc boolean * @name enableMinHeightCheck * @propertyOf ui.grid.class:GridOptions * @description True by default. When enabled, a newly initialized grid will check to see if it is tall enough to display * at least one row of data. If the grid is not tall enough, it will resize the DOM element to display minRowsToShow number * of rows. */ baseOptions.enableMinHeightCheck = baseOptions.enableMinHeightCheck !== false; /** * @ngdoc boolean * @name minimumColumnSize * @propertyOf ui.grid.class:GridOptions * @description Columns can't be smaller than this, defaults to 10 pixels */ baseOptions.minimumColumnSize = typeof(baseOptions.minimumColumnSize) !== "undefined" ? baseOptions.minimumColumnSize : 10; /** * @ngdoc function * @name rowEquality * @methodOf ui.grid.class:GridOptions * @description By default, rows are compared using object equality. This option can be overridden * to compare on any data item property or function * @param {object} entityA First Data Item to compare * @param {object} entityB Second Data Item to compare */ baseOptions.rowEquality = baseOptions.rowEquality || function(entityA, entityB) { return entityA === entityB; }; /** * @ngdoc string * @name headerTemplate * @propertyOf ui.grid.class:GridOptions * @description Null by default. When provided, this setting uses a custom header * template, rather than the default template. Can be set to either the name of a template file: * <pre> $scope.gridOptions.headerTemplate = 'header_template.html';</pre> * inline html * <pre> $scope.gridOptions.headerTemplate = '<div class="ui-grid-top-panel" style="text-align: center">I am a Custom Grid Header</div>'</pre> * or the id of a precompiled template (TBD how to use this). * </br>Refer to the custom header tutorial for more information. * If you want no header at all, you can set to an empty div: * <pre> $scope.gridOptions.headerTemplate = '<div></div>';</pre> * * If you want to only have a static header, then you can set to static content. If * you want to tailor the existing column headers, then you should look at the * current 'ui-grid-header.html' template in github as your starting point. * */ baseOptions.headerTemplate = baseOptions.headerTemplate || null; /** * @ngdoc string * @name footerTemplate * @propertyOf ui.grid.class:GridOptions * @description (optional) ui-grid/ui-grid-footer by default. This footer shows the per-column * aggregation totals. * When provided, this setting uses a custom footer template. Can be set to either the name of a template file 'footer_template.html', inline html * <pre>'<div class="ui-grid-bottom-panel" style="text-align: center">I am a Custom Grid Footer</div>'</pre>, or the id * of a precompiled template (TBD how to use this). Refer to the custom footer tutorial for more information. */ baseOptions.footerTemplate = baseOptions.footerTemplate || 'ui-grid/ui-grid-footer'; /** * @ngdoc string * @name gridFooterTemplate * @propertyOf ui.grid.class:GridOptions * @description (optional) ui-grid/ui-grid-grid-footer by default. This template by default shows the * total items at the bottom of the grid, and the selected items if selection is enabled. */ baseOptions.gridFooterTemplate = baseOptions.gridFooterTemplate || 'ui-grid/ui-grid-grid-footer'; /** * @ngdoc string * @name rowTemplate * @propertyOf ui.grid.class:GridOptions * @description 'ui-grid/ui-grid-row' by default. When provided, this setting uses a * custom row template. Can be set to either the name of a template file: * <pre> $scope.gridOptions.rowTemplate = 'row_template.html';</pre> * inline html * <pre> $scope.gridOptions.rowTemplate = '<div style="background-color: aquamarine" ng-click="grid.appScope.fnOne(row)" ng-repeat="col in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ui-grid-cell></div>';</pre> * or the id of a precompiled template (TBD how to use this) can be provided. * </br>Refer to the custom row template tutorial for more information. */ baseOptions.rowTemplate = baseOptions.rowTemplate || 'ui-grid/ui-grid-row'; /** * @ngdoc object * @name appScopeProvider * @propertyOf ui.grid.class:GridOptions * @description by default, the parent scope of the ui-grid element will be assigned to grid.appScope * this property allows you to assign any reference you want to grid.appScope */ baseOptions.appScopeProvider = baseOptions.appScopeProvider || null; return baseOptions; } }; }]); })(); (function(){ angular.module('ui.grid') /** * @ngdoc function * @name ui.grid.class:GridRenderContainer * @description The grid has render containers, allowing the ability to have pinned columns. If the grid * is right-to-left then there may be a right render container, if left-to-right then there may * be a left render container. There is always a body render container. * @param {string} name The name of the render container ('body', 'left', or 'right') * @param {Grid} grid the grid the render container is in * @param {object} options the render container options */ .factory('GridRenderContainer', ['gridUtil', 'uiGridConstants', function(gridUtil, uiGridConstants) { function GridRenderContainer(name, grid, options) { var self = this; // if (gridUtil.type(grid) !== 'Grid') { // throw new Error('Grid argument is not a Grid object'); // } self.name = name; self.grid = grid; // self.rowCache = []; // self.columnCache = []; self.visibleRowCache = []; self.visibleColumnCache = []; self.renderedRows = []; self.renderedColumns = []; self.prevScrollTop = 0; self.prevScrolltopPercentage = 0; self.prevRowScrollIndex = 0; self.prevScrollLeft = 0; self.prevScrollleftPercentage = 0; self.prevColumnScrollIndex = 0; self.columnStyles = ""; self.viewportAdjusters = []; /** * @ngdoc boolean * @name hasHScrollbar * @propertyOf ui.grid.class:GridRenderContainer * @description flag to signal that container has a horizontal scrollbar */ self.hasHScrollbar = false; /** * @ngdoc boolean * @name hasHScrollbar * @propertyOf ui.grid.class:GridRenderContainer * @description flag to signal that container has a vertical scrollbar */ self.hasVScrollbar = false; /** * @ngdoc boolean * @name canvasHeightShouldUpdate * @propertyOf ui.grid.class:GridRenderContainer * @description flag to signal that container should recalculate the canvas size */ self.canvasHeightShouldUpdate = true; /** * @ngdoc boolean * @name canvasHeight * @propertyOf ui.grid.class:GridRenderContainer * @description last calculated canvas height value */ self.$$canvasHeight = 0; if (options && angular.isObject(options)) { angular.extend(self, options); } grid.registerStyleComputation({ priority: 5, func: function () { self.updateColumnWidths(); return self.columnStyles; } }); } GridRenderContainer.prototype.reset = function reset() { // this.rowCache.length = 0; // this.columnCache.length = 0; this.visibleColumnCache.length = 0; this.visibleRowCache.length = 0; this.renderedRows.length = 0; this.renderedColumns.length = 0; }; // TODO(c0bra): calculate size?? Should this be in a stackable directive? GridRenderContainer.prototype.containsColumn = function (col) { return this.visibleColumnCache.indexOf(col) !== -1; }; GridRenderContainer.prototype.minRowsToRender = function minRowsToRender() { var self = this; var minRows = 0; var rowAddedHeight = 0; var viewPortHeight = self.getViewportHeight(); for (var i = self.visibleRowCache.length - 1; rowAddedHeight < viewPortHeight && i >= 0; i--) { rowAddedHeight += self.visibleRowCache[i].height; minRows++; } return minRows; }; GridRenderContainer.prototype.minColumnsToRender = function minColumnsToRender() { var self = this; var viewportWidth = this.getViewportWidth(); var min = 0; var totalWidth = 0; // self.columns.forEach(function(col, i) { for (var i = 0; i < self.visibleColumnCache.length; i++) { var col = self.visibleColumnCache[i]; if (totalWidth < viewportWidth) { totalWidth += col.drawnWidth ? col.drawnWidth : 0; min++; } else { var currWidth = 0; for (var j = i; j >= i - min; j--) { currWidth += self.visibleColumnCache[j].drawnWidth ? self.visibleColumnCache[j].drawnWidth : 0; } if (currWidth < viewportWidth) { min++; } } } return min; }; GridRenderContainer.prototype.getVisibleRowCount = function getVisibleRowCount() { return this.visibleRowCache.length; }; /** * @ngdoc function * @name registerViewportAdjuster * @methodOf ui.grid.class:GridRenderContainer * @description Registers an adjuster to the render container's available width or height. Adjusters are used * to tell the render container that there is something else consuming space, and to adjust it's size * appropriately. * @param {function} func the adjuster function we want to register */ GridRenderContainer.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) { this.viewportAdjusters.push(func); }; /** * @ngdoc function * @name removeViewportAdjuster * @methodOf ui.grid.class:GridRenderContainer * @description Removes an adjuster, should be used when your element is destroyed * @param {function} func the adjuster function we want to remove */ GridRenderContainer.prototype.removeViewportAdjuster = function registerViewportAdjuster(func) { var idx = this.viewportAdjusters.indexOf(func); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.viewportAdjusters.splice(idx, 1); } }; /** * @ngdoc function * @name getViewportAdjustment * @methodOf ui.grid.class:GridRenderContainer * @description Gets the adjustment based on the viewportAdjusters. * @returns {object} a hash of { height: x, width: y }. Usually the values will be negative */ GridRenderContainer.prototype.getViewportAdjustment = function getViewportAdjustment() { var self = this; var adjustment = { height: 0, width: 0 }; self.viewportAdjusters.forEach(function (func) { adjustment = func.call(this, adjustment); }); return adjustment; }; GridRenderContainer.prototype.getMargin = function getMargin(side) { var self = this; var amount = 0; self.viewportAdjusters.forEach(function (func) { var adjustment = func.call(this, { height: 0, width: 0 }); if (adjustment.side && adjustment.side === side) { amount += adjustment.width * -1; } }); return amount; }; GridRenderContainer.prototype.getViewportHeight = function getViewportHeight() { var self = this; var headerHeight = (self.headerHeight) ? self.headerHeight : self.grid.headerHeight; var viewPortHeight = self.grid.gridHeight - headerHeight - self.grid.footerHeight; var adjustment = self.getViewportAdjustment(); viewPortHeight = viewPortHeight + adjustment.height; return viewPortHeight; }; GridRenderContainer.prototype.getViewportWidth = function getViewportWidth() { var self = this; var viewportWidth = self.grid.gridWidth; //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth - self.grid.verticalScrollbarWidth; //} // var viewportWidth = 0;\ // self.visibleColumnCache.forEach(function (column) { // viewportWidth += column.drawnWidth; // }); var adjustment = self.getViewportAdjustment(); viewportWidth = viewportWidth + adjustment.width; return viewportWidth; }; GridRenderContainer.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() { var self = this; var viewportWidth = this.getViewportWidth(); //if (typeof(self.grid.verticalScrollbarWidth) !== 'undefined' && self.grid.verticalScrollbarWidth !== undefined && self.grid.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth + self.grid.verticalScrollbarWidth; //} // var adjustment = self.getViewportAdjustment(); // viewPortWidth = viewPortWidth + adjustment.width; return viewportWidth; }; /** * @ngdoc function * @name getCanvasHeight * @methodOf ui.grid.class:GridRenderContainer * @description Returns the total canvas height. Only recalculates if canvasHeightShouldUpdate = false * @returns {number} total height of all the visible rows in the container */ GridRenderContainer.prototype.getCanvasHeight = function getCanvasHeight() { var self = this; if (!self.canvasHeightShouldUpdate) { return self.$$canvasHeight; } var oldCanvasHeight = self.$$canvasHeight; self.$$canvasHeight = 0; self.visibleRowCache.forEach(function(row){ self.$$canvasHeight += row.height; }); self.canvasHeightShouldUpdate = false; self.grid.api.core.raise.canvasHeightChanged(oldCanvasHeight, self.$$canvasHeight); return self.$$canvasHeight; }; GridRenderContainer.prototype.getVerticalScrollLength = function getVerticalScrollLength() { return this.getCanvasHeight() - this.getViewportHeight() + this.grid.scrollbarHeight; }; GridRenderContainer.prototype.getCanvasWidth = function getCanvasWidth() { var self = this; var ret = self.canvasWidth; return ret; }; GridRenderContainer.prototype.setRenderedRows = function setRenderedRows(newRows) { this.renderedRows.length = newRows.length; for (var i = 0; i < newRows.length; i++) { this.renderedRows[i] = newRows[i]; } }; GridRenderContainer.prototype.setRenderedColumns = function setRenderedColumns(newColumns) { var self = this; // OLD: this.renderedColumns.length = newColumns.length; for (var i = 0; i < newColumns.length; i++) { this.renderedColumns[i] = newColumns[i]; } this.updateColumnOffset(); }; GridRenderContainer.prototype.updateColumnOffset = function updateColumnOffset() { // Calculate the width of the columns on the left side that are no longer rendered. // That will be the offset for the columns as we scroll horizontally. var hiddenColumnsWidth = 0; for (var i = 0; i < this.currentFirstColumn; i++) { hiddenColumnsWidth += this.visibleColumnCache[i].drawnWidth; } this.columnOffset = hiddenColumnsWidth; }; GridRenderContainer.prototype.scrollVertical = function (newScrollTop) { var vertScrollPercentage = -1; if (newScrollTop !== this.prevScrollTop) { var yDiff = newScrollTop - this.prevScrollTop; if (yDiff > 0 ) { this.grid.scrollDirection = uiGridConstants.scrollDirection.DOWN; } if (yDiff < 0 ) { this.grid.scrollDirection = uiGridConstants.scrollDirection.UP; } var vertScrollLength = this.getVerticalScrollLength(); vertScrollPercentage = newScrollTop / vertScrollLength; // console.log('vert', vertScrollPercentage, newScrollTop, vertScrollLength); if (vertScrollPercentage > 1) { vertScrollPercentage = 1; } if (vertScrollPercentage < 0) { vertScrollPercentage = 0; } this.adjustScrollVertical(newScrollTop, vertScrollPercentage); return vertScrollPercentage; } }; GridRenderContainer.prototype.scrollHorizontal = function(newScrollLeft){ var horizScrollPercentage = -1; // Handle RTL here if (newScrollLeft !== this.prevScrollLeft) { var xDiff = newScrollLeft - this.prevScrollLeft; if (xDiff > 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.RIGHT; } if (xDiff < 0) { this.grid.scrollDirection = uiGridConstants.scrollDirection.LEFT; } var horizScrollLength = (this.canvasWidth - this.getViewportWidth()); if (horizScrollLength !== 0) { horizScrollPercentage = newScrollLeft / horizScrollLength; } else { horizScrollPercentage = 0; } this.adjustScrollHorizontal(newScrollLeft, horizScrollPercentage); return horizScrollPercentage; } }; GridRenderContainer.prototype.adjustScrollVertical = function adjustScrollVertical(scrollTop, scrollPercentage, force) { if (this.prevScrollTop === scrollTop && !force) { return; } if (typeof(scrollTop) === 'undefined' || scrollTop === undefined || scrollTop === null) { scrollTop = (this.getCanvasHeight() - this.getViewportHeight()) * scrollPercentage; } this.adjustRows(scrollTop, scrollPercentage, false); this.prevScrollTop = scrollTop; this.prevScrolltopPercentage = scrollPercentage; this.grid.queueRefresh(); }; GridRenderContainer.prototype.adjustScrollHorizontal = function adjustScrollHorizontal(scrollLeft, scrollPercentage, force) { if (this.prevScrollLeft === scrollLeft && !force) { return; } if (typeof(scrollLeft) === 'undefined' || scrollLeft === undefined || scrollLeft === null) { scrollLeft = (this.getCanvasWidth() - this.getViewportWidth()) * scrollPercentage; } this.adjustColumns(scrollLeft, scrollPercentage); this.prevScrollLeft = scrollLeft; this.prevScrollleftPercentage = scrollPercentage; this.grid.queueRefresh(); }; GridRenderContainer.prototype.adjustRows = function adjustRows(scrollTop, scrollPercentage, postDataLoaded) { var self = this; var minRows = self.minRowsToRender(); var rowCache = self.visibleRowCache; var maxRowIndex = rowCache.length - minRows; // console.log('scroll%1', scrollPercentage); // Calculate the scroll percentage according to the scrollTop location, if no percentage was provided if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollTop) { scrollPercentage = scrollTop / self.getVerticalScrollLength(); } var rowIndex = Math.ceil(Math.min(maxRowIndex, maxRowIndex * scrollPercentage)); // console.log('maxRowIndex / scroll%', maxRowIndex, scrollPercentage, rowIndex); // Define a max row index that we can't scroll past if (rowIndex > maxRowIndex) { rowIndex = maxRowIndex; } var newRange = []; if (rowCache.length > self.grid.options.virtualizationThreshold) { if (!(typeof(scrollTop) === 'undefined' || scrollTop === null)) { // Have we hit the threshold going down? if ( !self.grid.suppressParentScrollDown && self.prevScrollTop < scrollTop && rowIndex < self.prevRowScrollIndex + self.grid.options.scrollThreshold && rowIndex < maxRowIndex) { return; } //Have we hit the threshold going up? if ( !self.grid.suppressParentScrollUp && self.prevScrollTop > scrollTop && rowIndex > self.prevRowScrollIndex - self.grid.options.scrollThreshold && rowIndex < maxRowIndex) { return; } } var rangeStart = {}; var rangeEnd = {}; rangeStart = Math.max(0, rowIndex - self.grid.options.excessRows); rangeEnd = Math.min(rowCache.length, rowIndex + minRows + self.grid.options.excessRows); newRange = [rangeStart, rangeEnd]; } else { var maxLen = self.visibleRowCache.length; newRange = [0, Math.max(maxLen, minRows + self.grid.options.excessRows)]; } self.updateViewableRowRange(newRange); self.prevRowScrollIndex = rowIndex; }; GridRenderContainer.prototype.adjustColumns = function adjustColumns(scrollLeft, scrollPercentage) { var self = this; var minCols = self.minColumnsToRender(); var columnCache = self.visibleColumnCache; var maxColumnIndex = columnCache.length - minCols; // Calculate the scroll percentage according to the scrollTop location, if no percentage was provided if ((typeof(scrollPercentage) === 'undefined' || scrollPercentage === null) && scrollLeft) { scrollPercentage = scrollLeft / self.getCanvasWidth(); } var colIndex = Math.ceil(Math.min(maxColumnIndex, maxColumnIndex * scrollPercentage)); // Define a max row index that we can't scroll past if (colIndex > maxColumnIndex) { colIndex = maxColumnIndex; } var newRange = []; if (columnCache.length > self.grid.options.columnVirtualizationThreshold && self.getCanvasWidth() > self.getViewportWidth()) { /* Commented the following lines because otherwise the moved column wasn't visible immediately on the new position * in the case of many columns with horizontal scroll, one had to scroll left or right and then return in order to see it // Have we hit the threshold going down? if (self.prevScrollLeft < scrollLeft && colIndex < self.prevColumnScrollIndex + self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) { return; } //Have we hit the threshold going up? if (self.prevScrollLeft > scrollLeft && colIndex > self.prevColumnScrollIndex - self.grid.options.horizontalScrollThreshold && colIndex < maxColumnIndex) { return; }*/ var rangeStart = Math.max(0, colIndex - self.grid.options.excessColumns); var rangeEnd = Math.min(columnCache.length, colIndex + minCols + self.grid.options.excessColumns); newRange = [rangeStart, rangeEnd]; } else { var maxLen = self.visibleColumnCache.length; newRange = [0, Math.max(maxLen, minCols + self.grid.options.excessColumns)]; } self.updateViewableColumnRange(newRange); self.prevColumnScrollIndex = colIndex; }; // Method for updating the visible rows GridRenderContainer.prototype.updateViewableRowRange = function updateViewableRowRange(renderedRange) { // Slice out the range of rows from the data // var rowArr = uiGridCtrl.grid.rows.slice(renderedRange[0], renderedRange[1]); var rowArr = this.visibleRowCache.slice(renderedRange[0], renderedRange[1]); // Define the top-most rendered row this.currentTopRow = renderedRange[0]; this.setRenderedRows(rowArr); }; // Method for updating the visible columns GridRenderContainer.prototype.updateViewableColumnRange = function updateViewableColumnRange(renderedRange) { // Slice out the range of rows from the data // var columnArr = uiGridCtrl.grid.columns.slice(renderedRange[0], renderedRange[1]); var columnArr = this.visibleColumnCache.slice(renderedRange[0], renderedRange[1]); // Define the left-most rendered columns this.currentFirstColumn = renderedRange[0]; this.setRenderedColumns(columnArr); }; GridRenderContainer.prototype.headerCellWrapperStyle = function () { var self = this; if (self.currentFirstColumn !== 0) { var offset = self.columnOffset; if (self.grid.isRTL()) { return { 'margin-right': offset + 'px' }; } else { return { 'margin-left': offset + 'px' }; } } return null; }; /** * @ngdoc boolean * @name updateColumnWidths * @propertyOf ui.grid.class:GridRenderContainer * @description Determine the appropriate column width of each column across all render containers. * * Column width is easy when each column has a specified width. When columns are variable width (i.e. * have an * or % of the viewport) then we try to calculate so that things fit in. The problem is that * we have multiple render containers, and we don't want one render container to just take the whole viewport * when it doesn't need to - we want things to balance out across the render containers. * * To do this, we use this method to calculate all the renderContainers, recognising that in a given render * cycle it'll get called once per render container, so it needs to return the same values each time. * * The constraints on this method are therefore: * - must return the same value when called multiple times, to do this it needs to rely on properties of the * columns, but not properties that change when this is called (so it shouldn't rely on drawnWidth) * * The general logic of this method is: * - calculate our total available width * - look at all the columns across all render containers, and work out which have widths and which have * constraints such as % or * or something else * - for those with *, count the total number of * we see and add it onto a running total, add this column to an * array * - for those with a %, allocate the % as a percentage of the viewport, having consideration of min and max * - for those with manual width (in pixels) we set the drawnWidth to the specified width * - we end up with an asterisks array still to process * - we look at our remaining width. If it's greater than zero, we divide it up among the asterisk columns, then process * them for min and max width constraints * - if it's zero or less, we set the asterisk columns to their minimum widths * - we use parseInt quite a bit, as we try to make all our column widths integers */ GridRenderContainer.prototype.updateColumnWidths = function () { var self = this; var asterisksArray = [], asteriskNum = 0, usedWidthSum = 0, ret = ''; // Get the width of the viewport var availableWidth = self.grid.getViewportWidth() - self.grid.scrollbarWidth; // get all the columns across all render containers, we have to calculate them all or one render container // could consume the whole viewport var columnCache = []; angular.forEach(self.grid.renderContainers, function( container, name){ columnCache = columnCache.concat(container.visibleColumnCache); }); // look at each column, process any manual values or %, put the * into an array to look at later columnCache.forEach(function(column, i) { var width = 0; // Skip hidden columns if (!column.visible) { return; } if (angular.isNumber(column.width)) { // pixel width, set to this value width = parseInt(column.width, 10); usedWidthSum = usedWidthSum + width; column.drawnWidth = width; } else if (gridUtil.endsWith(column.width, "%")) { // percentage width, set to percentage of the viewport width = parseInt(parseInt(column.width.replace(/%/g, ''), 10) / 100 * availableWidth); if ( width > column.maxWidth ){ width = column.maxWidth; } if ( width < column.minWidth ){ width = column.minWidth; } usedWidthSum = usedWidthSum + width; column.drawnWidth = width; } else if (angular.isString(column.width) && column.width.indexOf('*') !== -1) { // is an asterisk column, the gridColumn already checked the string consists only of '****' asteriskNum = asteriskNum + column.width.length; asterisksArray.push(column); } }); // Get the remaining width (available width subtracted by the used widths sum) var remainingWidth = availableWidth - usedWidthSum; var i, column, colWidth; if (asterisksArray.length > 0) { // the width that each asterisk value would be assigned (this can be negative) var asteriskVal = remainingWidth / asteriskNum; asterisksArray.forEach(function( column ){ var width = parseInt(column.width.length * asteriskVal, 10); if ( width > column.maxWidth ){ width = column.maxWidth; } if ( width < column.minWidth ){ width = column.minWidth; } usedWidthSum = usedWidthSum + width; column.drawnWidth = width; }); } // If the grid width didn't divide evenly into the column widths and we have pixels left over, or our // calculated widths would have the grid narrower than the available space, // dole the remainder out one by one to make everything fit var processColumnUpwards = function(column){ if ( column.drawnWidth < column.maxWidth && leftoverWidth > 0) { column.drawnWidth++; usedWidthSum++; leftoverWidth--; columnsToChange = true; } }; var leftoverWidth = availableWidth - usedWidthSum; var columnsToChange = true; while (leftoverWidth > 0 && columnsToChange) { columnsToChange = false; asterisksArray.forEach(processColumnUpwards); } // We can end up with too much width even though some columns aren't at their max width, in this situation // we can trim the columns a little var processColumnDownwards = function(column){ if ( column.drawnWidth > column.minWidth && excessWidth > 0) { column.drawnWidth--; usedWidthSum--; excessWidth--; columnsToChange = true; } }; var excessWidth = usedWidthSum - availableWidth; columnsToChange = true; while (excessWidth > 0 && columnsToChange) { columnsToChange = false; asterisksArray.forEach(processColumnDownwards); } // all that was across all the renderContainers, now we need to work out what that calculation decided for // our renderContainer var canvasWidth = 0; self.visibleColumnCache.forEach(function(column){ if ( column.visible ){ canvasWidth = canvasWidth + column.drawnWidth; } }); // Build the CSS columnCache.forEach(function (column) { ret = ret + column.getColClassDefinition(); }); self.canvasWidth = canvasWidth; // Return the styles back to buildStyles which pops them into the `customStyles` scope variable // return ret; // Set this render container's column styles so they can be used in style computation this.columnStyles = ret; }; GridRenderContainer.prototype.needsHScrollbarPlaceholder = function () { return this.grid.options.enableHorizontalScrollbar && !this.hasHScrollbar; }; GridRenderContainer.prototype.getViewportStyle = function () { var self = this; var styles = {}; self.hasHScrollbar = false; self.hasVScrollbar = false; if (self.grid.disableScrolling) { styles['overflow-x'] = 'hidden'; styles['overflow-y'] = 'hidden'; return styles; } if (self.name === 'body') { self.hasHScrollbar = self.grid.options.enableHorizontalScrollbar !== uiGridConstants.scrollbars.NEVER; if (!self.grid.isRTL()) { if (!self.grid.hasRightContainerColumns()) { self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER; } } else { if (!self.grid.hasLeftContainerColumns()) { self.hasVScrollbar = self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER; } } } else if (self.name === 'left') { self.hasVScrollbar = self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false; } else { self.hasVScrollbar = !self.grid.isRTL() ? self.grid.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER : false; } styles['overflow-x'] = self.hasHScrollbar ? 'scroll' : 'hidden'; styles['overflow-y'] = self.hasVScrollbar ? 'scroll' : 'hidden'; return styles; }; return GridRenderContainer; }]); })(); (function(){ angular.module('ui.grid') .factory('GridRow', ['gridUtil', function(gridUtil) { /** * @ngdoc function * @name ui.grid.class:GridRow * @description GridRow is the viewModel for one logical row on the grid. A grid Row is not necessarily a one-to-one * relation to gridOptions.data. * @param {object} entity the array item from GridOptions.data * @param {number} index the current position of the row in the array * @param {Grid} reference to the parent grid */ function GridRow(entity, index, grid) { /** * @ngdoc object * @name grid * @propertyOf ui.grid.class:GridRow * @description A reference back to the grid */ this.grid = grid; /** * @ngdoc object * @name entity * @propertyOf ui.grid.class:GridRow * @description A reference to an item in gridOptions.data[] */ this.entity = entity; /** * @ngdoc object * @name uid * @propertyOf ui.grid.class:GridRow * @description UniqueId of row */ this.uid = gridUtil.nextUid(); /** * @ngdoc object * @name visible * @propertyOf ui.grid.class:GridRow * @description If true, the row will be rendered */ // Default to true this.visible = true; this.$$height = grid.options.rowHeight; } /** * @ngdoc object * @name height * @propertyOf ui.grid.class:GridRow * @description height of each individual row. changing the height will flag all * row renderContainers to recalculate their canvas height */ Object.defineProperty(GridRow.prototype, 'height', { get: function() { return this.$$height; }, set: function(height) { if (height !== this.$$height) { this.grid.updateCanvasHeight(); this.$$height = height; } } }); /** * @ngdoc function * @name getQualifiedColField * @methodOf ui.grid.class:GridRow * @description returns the qualified field name as it exists on scope * ie: row.entity.fieldA * @param {GridCol} col column instance * @returns {string} resulting name that can be evaluated on scope */ GridRow.prototype.getQualifiedColField = function(col) { return 'row.' + this.getEntityQualifiedColField(col); }; /** * @ngdoc function * @name getEntityQualifiedColField * @methodOf ui.grid.class:GridRow * @description returns the qualified field name minus the row path * ie: entity.fieldA * @param {GridCol} col column instance * @returns {string} resulting name that can be evaluated against a row */ GridRow.prototype.getEntityQualifiedColField = function(col) { return gridUtil.preEval('entity.' + col.field); }; /** * @ngdoc function * @name setRowInvisible * @methodOf ui.grid.class:GridRow * @description Sets an override on the row that forces it to always * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility. * * This method can be called from the api, passing in the gridRow we want * altered. It should really work by calling gridRow.setRowInvisible, but that's * not the way I coded it, and too late to change now. Changed to just call * the internal function row.setThisRowInvisible(). * * @param {GridRow} row the row we want to set to invisible * */ GridRow.prototype.setRowInvisible = function ( row ) { if (row && row.setThisRowInvisible){ row.setThisRowInvisible( 'user' ); } }; /** * @ngdoc function * @name clearRowInvisible * @methodOf ui.grid.class:GridRow * @description Clears an override on the row that forces it to always * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility. * * This method can be called from the api, passing in the gridRow we want * altered. It should really work by calling gridRow.clearRowInvisible, but that's * not the way I coded it, and too late to change now. Changed to just call * the internal function row.clearThisRowInvisible(). * * @param {GridRow} row the row we want to clear the invisible flag * */ GridRow.prototype.clearRowInvisible = function ( row ) { if (row && row.clearThisRowInvisible){ row.clearThisRowInvisible( 'user' ); } }; /** * @ngdoc function * @name setThisRowInvisible * @methodOf ui.grid.class:GridRow * @description Sets an override on the row that forces it to always * be invisible. Emits the rowsVisibleChanged event if it changed the row visibility * * @param {string} reason the reason (usually the module) for the row to be invisible. * E.g. grouping, user, filter * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility */ GridRow.prototype.setThisRowInvisible = function ( reason, fromRowsProcessor ) { if ( !this.invisibleReason ){ this.invisibleReason = {}; } this.invisibleReason[reason] = true; this.evaluateRowVisibility( fromRowsProcessor); }; /** * @ngdoc function * @name clearRowInvisible * @methodOf ui.grid.class:GridRow * @description Clears any override on the row visibility, returning it * to normal visibility calculations. Emits the rowsVisibleChanged * event * * @param {string} reason the reason (usually the module) for the row to be invisible. * E.g. grouping, user, filter * @param {boolean} fromRowsProcessor whether we were called from a rowsProcessor, passed through to evaluateRowVisibility */ GridRow.prototype.clearThisRowInvisible = function ( reason, fromRowsProcessor ) { if (typeof(this.invisibleReason) !== 'undefined' ) { delete this.invisibleReason[reason]; } this.evaluateRowVisibility( fromRowsProcessor ); }; /** * @ngdoc function * @name evaluateRowVisibility * @methodOf ui.grid.class:GridRow * @description Determines whether the row should be visible based on invisibleReason, * and if it changes the row visibility, then emits the rowsVisibleChanged event. * * Queues a grid refresh, but doesn't call it directly to avoid hitting lots of grid refreshes. * @param {boolean} fromRowProcessor if true, then it won't raise events or queue the refresh, the * row processor does that already */ GridRow.prototype.evaluateRowVisibility = function ( fromRowProcessor ) { var newVisibility = true; if ( typeof(this.invisibleReason) !== 'undefined' ){ angular.forEach(this.invisibleReason, function( value, key ){ if ( value ){ newVisibility = false; } }); } if ( typeof(this.visible) === 'undefined' || this.visible !== newVisibility ){ this.visible = newVisibility; if ( !fromRowProcessor ){ this.grid.queueGridRefresh(); this.grid.api.core.raise.rowsVisibleChanged(this); } } }; return GridRow; }]); })(); (function () { angular.module('ui.grid') .factory('ScrollEvent', ['gridUtil', function (gridUtil) { /** * @ngdoc function * @name ui.grid.class:ScrollEvent * @description Model for all scrollEvents * @param {Grid} grid that owns the scroll event * @param {GridRenderContainer} sourceRowContainer that owns the scroll event. Can be null * @param {GridRenderContainer} sourceColContainer that owns the scroll event. Can be null * @param {string} source the source of the event - from uiGridConstants.scrollEventSources or a string value of directive/service/factory.functionName */ function ScrollEvent(grid, sourceRowContainer, sourceColContainer, source) { var self = this; if (!grid) { throw new Error("grid argument is required"); } /** * @ngdoc object * @name grid * @propertyOf ui.grid.class:ScrollEvent * @description A reference back to the grid */ self.grid = grid; /** * @ngdoc object * @name source * @propertyOf ui.grid.class:ScrollEvent * @description the source of the scroll event. limited to values from uiGridConstants.scrollEventSources */ self.source = source; /** * @ngdoc object * @name noDelay * @propertyOf ui.grid.class:ScrollEvent * @description most scroll events from the mouse or trackpad require delay to operate properly * set to false to eliminate delay. Useful for scroll events that the grid causes, such as scrolling to make a row visible. */ self.withDelay = true; self.sourceRowContainer = sourceRowContainer; self.sourceColContainer = sourceColContainer; self.newScrollLeft = null; self.newScrollTop = null; self.x = null; self.y = null; self.verticalScrollLength = -9999999; self.horizontalScrollLength = -999999; /** * @ngdoc function * @name fireThrottledScrollingEvent * @methodOf ui.grid.class:ScrollEvent * @description fires a throttled event using grid.api.core.raise.scrollEvent */ self.fireThrottledScrollingEvent = gridUtil.throttle(function(sourceContainerId) { self.grid.scrollContainers(sourceContainerId, self); }, self.grid.options.wheelScrollThrottle, {trailing: true}); } /** * @ngdoc function * @name getNewScrollLeft * @methodOf ui.grid.class:ScrollEvent * @description returns newScrollLeft property if available; calculates a new value if it isn't */ ScrollEvent.prototype.getNewScrollLeft = function(colContainer, viewport){ var self = this; if (!self.newScrollLeft){ var scrollWidth = (colContainer.getCanvasWidth() - colContainer.getViewportWidth()); var oldScrollLeft = gridUtil.normalizeScrollLeft(viewport, self.grid); var scrollXPercentage; if (typeof(self.x.percentage) !== 'undefined' && self.x.percentage !== undefined) { scrollXPercentage = self.x.percentage; } else if (typeof(self.x.pixels) !== 'undefined' && self.x.pixels !== undefined) { scrollXPercentage = self.x.percentage = (oldScrollLeft + self.x.pixels) / scrollWidth; } else { throw new Error("No percentage or pixel value provided for scroll event X axis"); } return Math.max(0, scrollXPercentage * scrollWidth); } return self.newScrollLeft; }; /** * @ngdoc function * @name getNewScrollTop * @methodOf ui.grid.class:ScrollEvent * @description returns newScrollTop property if available; calculates a new value if it isn't */ ScrollEvent.prototype.getNewScrollTop = function(rowContainer, viewport){ var self = this; if (!self.newScrollTop){ var scrollLength = rowContainer.getVerticalScrollLength(); var oldScrollTop = viewport[0].scrollTop; var scrollYPercentage; if (typeof(self.y.percentage) !== 'undefined' && self.y.percentage !== undefined) { scrollYPercentage = self.y.percentage; } else if (typeof(self.y.pixels) !== 'undefined' && self.y.pixels !== undefined) { scrollYPercentage = self.y.percentage = (oldScrollTop + self.y.pixels) / scrollLength; } else { throw new Error("No percentage or pixel value provided for scroll event Y axis"); } return Math.max(0, scrollYPercentage * scrollLength); } return self.newScrollTop; }; ScrollEvent.prototype.atTop = function(scrollTop) { return (this.y && (this.y.percentage === 0 || this.verticalScrollLength < 0) && scrollTop === 0); }; ScrollEvent.prototype.atBottom = function(scrollTop) { return (this.y && (this.y.percentage === 1 || this.verticalScrollLength === 0) && scrollTop > 0); }; ScrollEvent.prototype.atLeft = function(scrollLeft) { return (this.x && (this.x.percentage === 0 || this.horizontalScrollLength < 0) && scrollLeft === 0); }; ScrollEvent.prototype.atRight = function(scrollLeft) { return (this.x && (this.x.percentage === 1 || this.horizontalScrollLength ===0) && scrollLeft > 0); }; ScrollEvent.Sources = { ViewPortScroll: 'ViewPortScroll', RenderContainerMouseWheel: 'RenderContainerMouseWheel', RenderContainerTouchMove: 'RenderContainerTouchMove', Other: 99 }; return ScrollEvent; }]); })(); (function () { 'use strict'; /** * @ngdoc object * @name ui.grid.service:gridClassFactory * * @description factory to return dom specific instances of a grid * */ angular.module('ui.grid').service('gridClassFactory', ['gridUtil', '$q', '$compile', '$templateCache', 'uiGridConstants', 'Grid', 'GridColumn', 'GridRow', function (gridUtil, $q, $compile, $templateCache, uiGridConstants, Grid, GridColumn, GridRow) { var service = { /** * @ngdoc method * @name createGrid * @methodOf ui.grid.service:gridClassFactory * @description Creates a new grid instance. Each instance will have a unique id * @param {object} options An object map of options to pass into the created grid instance. * @returns {Grid} grid */ createGrid : function(options) { options = (typeof(options) !== 'undefined') ? options : {}; options.id = gridUtil.newId(); var grid = new Grid(options); // NOTE/TODO: rowTemplate should always be defined... if (grid.options.rowTemplate) { var rowTemplateFnPromise = $q.defer(); grid.getRowTemplateFn = rowTemplateFnPromise.promise; gridUtil.getTemplate(grid.options.rowTemplate) .then( function (template) { var rowTemplateFn = $compile(template); rowTemplateFnPromise.resolve(rowTemplateFn); }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use row template '" + grid.options.rowTemplate + "'"); }); } grid.registerColumnBuilder(service.defaultColumnBuilder); // Row builder for custom row templates grid.registerRowBuilder(service.rowTemplateAssigner); // Reset all rows to visible initially grid.registerRowsProcessor(function allRowsVisible(rows) { rows.forEach(function (row) { row.evaluateRowVisibility( true ); }, 50); return rows; }); grid.registerColumnsProcessor(function allColumnsVisible(columns) { columns.forEach(function (column) { column.visible = true; }); return columns; }, 50); grid.registerColumnsProcessor(function(renderableColumns) { renderableColumns.forEach(function (column) { if (column.colDef.visible === false) { column.visible = false; } }); return renderableColumns; }, 50); grid.registerRowsProcessor(grid.searchRows, 100); // Register the default row processor, it sorts rows by selected columns if (grid.options.externalSort && angular.isFunction(grid.options.externalSort)) { grid.registerRowsProcessor(grid.options.externalSort, 200); } else { grid.registerRowsProcessor(grid.sortByColumn, 200); } return grid; }, /** * @ngdoc function * @name defaultColumnBuilder * @methodOf ui.grid.service:gridClassFactory * @description Processes designTime column definitions and applies them to col for the * core grid features * @param {object} colDef reference to column definition * @param {GridColumn} col reference to gridCol * @param {object} gridOptions reference to grid options */ defaultColumnBuilder: function (colDef, col, gridOptions) { var templateGetPromises = []; // Abstracts the standard template processing we do for every template type. var processTemplate = function( templateType, providedType, defaultTemplate, filterType, tooltipType ) { if ( !colDef[templateType] ){ col[providedType] = defaultTemplate; } else { col[providedType] = colDef[templateType]; } templateGetPromises.push(gridUtil.getTemplate(col[providedType]) .then( function (template) { var tooltipCall = ( tooltipType === 'cellTooltip' ) ? 'col.cellTooltip(row,col)' : 'col.headerTooltip(col)'; if ( tooltipType && col[tooltipType] === false ){ template = template.replace(uiGridConstants.TOOLTIP, ''); } else if ( tooltipType && col[tooltipType] ){ template = template.replace(uiGridConstants.TOOLTIP, 'title="{{' + tooltipCall + ' CUSTOM_FILTERS }}"'); } if ( filterType ){ col[templateType] = template.replace(uiGridConstants.CUSTOM_FILTERS, function() { return col[filterType] ? "|" + col[filterType] : ""; }); } else { col[templateType] = template; } }, function (res) { throw new Error("Couldn't fetch/use colDef." + templateType + " '" + colDef[templateType] + "'"); }) ); }; /** * @ngdoc property * @name cellTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for each cell in this column. The default * is ui-grid/uiGridCell. If you are using the cellNav feature, this template * must contain a div that can receive focus. * */ processTemplate( 'cellTemplate', 'providedCellTemplate', 'ui-grid/uiGridCell', 'cellFilter', 'cellTooltip' ); col.cellTemplatePromise = templateGetPromises[0]; /** * @ngdoc property * @name headerCellTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for the header for this column. The default * is ui-grid/uiGridHeaderCell * */ processTemplate( 'headerCellTemplate', 'providedHeaderCellTemplate', 'ui-grid/uiGridHeaderCell', 'headerCellFilter', 'headerTooltip' ); /** * @ngdoc property * @name footerCellTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for the footer for this column. The default * is ui-grid/uiGridFooterCell * */ processTemplate( 'footerCellTemplate', 'providedFooterCellTemplate', 'ui-grid/uiGridFooterCell', 'footerCellFilter' ); /** * @ngdoc property * @name filterHeaderTemplate * @propertyOf ui.grid.class:GridOptions.columnDef * @description a custom template for the filter input. The default is ui-grid/ui-grid-filter * */ processTemplate( 'filterHeaderTemplate', 'providedFilterHeaderTemplate', 'ui-grid/ui-grid-filter' ); // Create a promise for the compiled element function col.compiledElementFnDefer = $q.defer(); return $q.all(templateGetPromises); }, rowTemplateAssigner: function rowTemplateAssigner(row) { var grid = this; // Row has no template assigned to it if (!row.rowTemplate) { // Use the default row template from the grid row.rowTemplate = grid.options.rowTemplate; // Use the grid's function for fetching the compiled row template function row.getRowTemplateFn = grid.getRowTemplateFn; } // Row has its own template assigned else { // Create a promise for the compiled row template function var perRowTemplateFnPromise = $q.defer(); row.getRowTemplateFn = perRowTemplateFnPromise.promise; // Get the row template gridUtil.getTemplate(row.rowTemplate) .then(function (template) { // Compile the template var rowTemplateFn = $compile(template); // Resolve the compiled template function promise perRowTemplateFnPromise.resolve(rowTemplateFn); }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use row template '" + row.rowTemplate + "'"); }); } return row.getRowTemplateFn; } }; //class definitions (moved to separate factories) return service; }]); })(); (function() { var module = angular.module('ui.grid'); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } /** * @ngdoc service * @name ui.grid.service:rowSearcher * * @description Service for searching/filtering rows based on column value conditions. */ module.service('rowSearcher', ['gridUtil', 'uiGridConstants', function (gridUtil, uiGridConstants) { var defaultCondition = uiGridConstants.filter.CONTAINS; var rowSearcher = {}; /** * @ngdoc function * @name getTerm * @methodOf ui.grid.service:rowSearcher * @description Get the term from a filter * Trims leading and trailing whitespace * @param {object} filter object to use * @returns {object} Parsed term */ rowSearcher.getTerm = function getTerm(filter) { if (typeof(filter.term) === 'undefined') { return filter.term; } var term = filter.term; // Strip leading and trailing whitespace if the term is a string if (typeof(term) === 'string') { term = term.trim(); } return term; }; /** * @ngdoc function * @name stripTerm * @methodOf ui.grid.service:rowSearcher * @description Remove leading and trailing asterisk (*) from the filter's term * @param {object} filter object to use * @returns {uiGridConstants.filter<int>} Value representing the condition constant value */ rowSearcher.stripTerm = function stripTerm(filter) { var term = rowSearcher.getTerm(filter); if (typeof(term) === 'string') { return escapeRegExp(term.replace(/(^\*|\*$)/g, '')); } else { return term; } }; /** * @ngdoc function * @name guessCondition * @methodOf ui.grid.service:rowSearcher * @description Guess the condition for a filter based on its term * <br> * Defaults to STARTS_WITH. Uses CONTAINS for strings beginning and ending with *s (*bob*). * Uses STARTS_WITH for strings ending with * (bo*). Uses ENDS_WITH for strings starting with * (*ob). * @param {object} filter object to use * @returns {uiGridConstants.filter<int>} Value representing the condition constant value */ rowSearcher.guessCondition = function guessCondition(filter) { if (typeof(filter.term) === 'undefined' || !filter.term) { return defaultCondition; } var term = rowSearcher.getTerm(filter); if (/\*/.test(term)) { var regexpFlags = ''; if (!filter.flags || !filter.flags.caseSensitive) { regexpFlags += 'i'; } var reText = term.replace(/(\\)?\*/g, function ($0, $1) { return $1 ? $0 : '[\\s\\S]*?'; }); return new RegExp('^' + reText + '$', regexpFlags); } // Otherwise default to default condition else { return defaultCondition; } }; /** * @ngdoc function * @name setupFilters * @methodOf ui.grid.service:rowSearcher * @description For a given columns filters (either col.filters, or [col.filter] can be passed in), * do all the parsing and pre-processing and store that data into a new filters object. The object * has the condition, the flags, the stripped term, and a parsed reg exp if there was one. * * We could use a forEach in here, since it's much less performance sensitive, but since we're using * for loops everywhere else in this module... * * @param {array} filters the filters from the column (col.filters or [col.filter]) * @returns {array} An array of parsed/preprocessed filters */ rowSearcher.setupFilters = function setupFilters( filters ){ var newFilters = []; var filtersLength = filters.length; for ( var i = 0; i < filtersLength; i++ ){ var filter = filters[i]; if ( filter.noTerm || !gridUtil.isNullOrUndefined(filter.term) ){ var newFilter = {}; var regexpFlags = ''; if (!filter.flags || !filter.flags.caseSensitive) { regexpFlags += 'i'; } if ( !gridUtil.isNullOrUndefined(filter.term) ){ // it is possible to have noTerm. We don't need to copy that across, it was just a flag to avoid // getting the filter ignored if the filter was a function that didn't use a term newFilter.term = rowSearcher.stripTerm(filter); } if ( filter.condition ){ newFilter.condition = filter.condition; } else { newFilter.condition = rowSearcher.guessCondition(filter); } newFilter.flags = angular.extend( { caseSensitive: false, date: false }, filter.flags ); if (newFilter.condition === uiGridConstants.filter.STARTS_WITH) { newFilter.startswithRE = new RegExp('^' + newFilter.term, regexpFlags); } if (newFilter.condition === uiGridConstants.filter.ENDS_WITH) { newFilter.endswithRE = new RegExp(newFilter.term + '$', regexpFlags); } if (newFilter.condition === uiGridConstants.filter.CONTAINS) { newFilter.containsRE = new RegExp(newFilter.term, regexpFlags); } if (newFilter.condition === uiGridConstants.filter.EXACT) { newFilter.exactRE = new RegExp('^' + newFilter.term + '$', regexpFlags); } newFilters.push(newFilter); } } return newFilters; }; /** * @ngdoc function * @name runColumnFilter * @methodOf ui.grid.service:rowSearcher * @description Runs a single pre-parsed filter against a cell, returning true * if the cell matches that one filter. * * @param {Grid} grid the grid we're working against * @param {GridRow} row the row we're matching against * @param {GridCol} column the column that we're working against * @param {object} filter the specific, preparsed, filter that we want to test * @returns {boolean} true if we match (row stays visible) */ rowSearcher.runColumnFilter = function runColumnFilter(grid, row, column, filter) { // Cache typeof condition var conditionType = typeof(filter.condition); // Term to search for. var term = filter.term; // Get the column value for this row var value; if ( column.filterCellFiltered ){ value = grid.getCellDisplayValue(row, column); } else { value = grid.getCellValue(row, column); } // If the filter's condition is a RegExp, then use it if (filter.condition instanceof RegExp) { return filter.condition.test(value); } // If the filter's condition is a function, run it if (conditionType === 'function') { return filter.condition(term, value, row, column); } if (filter.startswithRE) { return filter.startswithRE.test(value); } if (filter.endswithRE) { return filter.endswithRE.test(value); } if (filter.containsRE) { return filter.containsRE.test(value); } if (filter.exactRE) { return filter.exactRE.test(value); } if (filter.condition === uiGridConstants.filter.NOT_EQUAL) { var regex = new RegExp('^' + term + '$'); return !regex.exec(value); } if (typeof(value) === 'number' && typeof(term) === 'string' ){ // if the term has a decimal in it, it comes through as '9\.4', we need to take out the \ // the same for negative numbers // TODO: I suspect the right answer is to look at escapeRegExp at the top of this code file, maybe it's not needed? var tempFloat = parseFloat(term.replace(/\\\./,'.').replace(/\\\-/,'-')); if (!isNaN(tempFloat)) { term = tempFloat; } } if (filter.flags.date === true) { value = new Date(value); // If the term has a dash in it, it comes through as '\-' -- we need to take out the '\'. term = new Date(term.replace(/\\/g, '')); } if (filter.condition === uiGridConstants.filter.GREATER_THAN) { return (value > term); } if (filter.condition === uiGridConstants.filter.GREATER_THAN_OR_EQUAL) { return (value >= term); } if (filter.condition === uiGridConstants.filter.LESS_THAN) { return (value < term); } if (filter.condition === uiGridConstants.filter.LESS_THAN_OR_EQUAL) { return (value <= term); } return true; }; /** * @ngdoc boolean * @name useExternalFiltering * @propertyOf ui.grid.class:GridOptions * @description False by default. When enabled, this setting suppresses the internal filtering. * All UI logic will still operate, allowing filter conditions to be set and modified. * * The external filter logic can listen for the `filterChange` event, which fires whenever * a filter has been adjusted. */ /** * @ngdoc function * @name searchColumn * @methodOf ui.grid.service:rowSearcher * @description Process provided filters on provided column against a given row. If the row meets * the conditions on all the filters, return true. * @param {Grid} grid Grid to search in * @param {GridRow} row Row to search on * @param {GridCol} column Column with the filters to use * @param {array} filters array of pre-parsed/preprocessed filters to apply * @returns {boolean} Whether the column matches or not. */ rowSearcher.searchColumn = function searchColumn(grid, row, column, filters) { if (grid.options.useExternalFiltering) { return true; } var filtersLength = filters.length; for (var i = 0; i < filtersLength; i++) { var filter = filters[i]; var ret = rowSearcher.runColumnFilter(grid, row, column, filter); if (!ret) { return false; } } return true; }; /** * @ngdoc function * @name search * @methodOf ui.grid.service:rowSearcher * @description Run a search across the given rows and columns, marking any rows that don't * match the stored col.filters or col.filter as invisible. * @param {Grid} grid Grid instance to search inside * @param {Array[GridRow]} rows GridRows to filter * @param {Array[GridColumn]} columns GridColumns with filters to process */ rowSearcher.search = function search(grid, rows, columns) { /* * Added performance optimisations into this code base, as this logic creates deeply nested * loops and is therefore very performance sensitive. In particular, avoiding forEach as * this impacts some browser optimisers (particularly Chrome), using iterators instead */ // Don't do anything if we weren't passed any rows if (!rows) { return; } // don't filter if filtering currently disabled if (!grid.options.enableFiltering){ return rows; } // Build list of filters to apply var filterData = []; var colsLength = columns.length; var hasTerm = function( filters ) { var hasTerm = false; filters.forEach( function (filter) { if ( !gridUtil.isNullOrUndefined(filter.term) && filter.term !== '' || filter.noTerm ){ hasTerm = true; } }); return hasTerm; }; for (var i = 0; i < colsLength; i++) { var col = columns[i]; if (typeof(col.filters) !== 'undefined' && hasTerm(col.filters) ) { filterData.push( { col: col, filters: rowSearcher.setupFilters(col.filters) } ); } } if (filterData.length > 0) { // define functions outside the loop, performance optimisation var foreachRow = function(grid, row, col, filters){ if ( row.visible && !rowSearcher.searchColumn(grid, row, col, filters) ) { row.visible = false; } }; var foreachFilterCol = function(grid, filterData){ var rowsLength = rows.length; for ( var i = 0; i < rowsLength; i++){ foreachRow(grid, rows[i], filterData.col, filterData.filters); } }; // nested loop itself - foreachFilterCol, which in turn calls foreachRow var filterDataLength = filterData.length; for ( var j = 0; j < filterDataLength; j++){ foreachFilterCol( grid, filterData[j] ); } if (grid.api.core.raise.rowsVisibleChanged) { grid.api.core.raise.rowsVisibleChanged(); } // drop any invisible rows // keeping these, as needed with filtering for trees - we have to come back and make parent nodes visible if child nodes are selected in the filter // rows = rows.filter(function(row){ return row.visible; }); } return rows; }; return rowSearcher; }]); })(); (function() { var module = angular.module('ui.grid'); /** * @ngdoc object * @name ui.grid.class:RowSorter * @description RowSorter provides the default sorting mechanisms, * including guessing column types and applying appropriate sort * algorithms * */ module.service('rowSorter', ['$parse', 'uiGridConstants', function ($parse, uiGridConstants) { var currencyRegexStr = '(' + uiGridConstants.CURRENCY_SYMBOLS .map(function (a) { return '\\' + a; }) // Escape all the currency symbols ($ at least will jack up this regex) .join('|') + // Join all the symbols together with |s ')?'; // /^[-+]?[£$¤¥]?[\d,.]+%?$/ var numberStrRegex = new RegExp('^[-+]?' + currencyRegexStr + '[\\d,.]+' + currencyRegexStr + '%?$'); var rowSorter = { // Cache of sorting functions. Once we create them, we don't want to keep re-doing it // this takes a piece of data from the cell and tries to determine its type and what sorting // function to use for it colSortFnCache: {} }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name guessSortFn * @description Assigns a sort function to use based on the itemType in the column * @param {string} itemType one of 'number', 'boolean', 'string', 'date', 'object'. And * error will be thrown for any other type. * @returns {function} a sort function that will sort that type */ rowSorter.guessSortFn = function guessSortFn(itemType) { switch (itemType) { case "number": return rowSorter.sortNumber; case "numberStr": return rowSorter.sortNumberStr; case "boolean": return rowSorter.sortBool; case "string": return rowSorter.sortAlpha; case "date": return rowSorter.sortDate; case "object": return rowSorter.basicSort; default: throw new Error('No sorting function found for type:' + itemType); } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name handleNulls * @description Sorts nulls and undefined to the bottom (top when * descending). Called by each of the internal sorters before * attempting to sort. Note that this method is available on the core api * via gridApi.core.sortHandleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} null if there were no nulls/undefineds, otherwise returns * a sort value that should be passed back from the sort function */ rowSorter.handleNulls = function handleNulls(a, b) { // We want to allow zero values and false values to be evaluated in the sort function if ((!a && a !== 0 && a !== false) || (!b && b !== 0 && b !== false)) { // We want to force nulls and such to the bottom when we sort... which effectively is "greater than" if ((!a && a !== 0 && a !== false) && (!b && b !== 0 && b !== false)) { return 0; } else if (!a && a !== 0 && a !== false) { return 1; } else if (!b && b !== 0 && b !== false) { return -1; } } return null; }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name basicSort * @description Sorts any values that provide the < method, including strings * or numbers. Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.basicSort = function basicSort(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { if (a === b) { return 0; } if (a < b) { return -1; } return 1; } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortNumber * @description Sorts numerical values. Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortNumber = function sortNumber(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { return a - b; } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortNumberStr * @description Sorts numerical values that are stored in a string (i.e. parses them to numbers first). * Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortNumberStr = function sortNumberStr(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { var numA, // The parsed number form of 'a' numB, // The parsed number form of 'b' badA = false, badB = false; // Try to parse 'a' to a float numA = parseFloat(a.replace(/[^0-9.-]/g, '')); // If 'a' couldn't be parsed to float, flag it as bad if (isNaN(numA)) { badA = true; } // Try to parse 'b' to a float numB = parseFloat(b.replace(/[^0-9.-]/g, '')); // If 'b' couldn't be parsed to float, flag it as bad if (isNaN(numB)) { badB = true; } // We want bad ones to get pushed to the bottom... which effectively is "greater than" if (badA && badB) { return 0; } if (badA) { return 1; } if (badB) { return -1; } return numA - numB; } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortAlpha * @description Sorts string values. Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortAlpha = function sortAlpha(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { var strA = a.toString().toLowerCase(), strB = b.toString().toLowerCase(); return strA === strB ? 0 : (strA < strB ? -1 : 1); } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortDate * @description Sorts date values. Handles nulls and undefined through calling handleNulls. * Handles date strings by converting to Date object if not already an instance of Date * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortDate = function sortDate(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { if (!(a instanceof Date)) { a = new Date(a); } if (!(b instanceof Date)){ b = new Date(b); } var timeA = a.getTime(), timeB = b.getTime(); return timeA === timeB ? 0 : (timeA < timeB ? -1 : 1); } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sortBool * @description Sorts boolean values, true is considered larger than false. * Handles nulls and undefined through calling handleNulls * @param {object} a sort value a * @param {object} b sort value b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.sortBool = function sortBool(a, b) { var nulls = rowSorter.handleNulls(a, b); if ( nulls !== null ){ return nulls; } else { if (a && b) { return 0; } if (!a && !b) { return 0; } else { return a ? 1 : -1; } } }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name getSortFn * @description Get the sort function for the column. Looks first in * rowSorter.colSortFnCache using the column name, failing that it * looks at col.sortingAlgorithm (and puts it in the cache), failing that * it guesses the sort algorithm based on the data type. * * The cache currently seems a bit pointless, as none of the work we do is * processor intensive enough to need caching. Presumably in future we might * inspect the row data itself to guess the sort function, and in that case * it would make sense to have a cache, the infrastructure is in place to allow * that. * * @param {Grid} grid the grid to consider * @param {GridCol} col the column to find a function for * @param {array} rows an array of grid rows. Currently unused, but presumably in future * we might inspect the rows themselves to decide what sort of data might be there * @returns {function} the sort function chosen for the column */ rowSorter.getSortFn = function getSortFn(grid, col, rows) { var sortFn, item; // See if we already figured out what to use to sort the column and have it in the cache if (rowSorter.colSortFnCache[col.colDef.name]) { sortFn = rowSorter.colSortFnCache[col.colDef.name]; } // If the column has its OWN sorting algorithm, use that else if (col.sortingAlgorithm !== undefined) { sortFn = col.sortingAlgorithm; rowSorter.colSortFnCache[col.colDef.name] = col.sortingAlgorithm; } // Always default to sortAlpha when sorting after a cellFilter else if ( col.sortCellFiltered && col.cellFilter ){ sortFn = rowSorter.sortAlpha; rowSorter.colSortFnCache[col.colDef.name] = sortFn; } // Try and guess what sort function to use else { // Guess the sort function sortFn = rowSorter.guessSortFn(col.colDef.type); // If we found a sort function, cache it if (sortFn) { rowSorter.colSortFnCache[col.colDef.name] = sortFn; } else { // We assign the alpha sort because anything that is null/undefined will never get passed to // the actual sorting function. It will get caught in our null check and returned to be sorted // down to the bottom sortFn = rowSorter.sortAlpha; } } return sortFn; }; /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name prioritySort * @description Used where multiple columns are present in the sort criteria, * we determine which column should take precedence in the sort by sorting * the columns based on their sort.priority * * @param {gridColumn} a column a * @param {gridColumn} b column b * @returns {number} normal sort function, returns -ve, 0, +ve */ rowSorter.prioritySort = function (a, b) { // Both columns have a sort priority if (a.sort.priority !== undefined && b.sort.priority !== undefined) { // A is higher priority if (a.sort.priority < b.sort.priority) { return -1; } // Equal else if (a.sort.priority === b.sort.priority) { return 0; } // B is higher else { return 1; } } // Only A has a priority else if (a.sort.priority || a.sort.priority === 0) { return -1; } // Only B has a priority else if (b.sort.priority || b.sort.priority === 0) { return 1; } // Neither has a priority else { return 0; } }; /** * @ngdoc object * @name useExternalSorting * @propertyOf ui.grid.class:GridOptions * @description Prevents the internal sorting from executing. Events will * still be fired when the sort changes, and the sort information on * the columns will be updated, allowing an external sorter (for example, * server sorting) to be implemented. Defaults to false. * */ /** * @ngdoc method * @methodOf ui.grid.class:RowSorter * @name sort * @description sorts the grid * @param {Object} grid the grid itself * @param {array} rows the rows to be sorted * @param {array} columns the columns in which to look * for sort criteria * @returns {array} sorted rows */ rowSorter.sort = function rowSorterSort(grid, rows, columns) { // first make sure we are even supposed to do work if (!rows) { return; } if (grid.options.useExternalSorting){ return rows; } // Build the list of columns to sort by var sortCols = []; columns.forEach(function (col) { if (col.sort && !col.sort.ignoreSort && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) { sortCols.push(col); } }); // Sort the "sort columns" by their sort priority sortCols = sortCols.sort(rowSorter.prioritySort); // Now rows to sort by, maintain original order if (sortCols.length === 0) { return rows; } // Re-usable variables var col, direction; // put a custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome) var setIndex = function( row, idx ){ row.entity.$$uiGridIndex = idx; }; rows.forEach(setIndex); // IE9-11 HACK.... the 'rows' variable would be empty where we call rowSorter.getSortFn(...) below. We have to use a separate reference // var d = data.slice(0); var r = rows.slice(0); // Now actually sort the data var rowSortFn = function (rowA, rowB) { var tem = 0, idx = 0, sortFn; while (tem === 0 && idx < sortCols.length) { // grab the metadata for the rest of the logic col = sortCols[idx]; direction = sortCols[idx].sort.direction; sortFn = rowSorter.getSortFn(grid, col, r); var propA, propB; if ( col.sortCellFiltered ){ propA = grid.getCellDisplayValue(rowA, col); propB = grid.getCellDisplayValue(rowB, col); } else { propA = grid.getCellValue(rowA, col); propB = grid.getCellValue(rowB, col); } tem = sortFn(propA, propB); idx++; } // Chrome doesn't implement a stable sort function. If our sort returns 0 // (i.e. the items are equal), and we're at the last sort column in the list, // then return the previous order using our custom // index variable if (tem === 0 ) { return rowA.entity.$$uiGridIndex - rowB.entity.$$uiGridIndex; } // Made it this far, we don't have to worry about null & undefined if (direction === uiGridConstants.ASC) { return tem; } else { return 0 - tem; } }; var newRows = rows.sort(rowSortFn); // remove the custom index field on each row, used to make a stable sort out of unstable sorts (e.g. Chrome) var clearIndex = function( row, idx ){ delete row.entity.$$uiGridIndex; }; rows.forEach(clearIndex); return newRows; }; return rowSorter; }]); })(); (function() { var module = angular.module('ui.grid'); var bindPolyfill; if (typeof Function.prototype.bind !== "function") { bindPolyfill = function() { var slice = Array.prototype.slice; return function(context) { var fn = this, args = slice.call(arguments, 1); if (args.length) { return function() { return arguments.length ? fn.apply(context, args.concat(slice.call(arguments))) : fn.apply(context, args); }; } return function() { return arguments.length ? fn.apply(context, arguments) : fn.call(context); }; }; }; } function getStyles (elem) { var e = elem; if (typeof(e.length) !== 'undefined' && e.length) { e = elem[0]; } return e.ownerDocument.defaultView.getComputedStyle(e, null); } var rnumnonpx = new RegExp( "^(" + (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source + ")(?!px)[a-z%]+$", "i" ), // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(block|none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }; function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? 'border' : 'content' ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === 'width' ? 1 : 0, val = 0; var sides = ['Top', 'Right', 'Bottom', 'Left']; for ( ; i < 4; i += 2 ) { var side = sides[i]; // dump('side', side); // both box models exclude margin, so add it if we want it if ( extra === 'margin' ) { var marg = parseFloat(styles[extra + side]); if (!isNaN(marg)) { val += marg; } } // dump('val1', val); if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === 'content' ) { var padd = parseFloat(styles['padding' + side]); if (!isNaN(padd)) { val -= padd; // dump('val2', val); } } // at this point, extra isn't border nor margin, so remove border if ( extra !== 'margin' ) { var bordermarg = parseFloat(styles['border' + side + 'Width']); if (!isNaN(bordermarg)) { val -= bordermarg; // dump('val3', val); } } } else { // at this point, extra isn't content, so add padding var nocontentPad = parseFloat(styles['padding' + side]); if (!isNaN(nocontentPad)) { val += nocontentPad; // dump('val4', val); } // at this point, extra isn't content nor padding, so add border if ( extra !== 'padding') { var nocontentnopad = parseFloat(styles['border' + side + 'Width']); if (!isNaN(nocontentnopad)) { val += nocontentnopad; // dump('val5', val); } } } } // dump('augVal', val); return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val, // = name === 'width' ? elem.offsetWidth : elem.offsetHeight, styles = getStyles(elem), isBorderBox = styles['boxSizing'] === 'border-box'; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = styles[name]; if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( true || val === elem.style[ name ] ); // use 'true' instead of 'support.boxSizingReliable()' // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles var ret = ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ); // dump('ret', ret, val); return ret; } function getLineHeight(elm) { elm = angular.element(elm)[0]; var parent = elm.parentElement; if (!parent) { parent = document.getElementsByTagName('body')[0]; } return parseInt( getStyles(parent).fontSize ) || parseInt( getStyles(elm).fontSize ) || 16; } var uid = ['0', '0', '0']; var uidPrefix = 'uiGrid-'; /** * @ngdoc service * @name ui.grid.service:GridUtil * * @description Grid utility functions */ module.service('gridUtil', ['$log', '$window', '$document', '$http', '$templateCache', '$timeout', '$interval', '$injector', '$q', '$interpolate', 'uiGridConstants', function ($log, $window, $document, $http, $templateCache, $timeout, $interval, $injector, $q, $interpolate, uiGridConstants) { var s = { augmentWidthOrHeight: augmentWidthOrHeight, getStyles: getStyles, /** * @ngdoc method * @name createBoundedWrapper * @methodOf ui.grid.service:GridUtil * * @param {object} Object to bind 'this' to * @param {method} Method to bind * @returns {Function} The wrapper that performs the binding * * @description * Binds given method to given object. * * By means of a wrapper, ensures that ``method`` is always bound to * ``object`` regardless of its calling environment. * Iow, inside ``method``, ``this`` always points to ``object``. * * See http://alistapart.com/article/getoutbindingsituations * */ createBoundedWrapper: function(object, method) { return function() { return method.apply(object, arguments); }; }, /** * @ngdoc method * @name readableColumnName * @methodOf ui.grid.service:GridUtil * * @param {string} columnName Column name as a string * @returns {string} Column name appropriately capitalized and split apart * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid']); app.controller('MainCtrl', ['$scope', 'gridUtil', function ($scope, gridUtil) { $scope.name = 'firstName'; $scope.columnName = function(name) { return gridUtil.readableColumnName(name); }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <strong>Column name:</strong> <input ng-model="name" /> <br> <strong>Output:</strong> <span ng-bind="columnName(name)"></span> </div> </file> </example> */ readableColumnName: function (columnName) { // Convert underscores to spaces if (typeof(columnName) === 'undefined' || columnName === undefined || columnName === null) { return columnName; } if (typeof(columnName) !== 'string') { columnName = String(columnName); } return columnName.replace(/_+/g, ' ') // Replace a completely all-capsed word with a first-letter-capitalized version .replace(/^[A-Z]+$/, function (match) { return angular.lowercase(angular.uppercase(match.charAt(0)) + match.slice(1)); }) // Capitalize the first letter of words .replace(/([\w\u00C0-\u017F]+)/g, function (match) { return angular.uppercase(match.charAt(0)) + match.slice(1); }) // Put a space in between words that have partial capilizations (i.e. 'firstName' becomes 'First Name') // .replace(/([A-Z]|[A-Z]\w+)([A-Z])/g, "$1 $2"); // .replace(/(\w+?|\w)([A-Z])/g, "$1 $2"); .replace(/(\w+?(?=[A-Z]))/g, '$1 '); }, /** * @ngdoc method * @name getColumnsFromData * @methodOf ui.grid.service:GridUtil * @description Return a list of column names, given a data set * * @param {string} data Data array for grid * @returns {Object} Column definitions with field accessor and column name * * @example <pre> var data = [ { firstName: 'Bob', lastName: 'Jones' }, { firstName: 'Frank', lastName: 'Smith' } ]; var columnDefs = GridUtil.getColumnsFromData(data, excludeProperties); columnDefs == [ { field: 'firstName', name: 'First Name' }, { field: 'lastName', name: 'Last Name' } ]; </pre> */ getColumnsFromData: function (data, excludeProperties) { var columnDefs = []; if (!data || typeof(data[0]) === 'undefined' || data[0] === undefined) { return []; } if (angular.isUndefined(excludeProperties)) { excludeProperties = []; } var item = data[0]; angular.forEach(item,function (prop, propName) { if ( excludeProperties.indexOf(propName) === -1){ columnDefs.push({ name: propName }); } }); return columnDefs; }, /** * @ngdoc method * @name newId * @methodOf ui.grid.service:GridUtil * @description Return a unique ID string * * @returns {string} Unique string * * @example <pre> var id = GridUtil.newId(); # 1387305700482; </pre> */ newId: (function() { var seedId = new Date().getTime(); return function() { return seedId += 1; }; })(), /** * @ngdoc method * @name getTemplate * @methodOf ui.grid.service:GridUtil * @description Get's template from cache / element / url * * @param {string|element|promise} Either a string representing the template id, a string representing the template url, * an jQuery/Angualr element, or a promise that returns the template contents to use. * @returns {object} a promise resolving to template contents * * @example <pre> GridUtil.getTemplate(url).then(function (contents) { alert(contents); }) </pre> */ getTemplate: function (template) { // Try to fetch the template out of the templateCache if ($templateCache.get(template)) { return s.postProcessTemplate($templateCache.get(template)); } // See if the template is itself a promise if (template.hasOwnProperty('then')) { return template.then(s.postProcessTemplate); } // If the template is an element, return the element try { if (angular.element(template).length > 0) { return $q.when(template).then(s.postProcessTemplate); } } catch (err){ //do nothing; not valid html } s.logDebug('fetching url', template); // Default to trying to fetch the template as a url with $http return $http({ method: 'GET', url: template}) .then( function (result) { var templateHtml = result.data.trim(); //put in templateCache for next call $templateCache.put(template, templateHtml); return templateHtml; }, function (err) { throw new Error("Could not get template " + template + ": " + err); } ) .then(s.postProcessTemplate); }, // postProcessTemplate: function (template) { var startSym = $interpolate.startSymbol(), endSym = $interpolate.endSymbol(); // If either of the interpolation symbols have been changed, we need to alter this template if (startSym !== '{{' || endSym !== '}}') { template = template.replace(/\{\{/g, startSym); template = template.replace(/\}\}/g, endSym); } return $q.when(template); }, /** * @ngdoc method * @name guessType * @methodOf ui.grid.service:GridUtil * @description guesses the type of an argument * * @param {string/number/bool/object} item variable to examine * @returns {string} one of the following * - 'string' * - 'boolean' * - 'number' * - 'date' * - 'object' */ guessType : function (item) { var itemType = typeof(item); // Check for numbers and booleans switch (itemType) { case "number": case "boolean": case "string": return itemType; default: if (angular.isDate(item)) { return "date"; } return "object"; } }, /** * @ngdoc method * @name elementWidth * @methodOf ui.grid.service:GridUtil * * @param {element} element DOM element * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element * * @returns {number} Element width in pixels, accounting for any borders, etc. */ elementWidth: function (elem) { }, /** * @ngdoc method * @name elementHeight * @methodOf ui.grid.service:GridUtil * * @param {element} element DOM element * @param {string} [extra] Optional modifier for calculation. Use 'margin' to account for margins on element * * @returns {number} Element height in pixels, accounting for any borders, etc. */ elementHeight: function (elem) { }, // Thanks to http://stackoverflow.com/a/13382873/888165 getScrollbarWidth: function() { var outer = document.createElement("div"); outer.style.visibility = "hidden"; outer.style.width = "100px"; outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps document.body.appendChild(outer); var widthNoScroll = outer.offsetWidth; // force scrollbars outer.style.overflow = "scroll"; // add innerdiv var inner = document.createElement("div"); inner.style.width = "100%"; outer.appendChild(inner); var widthWithScroll = inner.offsetWidth; // remove divs outer.parentNode.removeChild(outer); return widthNoScroll - widthWithScroll; }, swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }, fakeElement: function( elem, options, callback, args ) { var ret, name, newElement = angular.element(elem).clone()[0]; for ( name in options ) { newElement.style[ name ] = options[ name ]; } angular.element(document.body).append(newElement); ret = callback.call( newElement, newElement ); angular.element(newElement).remove(); return ret; }, /** * @ngdoc method * @name normalizeWheelEvent * @methodOf ui.grid.service:GridUtil * * @param {event} event A mouse wheel event * * @returns {event} A normalized event * * @description * Given an event from this list: * * `wheel, mousewheel, DomMouseScroll, MozMousePixelScroll` * * "normalize" it * so that it stays consistent no matter what browser it comes from (i.e. scale it correctly and make sure the direction is right.) */ normalizeWheelEvent: function (event) { // var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll']; // var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll']; var lowestDelta, lowestDeltaXY; var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, absDeltaXY = 0, fn; // event = $.event.fix(orgEvent); // event.type = 'mousewheel'; // NOTE: jQuery masks the event and stores it in the event as originalEvent if (orgEvent.originalEvent) { orgEvent = orgEvent.originalEvent; } // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; } if ( orgEvent.detail ) { delta = orgEvent.detail * -1; } // At a minimum, setup the deltaY to be delta deltaY = delta; // Firefox < 17 related to DOMMouseScroll event if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = delta * -1; } // New school wheel delta (wheel event) if ( orgEvent.deltaY ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( orgEvent.deltaX ) { deltaX = orgEvent.deltaX; delta = deltaX * -1; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX; } // Look for lowest delta to normalize the delta values absDelta = Math.abs(delta); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; } absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; } // Get a whole value for the deltas fn = delta > 0 ? 'floor' : 'ceil'; delta = Math[fn](delta / lowestDelta); deltaX = Math[fn](deltaX / lowestDeltaXY); deltaY = Math[fn](deltaY / lowestDeltaXY); return { delta: delta, deltaX: deltaX, deltaY: deltaY }; }, // Stolen from Modernizr // TODO: make this, and everythign that flows from it, robust //http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ isTouchEnabled: function() { var bool; if (('ontouchstart' in $window) || $window.DocumentTouch && $document instanceof DocumentTouch) { bool = true; } return bool; }, isNullOrUndefined: function(obj) { if (obj === undefined || obj === null) { return true; } return false; }, endsWith: function(str, suffix) { if (!str || !suffix || typeof str !== "string") { return false; } return str.indexOf(suffix, str.length - suffix.length) !== -1; }, arrayContainsObjectWithProperty: function(array, propertyName, propertyValue) { var found = false; angular.forEach(array, function (object) { if (object[propertyName] === propertyValue) { found = true; } }); return found; }, //// Shim requestAnimationFrame //requestAnimationFrame: $window.requestAnimationFrame && $window.requestAnimationFrame.bind($window) || // $window.webkitRequestAnimationFrame && $window.webkitRequestAnimationFrame.bind($window) || // function(fn) { // return $timeout(fn, 10, false); // }, numericAndNullSort: function (a, b) { if (a === null) { return 1; } if (b === null) { return -1; } if (a === null && b === null) { return 0; } return a - b; }, // Disable ngAnimate animations on an element disableAnimations: function (element) { var $animate; try { $animate = $injector.get('$animate'); $animate.enabled(false, element); } catch (e) {} }, enableAnimations: function (element) { var $animate; try { $animate = $injector.get('$animate'); $animate.enabled(true, element); return $animate; } catch (e) {} }, // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?) nextUid: function nextUid() { var index = uid.length; var digit; while (index) { index--; digit = uid[index].charCodeAt(0); if (digit === 57 /*'9'*/) { uid[index] = 'A'; return uidPrefix + uid.join(''); } if (digit === 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uidPrefix + uid.join(''); } } uid.unshift('0'); return uidPrefix + uid.join(''); }, // Blatantly stolen from Angular as it isn't exposed (yet. 2.0 maybe?) hashKey: function hashKey(obj) { var objType = typeof obj, key; if (objType === 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) === 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (typeof(obj.$$hashKey) !== 'undefined' && obj.$$hashKey) { key = obj.$$hashKey; } else if (key === undefined) { key = obj.$$hashKey = s.nextUid(); } } else { key = obj; } return objType + ':' + key; }, resetUids: function () { uid = ['0', '0', '0']; }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil * @name logError * @description wraps the $log method, allowing us to choose different * treatment within ui-grid if we so desired. At present we only log * error messages if uiGridConstants.LOG_ERROR_MESSAGES is set to true * @param {string} logMessage message to be logged to the console * */ logError: function( logMessage ){ if ( uiGridConstants.LOG_ERROR_MESSAGES ){ $log.error( logMessage ); } }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil * @name logWarn * @description wraps the $log method, allowing us to choose different * treatment within ui-grid if we so desired. At present we only log * warning messages if uiGridConstants.LOG_WARN_MESSAGES is set to true * @param {string} logMessage message to be logged to the console * */ logWarn: function( logMessage ){ if ( uiGridConstants.LOG_WARN_MESSAGES ){ $log.warn( logMessage ); } }, /** * @ngdoc method * @methodOf ui.grid.service:GridUtil * @name logDebug * @description wraps the $log method, allowing us to choose different * treatment within ui-grid if we so desired. At present we only log * debug messages if uiGridConstants.LOG_DEBUG_MESSAGES is set to true * */ logDebug: function() { if ( uiGridConstants.LOG_DEBUG_MESSAGES ){ $log.debug.apply($log, arguments); } } }; ['width', 'height'].forEach(function (name) { var capsName = angular.uppercase(name.charAt(0)) + name.substr(1); s['element' + capsName] = function (elem, extra) { var e = elem; if (e && typeof(e.length) !== 'undefined' && e.length) { e = elem[0]; } if (e) { var styles = getStyles(e); return e.offsetWidth === 0 && rdisplayswap.test(styles.display) ? s.swap(e, cssShow, function() { return getWidthOrHeight(e, name, extra ); }) : getWidthOrHeight( e, name, extra ); } else { return null; } }; s['outerElement' + capsName] = function (elem, margin) { return elem ? s['element' + capsName].call(this, elem, margin ? 'margin' : 'border') : null; }; }); // http://stackoverflow.com/a/24107550/888165 s.closestElm = function closestElm(el, selector) { if (typeof(el.length) !== 'undefined' && el.length) { el = el[0]; } var matchesFn; // find vendor prefix ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) { if (typeof document.body[fn] === 'function') { matchesFn = fn; return true; } return false; }); // traverse parents var parent; while (el !== null) { parent = el.parentElement; if (parent !== null && parent[matchesFn](selector)) { return parent; } el = parent; } return null; }; s.type = function (obj) { var text = Function.prototype.toString.call(obj.constructor); return text.match(/function (.*?)\(/)[1]; }; s.getBorderSize = function getBorderSize(elem, borderType) { if (typeof(elem.length) !== 'undefined' && elem.length) { elem = elem[0]; } var styles = getStyles(elem); // If a specific border is supplied, like 'top', read the 'borderTop' style property if (borderType) { borderType = 'border' + borderType.charAt(0).toUpperCase() + borderType.slice(1); } else { borderType = 'border'; } borderType += 'Width'; var val = parseInt(styles[borderType], 10); if (isNaN(val)) { return 0; } else { return val; } }; // http://stackoverflow.com/a/22948274/888165 // TODO: Opera? Mobile? s.detectBrowser = function detectBrowser() { var userAgent = $window.navigator.userAgent; var browsers = {chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer|trident\//i}; for (var key in browsers) { if (browsers[key].test(userAgent)) { return key; } } return 'unknown'; }; // Borrowed from https://github.com/othree/jquery.rtl-scroll-type // Determine the scroll "type" this browser is using for RTL s.rtlScrollType = function rtlScrollType() { if (rtlScrollType.type) { return rtlScrollType.type; } var definer = angular.element('<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>')[0], type = 'reverse'; document.body.appendChild(definer); if (definer.scrollLeft > 0) { type = 'default'; } else { definer.scrollLeft = 1; if (definer.scrollLeft === 0) { type = 'negative'; } } angular.element(definer).remove(); rtlScrollType.type = type; return type; }; /** * @ngdoc method * @name normalizeScrollLeft * @methodOf ui.grid.service:GridUtil * * @param {element} element The element to get the `scrollLeft` from. * @param {grid} grid - grid used to normalize (uses the rtl property) * * @returns {number} A normalized scrollLeft value for the current browser. * * @description * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method normalizes them */ s.normalizeScrollLeft = function normalizeScrollLeft(element, grid) { if (typeof(element.length) !== 'undefined' && element.length) { element = element[0]; } var scrollLeft = element.scrollLeft; if (grid.isRTL()) { switch (s.rtlScrollType()) { case 'default': return element.scrollWidth - scrollLeft - element.clientWidth; case 'negative': return Math.abs(scrollLeft); case 'reverse': return scrollLeft; } } return scrollLeft; }; /** * @ngdoc method * @name denormalizeScrollLeft * @methodOf ui.grid.service:GridUtil * * @param {element} element The element to normalize the `scrollLeft` value for * @param {number} scrollLeft The `scrollLeft` value to denormalize. * @param {grid} grid The grid that owns the scroll event. * * @returns {number} A normalized scrollLeft value for the current browser. * * @description * Browsers currently handle RTL in different ways, resulting in inconsistent scrollLeft values. This method denormalizes a value for the current browser. */ s.denormalizeScrollLeft = function denormalizeScrollLeft(element, scrollLeft, grid) { if (typeof(element.length) !== 'undefined' && element.length) { element = element[0]; } if (grid.isRTL()) { switch (s.rtlScrollType()) { case 'default': // Get the max scroll for the element var maxScrollLeft = element.scrollWidth - element.clientWidth; // Subtract the current scroll amount from the max scroll return maxScrollLeft - scrollLeft; case 'negative': return scrollLeft * -1; case 'reverse': return scrollLeft; } } return scrollLeft; }; /** * @ngdoc method * @name preEval * @methodOf ui.grid.service:GridUtil * * @param {string} path Path to evaluate * * @returns {string} A path that is normalized. * * @description * Takes a field path and converts it to bracket notation to allow for special characters in path * @example * <pre> * gridUtil.preEval('property') == 'property' * gridUtil.preEval('nested.deep.prop-erty') = "nested['deep']['prop-erty']" * </pre> */ s.preEval = function (path) { var m = uiGridConstants.BRACKET_REGEXP.exec(path); if (m) { return (m[1] ? s.preEval(m[1]) : m[1]) + m[2] + (m[3] ? s.preEval(m[3]) : m[3]); } else { path = path.replace(uiGridConstants.APOS_REGEXP, '\\\''); var parts = path.split(uiGridConstants.DOT_REGEXP); var preparsed = [parts.shift()]; // first item must be var notation, thus skip angular.forEach(parts, function (part) { preparsed.push(part.replace(uiGridConstants.FUNC_REGEXP, '\']$1')); }); return preparsed.join('[\''); } }; /** * @ngdoc method * @name debounce * @methodOf ui.grid.service:GridUtil * * @param {function} func function to debounce * @param {number} wait milliseconds to delay * @param {boolean} immediate execute before delay * * @returns {function} A function that can be executed as debounced function * * @description * Copied from https://github.com/shahata/angular-debounce * Takes a function, decorates it to execute only 1 time after multiple calls, and returns the decorated function * @example * <pre> * var debouncedFunc = gridUtil.debounce(function(){alert('debounced');}, 500); * debouncedFunc(); * debouncedFunc(); * debouncedFunc(); * </pre> */ s.debounce = function (func, wait, immediate) { var timeout, args, context, result; function debounce() { /* jshint validthis:true */ context = this; args = arguments; var later = function () { timeout = null; if (!immediate) { result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (timeout) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; } debounce.cancel = function () { $timeout.cancel(timeout); timeout = null; }; return debounce; }; /** * @ngdoc method * @name throttle * @methodOf ui.grid.service:GridUtil * * @param {function} func function to throttle * @param {number} wait milliseconds to delay after first trigger * @param {Object} params to use in throttle. * * @returns {function} A function that can be executed as throttled function * * @description * Adapted from debounce function (above) * Potential keys for Params Object are: * trailing (bool) - whether to trigger after throttle time ends if called multiple times * Updated to use $interval rather than $timeout, as protractor (e2e tests) is able to work with $interval, * but not with $timeout * * Note that when using throttle, you need to use throttle to create a new function upfront, then use the function * return from that call each time you need to call throttle. If you call throttle itself repeatedly, the lastCall * variable will get overwritten and the throttling won't work * * @example * <pre> * var throttledFunc = gridUtil.throttle(function(){console.log('throttled');}, 500, {trailing: true}); * throttledFunc(); //=> logs throttled * throttledFunc(); //=> queues attempt to log throttled for ~500ms (since trailing param is truthy) * throttledFunc(); //=> updates arguments to keep most-recent request, but does not do anything else. * </pre> */ s.throttle = function(func, wait, options){ options = options || {}; var lastCall = 0, queued = null, context, args; function runFunc(endDate){ lastCall = +new Date(); func.apply(context, args); $interval(function(){ queued = null; }, 0, 1); } return function(){ /* jshint validthis:true */ context = this; args = arguments; if (queued === null){ var sinceLast = +new Date() - lastCall; if (sinceLast > wait){ runFunc(); } else if (options.trailing){ queued = $interval(runFunc, wait - sinceLast, 1); } } }; }; s.on = {}; s.off = {}; s._events = {}; s.addOff = function (eventName) { s.off[eventName] = function (elm, fn) { var idx = s._events[eventName].indexOf(fn); if (idx > 0) { s._events[eventName].removeAt(idx); } }; }; var mouseWheeltoBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], nullLowestDeltaTimeout, lowestDelta; s.on.mousewheel = function (elm, fn) { if (!elm || !fn) { return; } var $elm = angular.element(elm); // Store the line height and page height for this particular element $elm.data('mousewheel-line-height', getLineHeight($elm)); $elm.data('mousewheel-page-height', s.elementHeight($elm)); if (!$elm.data('mousewheel-callbacks')) { $elm.data('mousewheel-callbacks', {}); } var cbs = $elm.data('mousewheel-callbacks'); cbs[fn] = (Function.prototype.bind || bindPolyfill).call(mousewheelHandler, $elm[0], fn); // Bind all the mousew heel events for ( var i = mouseWheeltoBind.length; i; ) { $elm.on(mouseWheeltoBind[--i], cbs[fn]); } }; s.off.mousewheel = function (elm, fn) { var $elm = angular.element(this); var cbs = $elm.data('mousewheel-callbacks'); var handler = cbs[fn]; if (handler) { for ( var i = mouseWheeltoBind.length; i; ) { $elm.off(mouseWheeltoBind[--i], handler); } } delete cbs[fn]; if (Object.keys(cbs).length === 0) { $elm.removeData('mousewheel-line-height'); $elm.removeData('mousewheel-page-height'); $elm.removeData('mousewheel-callbacks'); } }; function mousewheelHandler(fn, event) { var $elm = angular.element(this); var delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, offsetX = 0, offsetY = 0; // jQuery masks events if (event.originalEvent) { event = event.originalEvent; } if ( 'detail' in event ) { deltaY = event.detail * -1; } if ( 'wheelDelta' in event ) { deltaY = event.wheelDelta; } if ( 'wheelDeltaY' in event ) { deltaY = event.wheelDeltaY; } if ( 'wheelDeltaX' in event ) { deltaX = event.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) if ( 'deltaY' in event ) { deltaY = event.deltaY * -1; delta = deltaY; } if ( 'deltaX' in event ) { deltaX = event.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } // No change actually happened, no reason to go any further if ( deltaY === 0 && deltaX === 0 ) { return; } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages if ( event.deltaMode === 1 ) { var lineHeight = $elm.data('mousewheel-line-height'); delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; } else if ( event.deltaMode === 2 ) { var pageHeight = $elm.data('mousewheel-page-height'); delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(event, absDelta) ) { lowestDelta /= 40; } } // Get a whole, normalized value for the deltas delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); event.deltaMode = 0; // Normalise offsetX and offsetY properties // if ($elm[0].getBoundingClientRect ) { // var boundingRect = $(elm)[0].getBoundingClientRect(); // offsetX = event.clientX - boundingRect.left; // offsetY = event.clientY - boundingRect.top; // } // event.deltaX = deltaX; // event.deltaY = deltaY; // event.deltaFactor = lowestDelta; var newEvent = { originalEvent: event, deltaX: deltaX, deltaY: deltaY, deltaFactor: lowestDelta, preventDefault: function () { event.preventDefault(); } }; // Clearout lowestDelta after sometime to better // handle multiple device types that give // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); fn.call($elm[0], newEvent); } function nullLowestDelta() { lowestDelta = null; } function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas // by 40 to try and get a more usable deltaFactor. // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. return orgEvent.type === 'mousewheel' && absDelta % 120 === 0; } return s; }]); // Add 'px' to the end of a number string if it doesn't have it already module.filter('px', function() { return function(str) { if (str.match(/^[\d\.]+$/)) { return str + 'px'; } else { return str; } }; }); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { var lang = { aggregate: { label: 'položky' }, groupPanel: { description: 'Přesuntě záhlaví zde pro vytvoření skupiny dle sloupce.' }, search: { placeholder: 'Hledat...', showingItems: 'Zobrazuji položky:', selectedItems: 'Vybrané položky:', totalItems: 'Celkem položek:', size: 'Velikost strany:', first: 'První strana', next: 'Další strana', previous: 'Předchozí strana', last: 'Poslední strana' }, menu: { text: 'Vyberte sloupec:' }, sort: { ascending: 'Seřadit od A-Z', descending: 'Seřadit od Z-A', remove: 'Odebrat seřazení' }, column: { hide: 'Schovat sloupec' }, aggregation: { count: 'celkem řádků: ', sum: 'celkem: ', avg: 'avg: ', min: 'min.: ', max: 'max.: ' }, pinning: { pinLeft: 'Zamknout v levo', pinRight: 'Zamknout v pravo', unpin: 'Odemknout' }, gridMenu: { columns: 'Sloupce:', importerTitle: 'Importovat soubor', exporterAllAsCsv: 'Exportovat všechny data do csv', exporterVisibleAsCsv: 'Exportovat viditelné data do csv', exporterSelectedAsCsv: 'Exportovat vybranné data do csv', exporterAllAsPdf: 'Exportovat všechny data do pdf', exporterVisibleAsPdf: 'Exportovat viditelné data do pdf', exporterSelectedAsPdf: 'Exportovat vybranné data do pdf' }, importer: { noHeaders: 'Názvy sloupců se nepodařilo získat, obsahuje soubor záhlaví?', noObjects: 'Data se nepodařilo zpracovat, obsahuje soubor řádky mimo záhlaví?', invalidCsv: 'Soubor nelze zpracovat, jedná se CSV?', invalidJson: 'Soubor nelze zpracovat, je to JSON?', jsonNotArray: 'Soubor musí obsahovat json. Ukončuji..' }, pagination: { sizes: 'položek na stránku', totalItems: 'položek' }, grouping: { group: 'Seskupit', ungroup: 'Odebrat seskupení', aggregate_count: 'Agregace: Count', aggregate_sum: 'Agregace: Sum', aggregate_max: 'Agregace: Max', aggregate_min: 'Agregace: Min', aggregate_avg: 'Agregace: Avg', aggregate_remove: 'Agregace: Odebrat' } }; // support varianty of different czech keys. $delegate.add('cs', lang); $delegate.add('cz', lang); $delegate.add('cs-cz', lang); $delegate.add('cs-CZ', lang); return $delegate; }]); }]); })(); (function(){ angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('da', { aggregate:{ label: 'artikler' }, groupPanel:{ description: 'Grupér rækker udfra en kolonne ved at trække dens overskift hertil.' }, search:{ placeholder: 'Søg...', showingItems: 'Viste rækker:', selectedItems: 'Valgte rækker:', totalItems: 'Rækker totalt:', size: 'Side størrelse:', first: 'Første side', next: 'Næste side', previous: 'Forrige side', last: 'Sidste side' }, menu:{ text: 'Vælg kolonner:' }, column: { hide: 'Skjul kolonne' }, aggregation: { count: 'samlede rækker: ', sum: 'smalede: ', avg: 'gns: ', min: 'min: ', max: 'max: ' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('de', { aggregate: { label: 'Eintrag' }, groupPanel: { description: 'Ziehen Sie eine Spaltenüberschrift hierhin, um nach dieser Spalte zu gruppieren.' }, search: { placeholder: 'Suche...', showingItems: 'Zeige Einträge:', selectedItems: 'Ausgewählte Einträge:', totalItems: 'Einträge gesamt:', size: 'Einträge pro Seite:', first: 'Erste Seite', next: 'Nächste Seite', previous: 'Vorherige Seite', last: 'Letzte Seite' }, menu: { text: 'Spalten auswählen:' }, sort: { ascending: 'aufsteigend sortieren', descending: 'absteigend sortieren', remove: 'Sortierung zurücksetzen' }, column: { hide: 'Spalte ausblenden' }, aggregation: { count: 'Zeilen insgesamt: ', sum: 'gesamt: ', avg: 'Durchschnitt: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Links anheften', pinRight: 'Rechts anheften', unpin: 'Lösen' }, gridMenu: { columns: 'Spalten:', importerTitle: 'Datei importieren', exporterAllAsCsv: 'Alle Daten als CSV exportieren', exporterVisibleAsCsv: 'sichtbare Daten als CSV exportieren', exporterSelectedAsCsv: 'markierte Daten als CSV exportieren', exporterAllAsPdf: 'Alle Daten als PDF exportieren', exporterVisibleAsPdf: 'sichtbare Daten als PDF exportieren', exporterSelectedAsPdf: 'markierte Daten als CSV exportieren' }, importer: { noHeaders: 'Es konnten keine Spaltennamen ermittelt werden. Sind in der Datei Spaltendefinitionen enthalten?', noObjects: 'Es konnten keine Zeileninformationen gelesen werden, Sind in der Datei außer den Spaltendefinitionen auch Daten enthalten?', invalidCsv: 'Die Datei konnte nicht eingelesen werden, ist es eine gültige CSV-Datei?', invalidJson: 'Die Datei konnte nicht eingelesen werden. Enthält sie gültiges JSON?', jsonNotArray: 'Die importierte JSON-Datei muß ein Array enthalten. Breche Import ab.' }, pagination: { sizes: 'Einträge pro Seite', totalItems: 'Einträge' }, grouping: { group: 'Gruppieren', ungroup: 'Gruppierung aufheben', aggregate_count: 'Agg: Anzahl', aggregate_sum: 'Agg: Summe', aggregate_max: 'Agg: Maximum', aggregate_min: 'Agg: Minimum', aggregate_avg: 'Agg: Mittelwert', aggregate_remove: 'Aggregation entfernen' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('en', { aggregate: { label: 'items' }, groupPanel: { description: 'Drag a column header here and drop it to group by that column.' }, search: { placeholder: 'Search...', showingItems: 'Showing Items:', selectedItems: 'Selected Items:', totalItems: 'Total Items:', size: 'Page Size:', first: 'First Page', next: 'Next Page', previous: 'Previous Page', last: 'Last Page' }, menu: { text: 'Choose Columns:' }, sort: { ascending: 'Sort Ascending', descending: 'Sort Descending', remove: 'Remove Sort' }, column: { hide: 'Hide Column' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Pin Left', pinRight: 'Pin Right', unpin: 'Unpin' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' }, pagination: { sizes: 'items per page', totalItems: 'items', of: 'of' }, grouping: { group: 'Group', ungroup: 'Ungroup', aggregate_count: 'Agg: Count', aggregate_sum: 'Agg: Sum', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Avg', aggregate_remove: 'Agg: Remove' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('es', { aggregate: { label: 'Artículos' }, groupPanel: { description: 'Arrastre un encabezado de columna aquí y suéltelo para agrupar por esa columna.' }, search: { placeholder: 'Buscar...', showingItems: 'Artículos Mostrados:', selectedItems: 'Artículos Seleccionados:', totalItems: 'Artículos Totales:', size: 'Tamaño de Página:', first: 'Primera Página', next: 'Página Siguiente', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Elegir columnas:' }, sort: { ascending: 'Orden Ascendente', descending: 'Orden Descendente', remove: 'Sin Ordenar' }, column: { hide: 'Ocultar la columna' }, aggregation: { count: 'filas totales: ', sum: 'total: ', avg: 'media: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fijar a la Izquierda', pinRight: 'Fijar a la Derecha', unpin: 'Quitar Fijación' }, gridMenu: { columns: 'Columnas:', importerTitle: 'Importar archivo', exporterAllAsCsv: 'Exportar todo como csv', exporterVisibleAsCsv: 'Exportar vista como csv', exporterSelectedAsCsv: 'Exportar selección como csv', exporterAllAsPdf: 'Exportar todo como pdf', exporterVisibleAsPdf: 'Exportar vista como pdf', exporterSelectedAsPdf: 'Exportar selección como pdf' }, importer: { noHeaders: 'No fue posible derivar los nombres de las columnas, ¿tiene encabezados el archivo?', noObjects: 'No fue posible obtener registros, ¿contiene datos el archivo, aparte de los encabezados?', invalidCsv: 'No fue posible procesar el archivo, ¿es un CSV válido?', invalidJson: 'No fue posible procesar el archivo, ¿es un Json válido?', jsonNotArray: 'El archivo json importado debe contener un array, abortando.' }, pagination: { sizes: 'registros por página', totalItems: 'registros', of: 'de' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Cont', aggregate_sum: 'Agr: Sum', aggregate_max: 'Agr: Máx', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Prom', aggregate_remove: 'Agr: Quitar' } }); return $delegate; }]); }]); })(); /** * Translated by: R. Salarmehr * M. Hosseynzade * Using Vajje.com online dictionary. */ (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('fa', { aggregate: { label: 'قلم' }, groupPanel: { description: 'عنوان یک ستون را بگیر و به گروهی از آن ستون رها کن.' }, search: { placeholder: 'جستجو...', showingItems: 'نمایش اقلام:', selectedItems: 'قلم\u200cهای انتخاب شده:', totalItems: 'مجموع اقلام:', size: 'اندازه\u200cی صفحه:', first: 'اولین صفحه', next: 'صفحه\u200cی\u200cبعدی', previous: 'صفحه\u200cی\u200c قبلی', last: 'آخرین صفحه' }, menu: { text: 'ستون\u200cهای انتخابی:' }, sort: { ascending: 'ترتیب صعودی', descending: 'ترتیب نزولی', remove: 'حذف مرتب کردن' }, column: { hide: 'پنهان\u200cکردن ستون' }, aggregation: { count: 'تعداد: ', sum: 'مجموع: ', avg: 'میانگین: ', min: 'کمترین: ', max: 'بیشترین: ' }, pinning: { pinLeft: 'پین کردن سمت چپ', pinRight: 'پین کردن سمت راست', unpin: 'حذف پین' }, gridMenu: { columns: 'ستون\u200cها:', importerTitle: 'وارد کردن فایل', exporterAllAsCsv: 'خروجی تمام داده\u200cها در فایل csv', exporterVisibleAsCsv: 'خروجی داده\u200cهای قابل مشاهده در فایل csv', exporterSelectedAsCsv: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل csv', exporterAllAsPdf: 'خروجی تمام داده\u200cها در فایل pdf', exporterVisibleAsPdf: 'خروجی داده\u200cهای قابل مشاهده در فایل pdf', exporterSelectedAsPdf: 'خروجی داده\u200cهای انتخاب\u200cشده در فایل pdf' }, importer: { noHeaders: 'نام ستون قابل استخراج نیست. آیا فایل عنوان دارد؟', noObjects: 'اشیا قابل استخراج نیستند. آیا به جز عنوان\u200cها در فایل داده وجود دارد؟', invalidCsv: 'فایل قابل پردازش نیست. آیا فرمت csv معتبر است؟', invalidJson: 'فایل قابل پردازش نیست. آیا فرمت json معتبر است؟', jsonNotArray: 'فایل json وارد شده باید حاوی آرایه باشد. عملیات ساقط شد.' }, pagination: { sizes: 'اقلام در هر صفحه', totalItems: 'اقلام', of: 'از' }, grouping: { group: 'گروه\u200cبندی', ungroup: 'حذف گروه\u200cبندی', aggregate_count: 'Agg: تعداد', aggregate_sum: 'Agg: جمع', aggregate_max: 'Agg: بیشینه', aggregate_min: 'Agg: کمینه', aggregate_avg: 'Agg: میانگین', aggregate_remove: 'Agg: حذف' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('fi', { aggregate: { label: 'rivit' }, groupPanel: { description: 'Raahaa ja pudota otsikko tähän ryhmittääksesi sarakkeen mukaan.' }, search: { placeholder: 'Hae...', showingItems: 'Näytetään rivejä:', selectedItems: 'Valitut rivit:', totalItems: 'Rivejä yht.:', size: 'Näytä:', first: 'Ensimmäinen sivu', next: 'Seuraava sivu', previous: 'Edellinen sivu', last: 'Viimeinen sivu' }, menu: { text: 'Valitse sarakkeet:' }, sort: { ascending: 'Järjestä nouseva', descending: 'Järjestä laskeva', remove: 'Poista järjestys' }, column: { hide: 'Piilota sarake' }, aggregation: { count: 'Rivejä yht.: ', sum: 'Summa: ', avg: 'K.a.: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Lukitse vasemmalle', pinRight: 'Lukitse oikealle', unpin: 'Poista lukitus' }, gridMenu: { columns: 'Sarakkeet:', importerTitle: 'Tuo tiedosto', exporterAllAsCsv: 'Vie tiedot csv-muodossa', exporterVisibleAsCsv: 'Vie näkyvä tieto csv-muodossa', exporterSelectedAsCsv: 'Vie valittu tieto csv-muodossa', exporterAllAsPdf: 'Vie tiedot pdf-muodossa', exporterVisibleAsPdf: 'Vie näkyvä tieto pdf-muodossa', exporterSelectedAsPdf: 'Vie valittu tieto pdf-muodossa' }, importer: { noHeaders: 'Sarakkeen nimiä ei voitu päätellä, onko tiedostossa otsikkoriviä?', noObjects: 'Tietoja ei voitu lukea, onko tiedostossa muuta kuin otsikkot?', invalidCsv: 'Tiedostoa ei voitu käsitellä, oliko se CSV-muodossa?', invalidJson: 'Tiedostoa ei voitu käsitellä, oliko se JSON-muodossa?', jsonNotArray: 'Tiedosto ei sisältänyt taulukkoa, lopetetaan.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('fr', { aggregate: { label: 'éléments' }, groupPanel: { description: 'Faites glisser une en-tête de colonne ici pour créer un groupe de colonnes.' }, search: { placeholder: 'Recherche...', showingItems: 'Affichage des éléments :', selectedItems: 'Éléments sélectionnés :', totalItems: 'Nombre total d\'éléments:', size: 'Taille de page:', first: 'Première page', next: 'Page Suivante', previous: 'Page précédente', last: 'Dernière page' }, menu: { text: 'Choisir des colonnes :' }, sort: { ascending: 'Trier par ordre croissant', descending: 'Trier par ordre décroissant', remove: 'Enlever le tri' }, column: { hide: 'Cacher la colonne' }, aggregation: { count: 'lignes totales: ', sum: 'total: ', avg: 'moy: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Épingler à gauche', pinRight: 'Épingler à droite', unpin: 'Détacher' }, gridMenu: { columns: 'Colonnes:', importerTitle: 'Importer un fichier', exporterAllAsCsv: 'Exporter toutes les données en CSV', exporterVisibleAsCsv: 'Exporter les données visibles en CSV', exporterSelectedAsCsv: 'Exporter les données sélectionnées en CSV', exporterAllAsPdf: 'Exporter toutes les données en PDF', exporterVisibleAsPdf: 'Exporter les données visibles en PDF', exporterSelectedAsPdf: 'Exporter les données sélectionnées en PDF' }, importer: { noHeaders: 'Impossible de déterminer le nom des colonnes, le fichier possède-t-il une en-tête ?', noObjects: 'Aucun objet trouvé, le fichier possède-t-il des données autres que l\'en-tête ?', invalidCsv: 'Le fichier n\'a pas pu être traité, le CSV est-il valide ?', invalidJson: 'Le fichier n\'a pas pu être traité, le JSON est-il valide ?', jsonNotArray: 'Le fichier JSON importé doit contenir un tableau, abandon.' }, pagination: { sizes: 'éléments par page', totalItems: 'éléments' }, grouping: { group: 'Grouper', ungroup: 'Dégrouper', aggregate_count: 'Agg: Compte', aggregate_sum: 'Agg: Somme', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Moy', aggregate_remove: 'Agg: Retirer' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nService', ['$delegate', function ($delegate) { $delegate.add('he', { aggregate: { label: 'items' }, groupPanel: { description: 'גרור עמודה לכאן ושחרר בכדי לקבץ עמודה זו.' }, search: { placeholder: 'חפש...', showingItems: 'מציג:', selectedItems: 'סה"כ נבחרו:', totalItems: 'סה"כ רשומות:', size: 'תוצאות בדף:', first: 'דף ראשון', next: 'דף הבא', previous: 'דף קודם', last: 'דף אחרון' }, menu: { text: 'בחר עמודות:' }, sort: { ascending: 'סדר עולה', descending: 'סדר יורד', remove: 'בטל' }, column: { hide: 'טור הסתר' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('hy', { aggregate: { label: 'տվյալներ' }, groupPanel: { description: 'Ըստ սյան խմբավորելու համար քաշեք և գցեք վերնագիրն այստեղ։' }, search: { placeholder: 'Փնտրում...', showingItems: 'Ցուցադրված տվյալներ՝', selectedItems: 'Ընտրված:', totalItems: 'Ընդամենը՝', size: 'Տողերի քանակը էջում՝', first: 'Առաջին էջ', next: 'Հաջորդ էջ', previous: 'Նախորդ էջ', last: 'Վերջին էջ' }, menu: { text: 'Ընտրել սյուները:' }, sort: { ascending: 'Աճման կարգով', descending: 'Նվազման կարգով', remove: 'Հանել ' }, column: { hide: 'Թաքցնել սյունը' }, aggregation: { count: 'ընդամենը տող՝ ', sum: 'ընդամենը՝ ', avg: 'միջին՝ ', min: 'մին՝ ', max: 'մաքս՝ ' }, pinning: { pinLeft: 'Կպցնել ձախ կողմում', pinRight: 'Կպցնել աջ կողմում', unpin: 'Արձակել' }, gridMenu: { columns: 'Սյուներ:', importerTitle: 'Ներմուծել ֆայլ', exporterAllAsCsv: 'Արտահանել ամբողջը CSV', exporterVisibleAsCsv: 'Արտահանել երևացող տվյալները CSV', exporterSelectedAsCsv: 'Արտահանել ընտրված տվյալները CSV', exporterAllAsPdf: 'Արտահանել PDF', exporterVisibleAsPdf: 'Արտահանել երևացող տվյալները PDF', exporterSelectedAsPdf: 'Արտահանել ընտրված տվյալները PDF' }, importer: { noHeaders: 'Հնարավոր չեղավ որոշել սյան վերնագրերը։ Արդյո՞ք ֆայլը ունի վերնագրեր։', noObjects: 'Հնարավոր չեղավ կարդալ տվյալները։ Արդյո՞ք ֆայլում կան տվյալներ։', invalidCsv: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր CSV է։', invalidJson: 'Հնարավոր չեղավ մշակել ֆայլը։ Արդյո՞ք այն վավեր Json է։', jsonNotArray: 'Ներմուծված json ֆայլը պետք է պարունակի զանգված, կասեցվում է։' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('it', { aggregate: { label: 'elementi' }, groupPanel: { description: 'Trascina un\'intestazione all\'interno del gruppo della colonna.' }, search: { placeholder: 'Ricerca...', showingItems: 'Mostra:', selectedItems: 'Selezionati:', totalItems: 'Totali:', size: 'Tot Pagine:', first: 'Prima', next: 'Prossima', previous: 'Precedente', last: 'Ultima' }, menu: { text: 'Scegli le colonne:' }, sort: { ascending: 'Asc.', descending: 'Desc.', remove: 'Annulla ordinamento' }, column: { hide: 'Nascondi' }, aggregation: { count: 'righe totali: ', sum: 'tot: ', avg: 'media: ', min: 'minimo: ', max: 'massimo: ' }, pinning: { pinLeft: 'Blocca a sx', pinRight: 'Blocca a dx', unpin: 'Blocca in alto' }, gridMenu: { columns: 'Colonne:', importerTitle: 'Importa', exporterAllAsCsv: 'Esporta tutti i dati in CSV', exporterVisibleAsCsv: 'Esporta i dati visibili in CSV', exporterSelectedAsCsv: 'Esporta i dati selezionati in CSV', exporterAllAsPdf: 'Esporta tutti i dati in PDF', exporterVisibleAsPdf: 'Esporta i dati visibili in PDF', exporterSelectedAsPdf: 'Esporta i dati selezionati in PDF' }, importer: { noHeaders: 'Impossibile reperire i nomi delle colonne, sicuro che siano indicati all\'interno del file?', noObjects: 'Impossibile reperire gli oggetti, sicuro che siano indicati all\'interno del file?', invalidCsv: 'Impossibile elaborare il file, sicuro che sia un CSV?', invalidJson: 'Impossibile elaborare il file, sicuro che sia un JSON valido?', jsonNotArray: 'Errore! Il file JSON da importare deve contenere un array.' }, grouping: { group: 'Raggruppa', ungroup: 'Separa', aggregate_count: 'Agg: N. Elem.', aggregate_sum: 'Agg: Somma', aggregate_max: 'Agg: Massimo', aggregate_min: 'Agg: Minimo', aggregate_avg: 'Agg: Media', aggregate_remove: 'Agg: Rimuovi' } }); return $delegate; }]); }]); })(); (function() { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ja', { aggregate: { label: '項目' }, groupPanel: { description: 'ここに列ヘッダをドラッグアンドドロップして、その列でグループ化します。' }, search: { placeholder: '検索...', showingItems: '表示中の項目:', selectedItems: '選択した項目:', totalItems: '項目の総数:', size: 'ページサイズ:', first: '最初のページ', next: '次のページ', previous: '前のページ', last: '前のページ' }, menu: { text: '列の選択:' }, sort: { ascending: '昇順に並べ替え', descending: '降順に並べ替え', remove: '並べ替えの解除' }, column: { hide: '列の非表示' }, aggregation: { count: '合計行数: ', sum: '合計: ', avg: '平均: ', min: '最小: ', max: '最大: ' }, pinning: { pinLeft: '左に固定', pinRight: '右に固定', unpin: '固定解除' }, gridMenu: { columns: '列:', importerTitle: 'ファイルのインポート', exporterAllAsCsv: 'すべてのデータをCSV形式でエクスポート', exporterVisibleAsCsv: '表示中のデータをCSV形式でエクスポート', exporterSelectedAsCsv: '選択したデータをCSV形式でエクスポート', exporterAllAsPdf: 'すべてのデータをPDF形式でエクスポート', exporterVisibleAsPdf: '表示中のデータをPDF形式でエクスポート', exporterSelectedAsPdf: '選択したデータをPDF形式でエクスポート' }, importer: { noHeaders: '列名を取得できません。ファイルにヘッダが含まれていることを確認してください。', noObjects: 'オブジェクトを取得できません。ファイルにヘッダ以外のデータが含まれていることを確認してください。', invalidCsv: 'ファイルを処理できません。ファイルが有効なCSV形式であることを確認してください。', invalidJson: 'ファイルを処理できません。ファイルが有効なJSON形式であることを確認してください。', jsonNotArray: 'インポートしたJSONファイルには配列が含まれている必要があります。処理を中止します。' }, pagination: { sizes: '項目/ページ', totalItems: '項目' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ko', { aggregate: { label: '아이템' }, groupPanel: { description: '컬럼으로 그룹핑하기 위해서는 컬럼 헤더를 끌어 떨어뜨려 주세요.' }, search: { placeholder: '검색...', showingItems: '항목 보여주기:', selectedItems: '선택 항목:', totalItems: '전체 항목:', size: '페이지 크기:', first: '첫번째 페이지', next: '다음 페이지', previous: '이전 페이지', last: '마지막 페이지' }, menu: { text: '컬럼을 선택하세요:' }, sort: { ascending: '오름차순 정렬', descending: '내림차순 정렬', remove: '소팅 제거' }, column: { hide: '컬럼 제거' }, aggregation: { count: '전체 갯수: ', sum: '전체: ', avg: '평균: ', min: '최소: ', max: '최대: ' }, pinning: { pinLeft: '왼쪽 핀', pinRight: '오른쪽 핀', unpin: '핀 제거' }, gridMenu: { columns: '컬럼:', importerTitle: '파일 가져오기', exporterAllAsCsv: 'csv로 모든 데이터 내보내기', exporterVisibleAsCsv: 'csv로 보이는 데이터 내보내기', exporterSelectedAsCsv: 'csv로 선택된 데이터 내보내기', exporterAllAsPdf: 'pdf로 모든 데이터 내보내기', exporterVisibleAsPdf: 'pdf로 보이는 데이터 내보내기', exporterSelectedAsPdf: 'pdf로 선택 데이터 내보내기' }, importer: { noHeaders: '컬럼명이 지정되어 있지 않습니다. 파일에 헤더가 명시되어 있는지 확인해 주세요.', noObjects: '데이터가 지정되어 있지 않습니다. 데이터가 파일에 있는지 확인해 주세요.', invalidCsv: '파일을 처리할 수 없습니다. 올바른 csv인지 확인해 주세요.', invalidJson: '파일을 처리할 수 없습니다. 올바른 json인지 확인해 주세요.', jsonNotArray: 'json 파일은 배열을 포함해야 합니다.' }, pagination: { sizes: '페이지당 항목', totalItems: '전체 항목' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('nl', { aggregate: { label: 'items' }, groupPanel: { description: 'Sleep hier een kolomnaam heen om op te groeperen.' }, search: { placeholder: 'Zoeken...', showingItems: 'Getoonde items:', selectedItems: 'Geselecteerde items:', totalItems: 'Totaal aantal items:', size: 'Items per pagina:', first: 'Eerste pagina', next: 'Volgende pagina', previous: 'Vorige pagina', last: 'Laatste pagina' }, menu: { text: 'Kies kolommen:' }, sort: { ascending: 'Sorteer oplopend', descending: 'Sorteer aflopend', remove: 'Verwijder sortering' }, column: { hide: 'Verberg kolom' }, aggregation: { count: 'Aantal rijen: ', sum: 'Som: ', avg: 'Gemiddelde: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Zet links vast', pinRight: 'Zet rechts vast', unpin: 'Maak los' }, gridMenu: { columns: 'Kolommen:', importerTitle: 'Importeer bestand', exporterAllAsCsv: 'Exporteer alle data als csv', exporterVisibleAsCsv: 'Exporteer zichtbare data als csv', exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv', exporterAllAsPdf: 'Exporteer alle data als pdf', exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf', exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf' }, importer: { noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?', noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?', invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?', invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?', jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.' }, pagination: { sizes: 'items per pagina', totalItems: 'items' }, grouping: { group: 'Groepeer', ungroup: 'Groepering opheffen', aggregate_count: 'Agg: Aantal', aggregate_sum: 'Agg: Som', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Gem', aggregate_remove: 'Agg: Verwijder' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('pt-br', { aggregate: { label: 'itens' }, groupPanel: { description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna' }, search: { placeholder: 'Procurar...', showingItems: 'Mostrando os Itens:', selectedItems: 'Items Selecionados:', totalItems: 'Total de Itens:', size: 'Tamanho da Página:', first: 'Primeira Página', next: 'Próxima Página', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Selecione as colunas:' }, sort: { ascending: 'Ordenar Ascendente', descending: 'Ordenar Descendente', remove: 'Remover Ordenação' }, column: { hide: 'Esconder coluna' }, aggregation: { count: 'total de linhas: ', sum: 'total: ', avg: 'med: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fixar Esquerda', pinRight: 'Fixar Direita', unpin: 'Desprender' }, gridMenu: { columns: 'Colunas:', importerTitle: 'Importar arquivo', exporterAllAsCsv: 'Exportar todos os dados como csv', exporterVisibleAsCsv: 'Exportar dados visíveis como csv', exporterSelectedAsCsv: 'Exportar dados selecionados como csv', exporterAllAsPdf: 'Exportar todos os dados como pdf', exporterVisibleAsPdf: 'Exportar dados visíveis como pdf', exporterSelectedAsPdf: 'Exportar dados selecionados como pdf' }, importer: { noHeaders: 'Nomes de colunas não puderam ser derivados. O arquivo tem um cabeçalho?', noObjects: 'Objetos não puderam ser derivados. Havia dados no arquivo, além dos cabeçalhos?', invalidCsv: 'Arquivo não pode ser processado. É um CSV válido?', invalidJson: 'Arquivo não pode ser processado. É um Json válido?', jsonNotArray: 'Arquivo json importado tem que conter um array. Abortando.' }, pagination: { sizes: 'itens por página', totalItems: 'itens' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Contar', aggregate_sum: 'Agr: Soma', aggregate_max: 'Agr: Max', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Med', aggregate_remove: 'Agr: Remover' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('pt', { aggregate: { label: 'itens' }, groupPanel: { description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna' }, search: { placeholder: 'Procurar...', showingItems: 'Mostrando os Itens:', selectedItems: 'Itens Selecionados:', totalItems: 'Total de Itens:', size: 'Tamanho da Página:', first: 'Primeira Página', next: 'Próxima Página', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Selecione as colunas:' }, sort: { ascending: 'Ordenar Ascendente', descending: 'Ordenar Descendente', remove: 'Remover Ordenação' }, column: { hide: 'Esconder coluna' }, aggregation: { count: 'total de linhas: ', sum: 'total: ', avg: 'med: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fixar Esquerda', pinRight: 'Fixar Direita', unpin: 'Desprender' }, gridMenu: { columns: 'Colunas:', importerTitle: 'Importar ficheiro', exporterAllAsCsv: 'Exportar todos os dados como csv', exporterVisibleAsCsv: 'Exportar dados visíveis como csv', exporterSelectedAsCsv: 'Exportar dados selecionados como csv', exporterAllAsPdf: 'Exportar todos os dados como pdf', exporterVisibleAsPdf: 'Exportar dados visíveis como pdf', exporterSelectedAsPdf: 'Exportar dados selecionados como pdf' }, importer: { noHeaders: 'Nomes de colunas não puderam ser derivados. O ficheiro tem um cabeçalho?', noObjects: 'Objetos não puderam ser derivados. Havia dados no ficheiro, além dos cabeçalhos?', invalidCsv: 'Ficheiro não pode ser processado. É um CSV válido?', invalidJson: 'Ficheiro não pode ser processado. É um Json válido?', jsonNotArray: 'Ficheiro json importado tem que conter um array. Interrompendo.' }, pagination: { sizes: 'itens por página', totalItems: 'itens' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Contar', aggregate_sum: 'Agr: Soma', aggregate_max: 'Agr: Max', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Med', aggregate_remove: 'Agr: Remover' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('ru', { aggregate: { label: 'элементы' }, groupPanel: { description: 'Для группировки по столбцу перетащите сюда его название.' }, search: { placeholder: 'Поиск...', showingItems: 'Показать элементы:', selectedItems: 'Выбранные элементы:', totalItems: 'Всего элементов:', size: 'Размер страницы:', first: 'Первая страница', next: 'Следующая страница', previous: 'Предыдущая страница', last: 'Последняя страница' }, menu: { text: 'Выбрать столбцы:' }, sort: { ascending: 'По возрастанию', descending: 'По убыванию', remove: 'Убрать сортировку' }, column: { hide: 'спрятать столбец' }, aggregation: { count: 'всего строк: ', sum: 'итого: ', avg: 'среднее: ', min: 'мин: ', max: 'макс: ' }, gridMenu: { columns: 'Столбцы:', importerTitle: 'Import file', exporterAllAsCsv: 'Экспортировать всё в CSV', exporterVisibleAsCsv: 'Экспортировать видимые данные в CSV', exporterSelectedAsCsv: 'Экспортировать выбранные данные в CSV', exporterAllAsPdf: 'Экспортировать всё в PDF', exporterVisibleAsPdf: 'Экспортировать видимые данные в PDF', exporterSelectedAsPdf: 'Экспортировать выбранные данные в PDF' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('sk', { aggregate: { label: 'items' }, groupPanel: { description: 'Pretiahni sem názov stĺpca pre zoskupenie podľa toho stĺpca.' }, search: { placeholder: 'Hľadaj...', showingItems: 'Zobrazujem položky:', selectedItems: 'Vybraté položky:', totalItems: 'Počet položiek:', size: 'Počet:', first: 'Prvá strana', next: 'Ďalšia strana', previous: 'Predchádzajúca strana', last: 'Posledná strana' }, menu: { text: 'Vyberte stĺpce:' }, sort: { ascending: 'Zotriediť vzostupne', descending: 'Zotriediť zostupne', remove: 'Vymazať triedenie' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' }, gridMenu: { columns: 'Columns:', importerTitle: 'Import file', exporterAllAsCsv: 'Export all data as csv', exporterVisibleAsCsv: 'Export visible data as csv', exporterSelectedAsCsv: 'Export selected data as csv', exporterAllAsPdf: 'Export all data as pdf', exporterVisibleAsPdf: 'Export visible data as pdf', exporterSelectedAsPdf: 'Export selected data as pdf' }, importer: { noHeaders: 'Column names were unable to be derived, does the file have a header?', noObjects: 'Objects were not able to be derived, was there data in the file other than headers?', invalidCsv: 'File was unable to be processed, is it valid CSV?', invalidJson: 'File was unable to be processed, is it valid Json?', jsonNotArray: 'Imported json file must contain an array, aborting.' } }); return $delegate; }]); }]); })(); (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('sv', { aggregate: { label: 'Artiklar' }, groupPanel: { description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.' }, search: { placeholder: 'Sök...', showingItems: 'Visar artiklar:', selectedItems: 'Valda artiklar:', totalItems: 'Antal artiklar:', size: 'Sidstorlek:', first: 'Första sidan', next: 'Nästa sida', previous: 'Föregående sida', last: 'Sista sidan' }, menu: { text: 'Välj kolumner:' }, sort: { ascending: 'Sortera stigande', descending: 'Sortera fallande', remove: 'Inaktivera sortering' }, column: { hide: 'Göm kolumn' }, aggregation: { count: 'Antal rader: ', sum: 'Summa: ', avg: 'Genomsnitt: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Fäst vänster', pinRight: 'Fäst höger', unpin: 'Lösgör' }, gridMenu: { columns: 'Kolumner:', importerTitle: 'Importera fil', exporterAllAsCsv: 'Exportera all data som CSV', exporterVisibleAsCsv: 'Exportera synlig data som CSV', exporterSelectedAsCsv: 'Exportera markerad data som CSV', exporterAllAsPdf: 'Exportera all data som PDF', exporterVisibleAsPdf: 'Exportera synlig data som PDF', exporterSelectedAsPdf: 'Exportera markerad data som PDF' }, importer: { noHeaders: 'Kolumnnamn kunde inte härledas. Har filen ett sidhuvud?', noObjects: 'Objekt kunde inte härledas. Har filen data undantaget sidhuvud?', invalidCsv: 'Filen kunde inte behandlas, är den en giltig CSV?', invalidJson: 'Filen kunde inte behandlas, är den en giltig JSON?', jsonNotArray: 'Importerad JSON-fil måste innehålla ett fält. Import avbruten.' }, pagination: { sizes: 'Artiklar per sida', totalItems: 'Artiklar' } }); return $delegate; }]); }]); })(); /** * @ngdoc overview * @name ui.grid.i18n * @description * * # ui.grid.i18n * This module provides i18n functions to ui.grid and any application that wants to use it * * <div doc-module-components="ui.grid.i18n"></div> */ (function () { var DIRECTIVE_ALIASES = ['uiT', 'uiTranslate']; var FILTER_ALIASES = ['t', 'uiTranslate']; var module = angular.module('ui.grid.i18n'); /** * @ngdoc object * @name ui.grid.i18n.constant:i18nConstants * * @description constants available in i18n module */ module.constant('i18nConstants', { MISSING: '[MISSING]', UPDATE_EVENT: '$uiI18n', LOCALE_DIRECTIVE_ALIAS: 'uiI18n', // default to english DEFAULT_LANG: 'en' }); // module.config(['$provide', function($provide) { // $provide.decorator('i18nService', ['$delegate', function($delegate) {}])}]); /** * @ngdoc service * @name ui.grid.i18n.service:i18nService * * @description Services for i18n */ module.service('i18nService', ['$log', 'i18nConstants', '$rootScope', function ($log, i18nConstants, $rootScope) { var langCache = { _langs: {}, current: null, get: function (lang) { return this._langs[lang.toLowerCase()]; }, add: function (lang, strings) { var lower = lang.toLowerCase(); if (!this._langs[lower]) { this._langs[lower] = {}; } angular.extend(this._langs[lower], strings); }, getAllLangs: function () { var langs = []; if (!this._langs) { return langs; } for (var key in this._langs) { langs.push(key); } return langs; }, setCurrent: function (lang) { this.current = lang.toLowerCase(); }, getCurrentLang: function () { return this.current; } }; var service = { /** * @ngdoc service * @name add * @methodOf ui.grid.i18n.service:i18nService * @description Adds the languages and strings to the cache. Decorate this service to * add more translation strings * @param {string} lang language to add * @param {object} stringMaps of strings to add grouped by property names * @example * <pre> * i18nService.add('en', { * aggregate: { * label1: 'items', * label2: 'some more items' * } * }, * groupPanel: { * description: 'Drag a column header here and drop it to group by that column.' * } * } * </pre> */ add: function (langs, stringMaps) { if (typeof(langs) === 'object') { angular.forEach(langs, function (lang) { if (lang) { langCache.add(lang, stringMaps); } }); } else { langCache.add(langs, stringMaps); } }, /** * @ngdoc service * @name getAllLangs * @methodOf ui.grid.i18n.service:i18nService * @description return all currently loaded languages * @returns {array} string */ getAllLangs: function () { return langCache.getAllLangs(); }, /** * @ngdoc service * @name get * @methodOf ui.grid.i18n.service:i18nService * @description return all currently loaded languages * @param {string} lang to return. If not specified, returns current language * @returns {object} the translation string maps for the language */ get: function (lang) { var language = lang ? lang : service.getCurrentLang(); return langCache.get(language); }, /** * @ngdoc service * @name getSafeText * @methodOf ui.grid.i18n.service:i18nService * @description returns the text specified in the path or a Missing text if text is not found * @param {string} path property path to use for retrieving text from string map * @param {string} lang to return. If not specified, returns current language * @returns {object} the translation for the path * @example * <pre> * i18nService.getSafeText('sort.ascending') * </pre> */ getSafeText: function (path, lang) { var language = lang ? lang : service.getCurrentLang(); var trans = langCache.get(language); if (!trans) { return i18nConstants.MISSING; } var paths = path.split('.'); var current = trans; for (var i = 0; i < paths.length; ++i) { if (current[paths[i]] === undefined || current[paths[i]] === null) { return i18nConstants.MISSING; } else { current = current[paths[i]]; } } return current; }, /** * @ngdoc service * @name setCurrentLang * @methodOf ui.grid.i18n.service:i18nService * @description sets the current language to use in the application * $broadcasts the Update_Event on the $rootScope * @param {string} lang to set * @example * <pre> * i18nService.setCurrentLang('fr'); * </pre> */ setCurrentLang: function (lang) { if (lang) { langCache.setCurrent(lang); $rootScope.$broadcast(i18nConstants.UPDATE_EVENT); } }, /** * @ngdoc service * @name getCurrentLang * @methodOf ui.grid.i18n.service:i18nService * @description returns the current language used in the application */ getCurrentLang: function () { var lang = langCache.getCurrentLang(); if (!lang) { lang = i18nConstants.DEFAULT_LANG; langCache.setCurrent(lang); } return lang; } }; return service; }]); var localeDirective = function (i18nService, i18nConstants) { return { compile: function () { return { pre: function ($scope, $elm, $attrs) { var alias = i18nConstants.LOCALE_DIRECTIVE_ALIAS; // check for watchable property var lang = $scope.$eval($attrs[alias]); if (lang) { $scope.$watch($attrs[alias], function () { i18nService.setCurrentLang(lang); }); } else if ($attrs.$$observers) { $attrs.$observe(alias, function () { i18nService.setCurrentLang($attrs[alias] || i18nConstants.DEFAULT_LANG); }); } } }; } }; }; module.directive('uiI18n', ['i18nService', 'i18nConstants', localeDirective]); // directive syntax var uitDirective = function ($parse, i18nService, i18nConstants) { return { restrict: 'EA', compile: function () { return { pre: function ($scope, $elm, $attrs) { var alias1 = DIRECTIVE_ALIASES[0], alias2 = DIRECTIVE_ALIASES[1]; var token = $attrs[alias1] || $attrs[alias2] || $elm.html(); var missing = i18nConstants.MISSING + token; var observer; if ($attrs.$$observers) { var prop = $attrs[alias1] ? alias1 : alias2; observer = $attrs.$observe(prop, function (result) { if (result) { $elm.html($parse(result)(i18nService.getCurrentLang()) || missing); } }); } var getter = $parse(token); var listener = $scope.$on(i18nConstants.UPDATE_EVENT, function (evt) { if (observer) { observer($attrs[alias1] || $attrs[alias2]); } else { // set text based on i18n current language $elm.html(getter(i18nService.get()) || missing); } }); $scope.$on('$destroy', listener); $elm.html(getter(i18nService.get()) || missing); } }; } }; }; angular.forEach( DIRECTIVE_ALIASES, function ( alias ) { module.directive( alias, ['$parse', 'i18nService', 'i18nConstants', uitDirective] ); } ); // optional filter syntax var uitFilter = function ($parse, i18nService, i18nConstants) { return function (data) { var getter = $parse(data); // set text based on i18n current language return getter(i18nService.get()) || i18nConstants.MISSING + data; }; }; angular.forEach( FILTER_ALIASES, function ( alias ) { module.filter( alias, ['$parse', 'i18nService', 'i18nConstants', uitFilter] ); } ); })(); (function() { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('zh-cn', { aggregate: { label: '行' }, groupPanel: { description: '拖曳表头到此处进行分组' }, search: { placeholder: '查找', showingItems: '已显示行数:', selectedItems: '已选择行数:', totalItems: '总行数:', size: '每页显示行数:', first: '首页', next: '下一页', previous: '上一页', last: '末页' }, menu: { text: '选择列:' }, sort: { ascending: '升序', descending: '降序', remove: '取消排序' }, column: { hide: '隐藏列' }, aggregation: { count: '计数:', sum: '求和:', avg: '均值:', min: '最小值:', max: '最大值:' }, pinning: { pinLeft: '左侧固定', pinRight: '右侧固定', unpin: '取消固定' }, gridMenu: { columns: '列:', importerTitle: '导入文件', exporterAllAsCsv: '导出全部数据到CSV', exporterVisibleAsCsv: '导出可见数据到CSV', exporterSelectedAsCsv: '导出已选数据到CSV', exporterAllAsPdf: '导出全部数据到PDF', exporterVisibleAsPdf: '导出可见数据到PDF', exporterSelectedAsPdf: '导出已选数据到PDF' }, importer: { noHeaders: '无法获取列名,确定文件包含表头?', noObjects: '无法获取数据,确定文件包含数据?', invalidCsv: '无法处理文件,确定是合法的CSV文件?', invalidJson: '无法处理文件,确定是合法的JSON文件?', jsonNotArray: '导入的文件不是JSON数组!' }, pagination: { sizes: '行每页', totalItems: '行' } }); return $delegate; }]); }]); })(); (function() { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('zh-tw', { aggregate: { label: '行' }, groupPanel: { description: '拖曳表頭到此處進行分組' }, search: { placeholder: '查找', showingItems: '已顯示行數:', selectedItems: '已選擇行數:', totalItems: '總行數:', size: '每頁顯示行數:', first: '首頁', next: '下壹頁', previous: '上壹頁', last: '末頁' }, menu: { text: '選擇列:' }, sort: { ascending: '升序', descending: '降序', remove: '取消排序' }, column: { hide: '隱藏列' }, aggregation: { count: '計數:', sum: '求和:', avg: '均值:', min: '最小值:', max: '最大值:' }, pinning: { pinLeft: '左側固定', pinRight: '右側固定', unpin: '取消固定' }, gridMenu: { columns: '列:', importerTitle: '導入文件', exporterAllAsCsv: '導出全部數據到CSV', exporterVisibleAsCsv: '導出可見數據到CSV', exporterSelectedAsCsv: '導出已選數據到CSV', exporterAllAsPdf: '導出全部數據到PDF', exporterVisibleAsPdf: '導出可見數據到PDF', exporterSelectedAsPdf: '導出已選數據到PDF' }, importer: { noHeaders: '無法獲取列名,確定文件包含表頭?', noObjects: '無法獲取數據,確定文件包含數據?', invalidCsv: '無法處理文件,確定是合法的CSV文件?', invalidJson: '無法處理文件,確定是合法的JSON文件?', jsonNotArray: '導入的文件不是JSON數組!' }, pagination: { sizes: '行每頁', totalItems: '行' } }); return $delegate; }]); }]); })(); (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.autoResize * * @description * * #ui.grid.autoResize * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides auto-resizing functionality to UI-Grid. */ var module = angular.module('ui.grid.autoResize', ['ui.grid']); module.directive('uiGridAutoResize', ['$timeout', 'gridUtil', function ($timeout, gridUtil) { return { require: 'uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var prevGridWidth, prevGridHeight; function getDimensions() { prevGridHeight = gridUtil.elementHeight($elm); prevGridWidth = gridUtil.elementWidth($elm); } // Initialize the dimensions getDimensions(); var resizeTimeoutId; function startTimeout() { clearTimeout(resizeTimeoutId); resizeTimeoutId = setTimeout(function () { var newGridHeight = gridUtil.elementHeight($elm); var newGridWidth = gridUtil.elementWidth($elm); if (newGridHeight !== prevGridHeight || newGridWidth !== prevGridWidth) { uiGridCtrl.grid.gridHeight = newGridHeight; uiGridCtrl.grid.gridWidth = newGridWidth; $scope.$apply(function () { uiGridCtrl.grid.refresh() .then(function () { getDimensions(); startTimeout(); }); }); } else { startTimeout(); } }, 250); } startTimeout(); $scope.$on('$destroy', function() { clearTimeout(resizeTimeoutId); }); } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.cellNav * * @description #ui.grid.cellNav <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> This module provides auto-resizing functionality to UI-Grid. */ var module = angular.module('ui.grid.cellNav', ['ui.grid']); function RowCol(row, col) { this.row = row; this.col = col; } /** * @ngdoc object * @name ui.grid.cellNav.constant:uiGridCellNavConstants * * @description constants available in cellNav */ module.constant('uiGridCellNavConstants', { FEATURE_NAME: 'gridCellNav', CELL_NAV_EVENT: 'cellNav', direction: {LEFT: 0, RIGHT: 1, UP: 2, DOWN: 3, PG_UP: 4, PG_DOWN: 5}, EVENT_TYPE: { KEYDOWN: 0, CLICK: 1, CLEAR: 2 } }); module.factory('uiGridCellNavFactory', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', '$q', function (gridUtil, uiGridConstants, uiGridCellNavConstants, $q) { /** * @ngdoc object * @name ui.grid.cellNav.object:CellNav * @description returns a CellNav prototype function * @param {object} rowContainer container for rows * @param {object} colContainer parent column container * @param {object} leftColContainer column container to the left of parent * @param {object} rightColContainer column container to the right of parent */ var UiGridCellNav = function UiGridCellNav(rowContainer, colContainer, leftColContainer, rightColContainer) { this.rows = rowContainer.visibleRowCache; this.columns = colContainer.visibleColumnCache; this.leftColumns = leftColContainer ? leftColContainer.visibleColumnCache : []; this.rightColumns = rightColContainer ? rightColContainer.visibleColumnCache : []; this.bodyContainer = rowContainer; }; /** returns focusable columns of all containers */ UiGridCellNav.prototype.getFocusableCols = function () { var allColumns = this.leftColumns.concat(this.columns, this.rightColumns); return allColumns.filter(function (col) { return col.colDef.allowCellFocus; }); }; /** * @ngdoc object * @name ui.grid.cellNav.api:GridRow * * @description GridRow settings for cellNav feature, these are available to be * set only internally (for example, by other features) */ /** * @ngdoc object * @name allowCellFocus * @propertyOf ui.grid.cellNav.api:GridRow * @description Enable focus on a cell within this row. If set to false then no cells * in this row can be focused - group header rows as an example would set this to false. * <br/>Defaults to true */ /** returns focusable rows */ UiGridCellNav.prototype.getFocusableRows = function () { return this.rows.filter(function(row) { return row.allowCellFocus !== false; }); }; UiGridCellNav.prototype.getNextRowCol = function (direction, curRow, curCol) { switch (direction) { case uiGridCellNavConstants.direction.LEFT: return this.getRowColLeft(curRow, curCol); case uiGridCellNavConstants.direction.RIGHT: return this.getRowColRight(curRow, curCol); case uiGridCellNavConstants.direction.UP: return this.getRowColUp(curRow, curCol); case uiGridCellNavConstants.direction.DOWN: return this.getRowColDown(curRow, curCol); case uiGridCellNavConstants.direction.PG_UP: return this.getRowColPageUp(curRow, curCol); case uiGridCellNavConstants.direction.PG_DOWN: return this.getRowColPageDown(curRow, curCol); } }; UiGridCellNav.prototype.initializeSelection = function () { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); if (focusableCols.length === 0 || focusableRows.length === 0) { return null; } var curRowIndex = 0; var curColIndex = 0; return new RowCol(focusableRows[0], focusableCols[0]); //return same row }; UiGridCellNav.prototype.getRowColLeft = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 1 if (curColIndex === -1) { curColIndex = 1; } var nextColIndex = curColIndex === 0 ? focusableCols.length - 1 : curColIndex - 1; //get column to left if (nextColIndex > curColIndex) { // On the first row // if (curRowIndex === 0 && curColIndex === 0) { // return null; // } if (curRowIndex === 0) { return new RowCol(curRow, focusableCols[nextColIndex]); //return same row } else { //up one row and far right column return new RowCol(focusableRows[curRowIndex - 1], focusableCols[nextColIndex]); } } else { return new RowCol(curRow, focusableCols[nextColIndex]); } }; UiGridCellNav.prototype.getRowColRight = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } var nextColIndex = curColIndex === focusableCols.length - 1 ? 0 : curColIndex + 1; if (nextColIndex < curColIndex) { if (curRowIndex === focusableRows.length - 1) { return new RowCol(curRow, focusableCols[nextColIndex]); //return same row } else { //down one row and far left column return new RowCol(focusableRows[curRowIndex + 1], focusableCols[nextColIndex]); } } else { return new RowCol(curRow, focusableCols[nextColIndex]); } }; UiGridCellNav.prototype.getRowColDown = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } if (curRowIndex === focusableRows.length - 1) { return new RowCol(curRow, focusableCols[curColIndex]); //return same row } else { //down one row return new RowCol(focusableRows[curRowIndex + 1], focusableCols[curColIndex]); } }; UiGridCellNav.prototype.getRowColPageDown = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } var pageSize = this.bodyContainer.minRowsToRender(); if (curRowIndex >= focusableRows.length - pageSize) { return new RowCol(focusableRows[focusableRows.length - 1], focusableCols[curColIndex]); //return last row } else { //down one page return new RowCol(focusableRows[curRowIndex + pageSize], focusableCols[curColIndex]); } }; UiGridCellNav.prototype.getRowColUp = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } if (curRowIndex === 0) { return new RowCol(curRow, focusableCols[curColIndex]); //return same row } else { //up one row return new RowCol(focusableRows[curRowIndex - 1], focusableCols[curColIndex]); } }; UiGridCellNav.prototype.getRowColPageUp = function (curRow, curCol) { var focusableCols = this.getFocusableCols(); var focusableRows = this.getFocusableRows(); var curColIndex = focusableCols.indexOf(curCol); var curRowIndex = focusableRows.indexOf(curRow); //could not find column in focusable Columns so set it to 0 if (curColIndex === -1) { curColIndex = 0; } var pageSize = this.bodyContainer.minRowsToRender(); if (curRowIndex - pageSize < 0) { return new RowCol(focusableRows[0], focusableCols[curColIndex]); //return first row } else { //up one page return new RowCol(focusableRows[curRowIndex - pageSize], focusableCols[curColIndex]); } }; return UiGridCellNav; }]); /** * @ngdoc service * @name ui.grid.cellNav.service:uiGridCellNavService * * @description Services for cell navigation features. If you don't like the key maps we use, * or the direction cells navigation, override with a service decorator (see angular docs) */ module.service('uiGridCellNavService', ['gridUtil', 'uiGridConstants', 'uiGridCellNavConstants', '$q', 'uiGridCellNavFactory', 'ScrollEvent', function (gridUtil, uiGridConstants, uiGridCellNavConstants, $q, UiGridCellNav, ScrollEvent) { var service = { initializeGrid: function (grid) { grid.registerColumnBuilder(service.cellNavColumnBuilder); /** * @ngdoc object * @name ui.grid.cellNav:Grid.cellNav * @description cellNav properties added to grid class */ grid.cellNav = {}; grid.cellNav.lastRowCol = null; grid.cellNav.focusedCells = []; service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.cellNav.api:PublicApi * * @description Public Api for cellNav feature */ var publicApi = { events: { cellNav: { /** * @ngdoc event * @name navigate * @eventOf ui.grid.cellNav.api:PublicApi * @description raised when the active cell is changed * <pre> * gridApi.cellNav.on.navigate(scope,function(newRowcol, oldRowCol){}) * </pre> * @param {object} newRowCol new position * @param {object} oldRowCol old position */ navigate: function (newRowCol, oldRowCol) {}, /** * @ngdoc event * @name viewPortKeyDown * @eventOf ui.grid.cellNav.api:PublicApi * @description is raised when the viewPort receives a keyDown event. Cells never get focus in uiGrid * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this * event whenever you need a keydown event on a cell * <br/> * @param {object} event keydown event * @param {object} rowCol current rowCol position */ viewPortKeyDown: function (event, rowCol) {}, /** * @ngdoc event * @name viewPortKeyPress * @eventOf ui.grid.cellNav.api:PublicApi * @description is raised when the viewPort receives a keyPress event. Cells never get focus in uiGrid * due to the difficulties of setting focus on a cell that is not visible in the viewport. Use this * event whenever you need a keypress event on a cell * <br/> * @param {object} event keypress event * @param {object} rowCol current rowCol position */ viewPortKeyPress: function (event, rowCol) {} } }, methods: { cellNav: { /** * @ngdoc function * @name scrollToFocus * @methodOf ui.grid.cellNav.api:PublicApi * @description brings the specified row and column into view, and sets focus * to that cell * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus * @param {object} colDef to make visible and set focus * @returns {promise} a promise that is resolved after any scrolling is finished */ scrollToFocus: function (rowEntity, colDef) { return service.scrollToFocus(grid, rowEntity, colDef); }, /** * @ngdoc function * @name getFocusedCell * @methodOf ui.grid.cellNav.api:PublicApi * @description returns the current (or last if Grid does not have focus) focused row and column * <br> value is null if no selection has occurred */ getFocusedCell: function () { return grid.cellNav.lastRowCol; }, /** * @ngdoc function * @name getCurrentSelection * @methodOf ui.grid.cellNav.api:PublicApi * @description returns an array containing the current selection * <br> array is empty if no selection has occurred */ getCurrentSelection: function () { return grid.cellNav.focusedCells; }, /** * @ngdoc function * @name rowColSelectIndex * @methodOf ui.grid.cellNav.api:PublicApi * @description returns the index in the order in which the RowCol was selected, returns -1 if the RowCol * isn't selected * @param {object} rowCol the rowCol to evaluate */ rowColSelectIndex: function (rowCol) { //return gridUtil.arrayContainsObjectWithProperty(grid.cellNav.focusedCells, 'col.uid', rowCol.col.uid) && var index = -1; for (var i = 0; i < grid.cellNav.focusedCells.length; i++) { if (grid.cellNav.focusedCells[i].col.uid === rowCol.col.uid && grid.cellNav.focusedCells[i].row.uid === rowCol.row.uid) { index = i; break; } } return index; } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.cellNav.api:GridOptions * * @description GridOptions for cellNav feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name modifierKeysToMultiSelectCells * @propertyOf ui.grid.cellNav.api:GridOptions * @description Enable multiple cell selection only when using the ctrlKey or shiftKey. * <br/>Defaults to false */ gridOptions.modifierKeysToMultiSelectCells = gridOptions.modifierKeysToMultiSelectCells === true; }, /** * @ngdoc service * @name decorateRenderContainers * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @description decorates grid renderContainers with cellNav functions */ decorateRenderContainers: function (grid) { var rightContainer = grid.hasRightContainer() ? grid.renderContainers.right : null; var leftContainer = grid.hasLeftContainer() ? grid.renderContainers.left : null; if (leftContainer !== null) { grid.renderContainers.left.cellNav = new UiGridCellNav(grid.renderContainers.body, leftContainer, rightContainer, grid.renderContainers.body); } if (rightContainer !== null) { grid.renderContainers.right.cellNav = new UiGridCellNav(grid.renderContainers.body, rightContainer, grid.renderContainers.body, leftContainer); } grid.renderContainers.body.cellNav = new UiGridCellNav(grid.renderContainers.body, grid.renderContainers.body, leftContainer, rightContainer); }, /** * @ngdoc service * @name getDirection * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @description determines which direction to for a given keyDown event * @returns {uiGridCellNavConstants.direction} direction */ getDirection: function (evt) { if (evt.keyCode === uiGridConstants.keymap.LEFT || (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey)) { return uiGridCellNavConstants.direction.LEFT; } if (evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.TAB) { return uiGridCellNavConstants.direction.RIGHT; } if (evt.keyCode === uiGridConstants.keymap.UP || (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ) { return uiGridCellNavConstants.direction.UP; } if (evt.keyCode === uiGridConstants.keymap.PG_UP){ return uiGridCellNavConstants.direction.PG_UP; } if (evt.keyCode === uiGridConstants.keymap.DOWN || evt.keyCode === uiGridConstants.keymap.ENTER && !(evt.ctrlKey || evt.altKey)) { return uiGridCellNavConstants.direction.DOWN; } if (evt.keyCode === uiGridConstants.keymap.PG_DOWN){ return uiGridCellNavConstants.direction.PG_DOWN; } return null; }, /** * @ngdoc service * @name cellNavColumnBuilder * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @description columnBuilder function that adds cell navigation properties to grid column * @returns {promise} promise that will load any needed templates when resolved */ cellNavColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.cellNav.api:ColumnDef * * @description Column Definitions for cellNav feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name allowCellFocus * @propertyOf ui.grid.cellNav.api:ColumnDef * @description Enable focus on a cell within this column. * <br/>Defaults to true */ colDef.allowCellFocus = colDef.allowCellFocus === undefined ? true : colDef.allowCellFocus; return $q.all(promises); }, /** * @ngdoc method * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @name scrollToFocus * @description Scroll the grid such that the specified * row and column is in view, and set focus to the cell in that row and column * @param {Grid} grid the grid you'd like to act upon, usually available * from gridApi.grid * @param {object} rowEntity gridOptions.data[] array instance to make visible and set focus to * @param {object} colDef to make visible and set focus to * @returns {promise} a promise that is resolved after any scrolling is finished */ scrollToFocus: function (grid, rowEntity, colDef) { var gridRow = null, gridCol = null; if (typeof(rowEntity) !== 'undefined' && rowEntity !== null) { gridRow = grid.getRow(rowEntity); } if (typeof(colDef) !== 'undefined' && colDef !== null) { gridCol = grid.getColumn(colDef.name ? colDef.name : colDef.field); } return grid.api.core.scrollToIfNecessary(gridRow, gridCol).then(function () { var rowCol = { row: gridRow, col: gridCol }; // Broadcast the navigation if (gridRow !== null && gridCol !== null) { grid.cellNav.broadcastCellNav(rowCol); } }); }, /** * @ngdoc method * @methodOf ui.grid.cellNav.service:uiGridCellNavService * @name getLeftWidth * @description Get the current drawn width of the columns in the * grid up to the numbered column, and add an apportionment for the * column that we're on. So if we are on column 0, we want to scroll * 0% (i.e. exclude this column from calc). If we're on the last column * we want to scroll to 100% (i.e. include this column in the calc). So * we include (thisColIndex / totalNumberCols) % of this column width * @param {Grid} grid the grid you'd like to act upon, usually available * from gridApi.grid * @param {gridCol} upToCol the column to total up to and including */ getLeftWidth: function (grid, upToCol) { var width = 0; if (!upToCol) { return width; } var lastIndex = grid.renderContainers.body.visibleColumnCache.indexOf( upToCol ); // total column widths up-to but not including the passed in column grid.renderContainers.body.visibleColumnCache.forEach( function( col, index ) { if ( index < lastIndex ){ width += col.drawnWidth; } }); // pro-rata the final column based on % of total columns. var percentage = lastIndex === 0 ? 0 : (lastIndex + 1) / grid.renderContainers.body.visibleColumnCache.length; width += upToCol.drawnWidth * percentage; return width; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.cellNav.directive:uiCellNav * @element div * @restrict EA * * @description Adds cell navigation features to the grid columns * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.cellNav']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name'}, {name: 'title'} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-cellnav></div> </div> </file> </example> */ module.directive('uiGridCellnav', ['gridUtil', 'uiGridCellNavService', 'uiGridCellNavConstants', 'uiGridConstants', '$timeout', function (gridUtil, uiGridCellNavService, uiGridCellNavConstants, uiGridConstants, $timeout) { return { replace: true, priority: -150, require: '^uiGrid', scope: false, controller: function () {}, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { var _scope = $scope; var grid = uiGridCtrl.grid; uiGridCellNavService.initializeGrid(grid); uiGridCtrl.cellNav = {}; uiGridCtrl.cellNav.getActiveCell = function () { var elms = $elm[0].getElementsByClassName('ui-grid-cell-focus'); if (elms.length > 0){ return elms[0]; } return undefined; }; uiGridCtrl.cellNav.broadcastCellNav = grid.cellNav.broadcastCellNav = function (newRowCol, modifierDown) { modifierDown = !(modifierDown === undefined || !modifierDown); uiGridCtrl.cellNav.broadcastFocus(newRowCol, modifierDown); _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT, newRowCol, modifierDown); }; uiGridCtrl.cellNav.clearFocus = grid.cellNav.clearFocus = function () { _scope.$broadcast(uiGridCellNavConstants.CELL_NAV_EVENT, { eventType: uiGridCellNavConstants.EVENT_TYPE.CLEAR }); }; uiGridCtrl.cellNav.broadcastFocus = function (rowCol, modifierDown) { modifierDown = !(modifierDown === undefined || !modifierDown); var row = rowCol.row, col = rowCol.col; var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol); if (grid.cellNav.lastRowCol === null || rowColSelectIndex === -1) { var newRowCol = new RowCol(row, col); grid.api.cellNav.raise.navigate(newRowCol, grid.cellNav.lastRowCol); grid.cellNav.lastRowCol = newRowCol; if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells && modifierDown) { grid.cellNav.focusedCells.push(rowCol); } else { grid.cellNav.focusedCells = [rowCol]; } } else if (grid.options.modifierKeysToMultiSelectCells && modifierDown && rowColSelectIndex >= 0) { grid.cellNav.focusedCells.splice(rowColSelectIndex, 1); } }; uiGridCtrl.cellNav.handleKeyDown = function (evt) { var direction = uiGridCellNavService.getDirection(evt); if (direction === null) { return null; } var containerId = 'body'; if (evt.uiGridTargetRenderContainerId) { containerId = evt.uiGridTargetRenderContainerId; } // Get the last-focused row+col combo var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (lastRowCol) { // Figure out which new row+combo we're navigating to var rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(direction, lastRowCol.row, lastRowCol.col); var focusableCols = uiGridCtrl.grid.renderContainers[containerId].cellNav.getFocusableCols(); var rowColSelectIndex = uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol); // Shift+tab on top-left cell should exit cellnav on render container if ( // Navigating left direction === uiGridCellNavConstants.direction.LEFT && // New col is last col (i.e. wrap around) rowCol.col === focusableCols[focusableCols.length - 1] && // Staying on same row, which means we're at first row rowCol.row === lastRowCol.row && evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey ) { grid.cellNav.focusedCells.splice(rowColSelectIndex, 1); uiGridCtrl.cellNav.clearFocus(); return true; } // Tab on bottom-right cell should exit cellnav on render container else if ( direction === uiGridCellNavConstants.direction.RIGHT && // New col is first col (i.e. wrap around) rowCol.col === focusableCols[0] && // Staying on same row, which means we're at first row rowCol.row === lastRowCol.row && evt.keyCode === uiGridConstants.keymap.TAB && !evt.shiftKey ) { grid.cellNav.focusedCells.splice(rowColSelectIndex, 1); uiGridCtrl.cellNav.clearFocus(); return true; } // Scroll to the new cell, if it's not completely visible within the render container's viewport grid.scrollToIfNecessary(rowCol.row, rowCol.col).then(function () { uiGridCtrl.cellNav.broadcastCellNav(rowCol); }); evt.stopPropagation(); evt.preventDefault(); return false; } }; }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); module.directive('uiGridRenderContainer', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', '$compile','uiGridCellNavConstants', function ($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, $compile, uiGridCellNavConstants) { return { replace: true, priority: -99999, //this needs to run very last require: ['^uiGrid', 'uiGridRenderContainer', '?^uiGridCellnav'], scope: false, compile: function () { return { post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], renderContainerCtrl = controllers[1]; // Skip attaching cell-nav specific logic if the directive is not attached above us if (!uiGridCtrl.grid.api.cellNav) { return; } var containerId = renderContainerCtrl.containerId; var grid = uiGridCtrl.grid; // focusser only created for body if (containerId !== 'body') { return; } // Needs to run last after all renderContainers are built uiGridCellNavService.decorateRenderContainers(grid); //add an element with no dimensions that can be used to set focus and capture keystrokes var focuser = $compile('<div class="ui-grid-focuser" tabindex="0"></div>')($scope); $elm.append(focuser); uiGridCtrl.focus = function () { focuser[0].focus(); //allow for first time grid focus focuser.on('focus', function (evt) { evt.uiGridTargetRenderContainerId = containerId; var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (rowCol === null) { rowCol = uiGridCtrl.grid.renderContainers[containerId].cellNav.getNextRowCol(uiGridCellNavConstants.direction.DOWN, null, null); if (rowCol.row && rowCol.col) { uiGridCtrl.cellNav.broadcastCellNav(rowCol); } } }); }; var viewPortKeyDownWasRaisedForRowCol = null; // Bind to keydown events in the render container focuser.on('keydown', function (evt) { evt.uiGridTargetRenderContainerId = containerId; var rowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); var result = uiGridCtrl.cellNav.handleKeyDown(evt); if (result === null) { uiGridCtrl.grid.api.cellNav.raise.viewPortKeyDown(evt, rowCol); viewPortKeyDownWasRaisedForRowCol = rowCol; } }); //Bind to keypress events in the render container //keypress events are needed by edit function so the key press //that initiated an edit is not lost //must fire the event in a timeout so the editor can //initialize and subscribe to the event on another event loop focuser.on('keypress', function (evt) { if (viewPortKeyDownWasRaisedForRowCol) { $timeout(function () { uiGridCtrl.grid.api.cellNav.raise.viewPortKeyPress(evt, viewPortKeyDownWasRaisedForRowCol); },4); viewPortKeyDownWasRaisedForRowCol = null; } }); } }; } }; }]); module.directive('uiGridViewport', ['$timeout', '$document', 'gridUtil', 'uiGridConstants', 'uiGridCellNavService', 'uiGridCellNavConstants','$log','$compile', function ($timeout, $document, gridUtil, uiGridConstants, uiGridCellNavService, uiGridCellNavConstants, $log, $compile) { return { replace: true, priority: -99999, //this needs to run very last require: ['^uiGrid', '^uiGridRenderContainer', '?^uiGridCellnav'], scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0], renderContainerCtrl = controllers[1]; // Skip attaching cell-nav specific logic if the directive is not attached above us if (!uiGridCtrl.grid.api.cellNav) { return; } var containerId = renderContainerCtrl.containerId; //no need to process for other containers if (containerId !== 'body') { return; } var grid = uiGridCtrl.grid; uiGridCtrl.focus(); grid.api.core.on.scrollBegin($scope, function (args) { // Skip if there's no currently-focused cell var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (lastRowCol == null) { return; } //if not in my container, move on //todo: worry about horiz scroll if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) { return; } //clear dom of focused cell var elements = $elm[0].getElementsByClassName('ui-grid-cell-focus'); Array.prototype.forEach.call(elements,function(e){angular.element(e).removeClass('ui-grid-cell-focus');}); }); grid.api.core.on.scrollEnd($scope, function (args) { // Skip if there's no currently-focused cell var lastRowCol = uiGridCtrl.grid.api.cellNav.getFocusedCell(); if (lastRowCol == null) { return; } //if not in my container, move on //todo: worry about horiz scroll if (!renderContainerCtrl.colContainer.containsColumn(lastRowCol.col)) { return; } uiGridCtrl.cellNav.broadcastCellNav(lastRowCol); }); grid.api.cellNav.on.navigate($scope, function () { //focus again because it can be lost uiGridCtrl.focus(); }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.cellNav.directive:uiGridCell * @element div * @restrict A * @description Stacks on top of ui.grid.uiGridCell to provide cell navigation */ module.directive('uiGridCell', ['$timeout', '$document', 'uiGridCellNavService', 'gridUtil', 'uiGridCellNavConstants', 'uiGridConstants', function ($timeout, $document, uiGridCellNavService, gridUtil, uiGridCellNavConstants, uiGridConstants) { return { priority: -150, // run after default uiGridCell directive and ui.grid.edit uiGridCell restrict: 'A', require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { // Skip attaching cell-nav specific logic if the directive is not attached above us if (!uiGridCtrl.grid.api.cellNav) { return; } if (!$scope.col.colDef.allowCellFocus) { return; } // When a cell is clicked, broadcast a cellNav event saying that this row+col combo is now focused $elm.find('div').on('click', function (evt) { uiGridCtrl.cellNav.broadcastCellNav(new RowCol($scope.row, $scope.col), evt.ctrlKey || evt.metaKey); evt.stopPropagation(); $scope.$apply(); }); $elm.find('div').on('focus', function (evt) { uiGridCtrl.cellNav.broadcastCellNav(new RowCol($scope.row, $scope.col), evt.ctrlKey || evt.metaKey); }); // This event is fired for all cells. If the cell matches, then focus is set $scope.$on(uiGridCellNavConstants.CELL_NAV_EVENT, function (evt, rowCol, modifierDown) { if (evt.eventType === uiGridCellNavConstants.EVENT_TYPE.CLEAR) { clearFocus(); return; } if (rowCol.row === $scope.row && rowCol.col === $scope.col) { if (uiGridCtrl.grid.options.modifierKeysToMultiSelectCells && modifierDown && uiGridCtrl.grid.api.cellNav.rowColSelectIndex(rowCol) === -1) { clearFocus(); } else { setFocused(); } // // This cellNav event came from a keydown event so we can safely refocus // if (rowCol.hasOwnProperty('eventType') && rowCol.eventType === uiGridCellNavConstants.EVENT_TYPE.KEYDOWN) { //// $elm.find('div')[0].focus(); // } } else if (!(uiGridCtrl.grid.options.modifierKeysToMultiSelectCells && modifierDown)) { clearFocus(); } }); function setFocused() { var div = $elm.find('div'); div.addClass('ui-grid-cell-focus'); } function clearFocus() { var div = $elm.find('div'); div.removeClass('ui-grid-cell-focus'); } $scope.$on('$destroy', function () { $elm.find('div').off('click'); }); } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.edit * @description * * # ui.grid.edit * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides cell editing capability to ui.grid. The goal was to emulate keying data in a spreadsheet via * a keyboard. * <br/> * <br/> * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the * user to key data and then tab, arrow, or enter to the cells beside or below. * * <div doc-module-components="ui.grid.edit"></div> */ var module = angular.module('ui.grid.edit', ['ui.grid']); /** * @ngdoc object * @name ui.grid.edit.constant:uiGridEditConstants * * @description constants available in edit module */ module.constant('uiGridEditConstants', { EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g, //must be lowercase because template bulder converts to lower EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g, events: { BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit', END_CELL_EDIT: 'uiGridEventEndCellEdit', CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit' } }); /** * @ngdoc service * @name ui.grid.edit.service:uiGridEditService * * @description Services for editing features */ module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil', function ($q, uiGridConstants, gridUtil) { var service = { initializeGrid: function (grid) { service.defaultGridOptions(grid.options); grid.registerColumnBuilder(service.editColumnBuilder); grid.edit = {}; /** * @ngdoc object * @name ui.grid.edit.api:PublicApi * * @description Public Api for edit feature */ var publicApi = { events: { edit: { /** * @ngdoc event * @name afterCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing is complete * <pre> * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited * @param {object} newValue new value * @param {object} oldValue old value */ afterCellEdit: function (rowEntity, colDef, newValue, oldValue) { }, /** * @ngdoc event * @name beginCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing starts on a cell * <pre> * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some * complex editors */ beginCellEdit: function (rowEntity, colDef, triggerEvent) { }, /** * @ngdoc event * @name cancelCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing is cancelled on a cell * <pre> * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited */ cancelCellEdit: function (rowEntity, colDef) { } } }, methods: { edit: { } } }; grid.api.registerEventsFromObject(publicApi.events); //grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.edit.api:GridOptions * * @description Options for configuring the edit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:GridOptions * @description If defined, sets the default value for the editable flag on each individual colDefs * if their individual enableCellEdit configuration is not defined. Defaults to undefined. */ /** * @ngdoc object * @name cellEditableCondition * @propertyOf ui.grid.edit.api:GridOptions * @description If specified, either a value or function to be used by all columns before editing. * If falsy, then editing of cell is not allowed. * @example * <pre> * function($scope){ * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed * return true; * } * </pre> */ gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition; /** * @ngdoc object * @name editableCellTemplate * @propertyOf ui.grid.edit.api:GridOptions * @description If specified, cellTemplate to use as the editor for all columns. * <br/> defaults to 'ui-grid/cellTextEditor' */ /** * @ngdoc object * @name enableCellEditOnFocus * @propertyOf ui.grid.edit.api:GridOptions * @description If true, then editor is invoked as soon as cell receives focus. Default false. * <br/>_requires cellNav feature and the edit feature to be enabled_ */ //enableCellEditOnFocus can only be used if cellnav module is used gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus; }, /** * @ngdoc service * @name editColumnBuilder * @methodOf ui.grid.edit.service:uiGridEditService * @description columnBuilder function that adds edit properties to grid column * @returns {promise} promise that will load any needed templates when resolved */ editColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.edit.api:ColumnDef * * @description Column Definition for edit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:ColumnDef * @description enable editing on column */ colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ? (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit; /** * @ngdoc object * @name cellEditableCondition * @propertyOf ui.grid.edit.api:ColumnDef * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed. * @example * <pre> * function($scope){ * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed * return true; * } * </pre> */ colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition; /** * @ngdoc object * @name editableCellTemplate * @propertyOf ui.grid.edit.api:ColumnDef * @description cell template to be used when editing this column. Can be Url or text template * <br/>Defaults to gridOptions.editableCellTemplate */ if (colDef.enableCellEdit) { colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor'; promises.push(gridUtil.getTemplate(colDef.editableCellTemplate) .then( function (template) { col.editableCellTemplate = template; }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'"); })); } /** * @ngdoc object * @name enableCellEditOnFocus * @propertyOf ui.grid.edit.api:ColumnDef * @requires ui.grid.cellNav * @description If true, then editor is invoked as soon as cell receives focus. Default false. * <br>_requires both the cellNav feature and the edit feature to be enabled_ */ //enableCellEditOnFocus can only be used if cellnav module is used colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus; /** * @ngdoc string * @name editModelField * @propertyOf ui.grid.edit.api:ColumnDef * @description a bindable string value that is used when binding to edit controls instead of colDef.field * <br/> example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The * grid should display state.name in the cell and sort/filter based on the state.name property but the editor * requires the full state object. * <br/>colDef.field = 'state.name' * <br/>colDef.editModelField = 'state' */ //colDef.editModelField return $q.all(promises); }, /** * @ngdoc service * @name isStartEditKey * @methodOf ui.grid.edit.service:uiGridEditService * @description Determines if a keypress should start editing. Decorate this service to override with your * own key events. See service decorator in angular docs. * @param {Event} evt keydown event * @returns {boolean} true if an edit should start */ isStartEditKey: function (evt) { if (evt.metaKey || evt.keyCode === uiGridConstants.keymap.ESC || evt.keyCode === uiGridConstants.keymap.SHIFT || evt.keyCode === uiGridConstants.keymap.CTRL || evt.keyCode === uiGridConstants.keymap.ALT || evt.keyCode === uiGridConstants.keymap.WIN || evt.keyCode === uiGridConstants.keymap.CAPSLOCK || evt.keyCode === uiGridConstants.keymap.LEFT || (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) || evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.TAB || evt.keyCode === uiGridConstants.keymap.UP || (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) || evt.keyCode === uiGridConstants.keymap.DOWN || evt.keyCode === uiGridConstants.keymap.ENTER) { return false; } return true; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEdit * @element div * @restrict A * * @description Adds editing features to the ui-grid directive. * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.edit']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-edit></div> </div> </file> </example> */ module.directive('uiGridEdit', ['gridUtil', 'uiGridEditService', function (gridUtil, uiGridEditService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridEditService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridRenderContainer * @element div * @restrict A * * @description Adds keydown listeners to renderContainer element so we can capture when to begin edits * */ module.directive('uiGridViewport', [ 'uiGridEditConstants', function ( uiGridEditConstants) { return { replace: true, priority: -99998, //run before cellNav require: ['^uiGrid', '^uiGridRenderContainer'], scope: false, compile: function () { return { post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; // Skip attaching if edit and cellNav is not enabled if (!uiGridCtrl.grid.api.edit || !uiGridCtrl.grid.api.cellNav) { return; } var containerId = controllers[1].containerId; //no need to process for other containers if (containerId !== 'body') { return; } //refocus on the grid $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () { uiGridCtrl.focus(); }); $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () { uiGridCtrl.focus(); }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridCell to provide in-line editing capabilities to the cell * Editing Actions. * * Binds edit start events to the uiGridCell element. When the events fire, the gridCell element is appended * with the columnDef.editableCellTemplate element ('cellEditor.html' by default). * * The editableCellTemplate should respond to uiGridEditConstants.events.BEGIN\_CELL\_EDIT angular event * and do the initial steps needed to edit the cell (setfocus on input element, etc). * * When the editableCellTemplate recognizes that the editing is ended (blur event, Enter key, etc.) * it should emit the uiGridEditConstants.events.END\_CELL\_EDIT event. * * If editableCellTemplate recognizes that the editing has been cancelled (esc key) * it should emit the uiGridEditConstants.events.CANCEL\_CELL\_EDIT event. The original value * will be set back on the model by the uiGridCell directive. * * Events that invoke editing: * - dblclick * - F2 keydown (when using cell selection) * * Events that end editing: * - Dependent on the specific editableCellTemplate * - Standards should be blur and enter keydown * * Events that cancel editing: * - Dependent on the specific editableCellTemplate * - Standards should be Esc keydown * * Grid Events that end editing: * - uiGridConstants.events.GRID_SCROLL * */ /** * @ngdoc object * @name ui.grid.edit.api:GridRow * * @description GridRow options for edit feature, these are available to be * set internally only, by other features */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:GridRow * @description enable editing on row, grouping for example might disable editing on group header rows */ module.directive('uiGridCell', ['$compile', '$injector', '$timeout', 'uiGridConstants', 'uiGridEditConstants', 'gridUtil', '$parse', 'uiGridEditService', '$rootScope', function ($compile, $injector, $timeout, uiGridConstants, uiGridEditConstants, gridUtil, $parse, uiGridEditService, $rootScope) { var touchstartTimeout = 500; if ($injector.has('uiGridCellNavService')) { var uiGridCellNavService = $injector.get('uiGridCellNavService'); } return { priority: -100, // run after default uiGridCell directive restrict: 'A', scope: false, require: '?^uiGrid', link: function ($scope, $elm, $attrs, uiGridCtrl) { var html; var origCellValue; var inEdit = false; var cellModel; var cancelTouchstartTimeout; var editCellScope; if (!$scope.col.colDef.enableCellEdit) { return; } var cellNavNavigateDereg = function() {}; // Bind to keydown events in the render container if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) { if (rowCol === null) { return; } if (rowCol.row === $scope.row && rowCol.col === $scope.col && !$scope.col.colDef.enableCellEditOnFocus) { //important to do this before scrollToIfNecessary beginEditKeyDown(evt); // uiGridCtrl.grid.api.core.scrollToIfNecessary(rowCol.row, rowCol.col); } }); } var setEditable = function() { if ($scope.col.colDef.enableCellEdit && $scope.row.enableCellEdit !== false) { registerBeginEditEvents(); } else { cancelBeginEditEvents(); } }; setEditable(); var rowWatchDereg = $scope.$watch( 'row', setEditable ); $scope.$on( '$destroy', rowWatchDereg ); function registerBeginEditEvents() { $elm.on('dblclick', beginEdit); // Add touchstart handling. If the users starts a touch and it doesn't end after X milliseconds, then start the edit $elm.on('touchstart', touchStart); if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { cellNavNavigateDereg = uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) { if ($scope.col.colDef.enableCellEditOnFocus) { if (newRowCol.row === $scope.row && newRowCol.col === $scope.col) { $timeout(function () { beginEdit(); }); } } }); } } function touchStart(event) { // jQuery masks events if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) { event = event.originalEvent; } // Bind touchend handler $elm.on('touchend', touchEnd); // Start a timeout cancelTouchstartTimeout = $timeout(function() { }, touchstartTimeout); // Timeout's done! Start the edit cancelTouchstartTimeout.then(function () { // Use setTimeout to start the edit because beginEdit expects to be outside of $digest setTimeout(beginEdit, 0); // Undbind the touchend handler, we don't need it anymore $elm.off('touchend', touchEnd); }); } // Cancel any touchstart timeout function touchEnd(event) { $timeout.cancel(cancelTouchstartTimeout); $elm.off('touchend', touchEnd); } function cancelBeginEditEvents() { $elm.off('dblclick', beginEdit); $elm.off('keydown', beginEditKeyDown); $elm.off('touchstart', touchStart); cellNavNavigateDereg(); } function beginEditKeyDown(evt) { if (uiGridEditService.isStartEditKey(evt)) { beginEdit(evt); } } function shouldEdit(col, row) { return !row.isSaving && ( angular.isFunction(col.colDef.cellEditableCondition) ? col.colDef.cellEditableCondition($scope) : col.colDef.cellEditableCondition ); } function beginEdit(triggerEvent) { //we need to scroll the cell into focus before invoking the editor $scope.grid.api.core.scrollToIfNecessary($scope.row, $scope.col) .then(function () { beginEditAfterScroll(triggerEvent); }); } /** * @ngdoc property * @name editDropdownOptionsArray * @propertyOf ui.grid.edit.api:ColumnDef * @description an array of values in the format * [ {id: xxx, value: xxx} ], which is populated * into the edit dropdown * */ /** * @ngdoc property * @name editDropdownIdLabel * @propertyOf ui.grid.edit.api:ColumnDef * @description the label for the "id" field * in the editDropdownOptionsArray. Defaults * to 'id' * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownRowEntityOptionsArrayPath * @propertyOf ui.grid.edit.api:ColumnDef * @description a path to a property on row.entity containing an * array of values in the format * [ {id: xxx, value: xxx} ], which will be used to populate * the edit dropdown. This can be used when the dropdown values are dependent on * the backing row entity. * If this property is set then editDropdownOptionsArray will be ignored. * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz', * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownValueLabel * @propertyOf ui.grid.edit.api:ColumnDef * @description the label for the "value" field * in the editDropdownOptionsArray. Defaults * to 'value' * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownFilter * @propertyOf ui.grid.edit.api:ColumnDef * @description A filter that you would like to apply to the values in the options list * of the dropdown. For example if you were using angular-translate you might set this * to `'translate'` * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' } * ], * </pre> * */ function beginEditAfterScroll(triggerEvent) { // If we are already editing, then just skip this so we don't try editing twice... if (inEdit) { return; } if (!shouldEdit($scope.col, $scope.row)) { return; } cellModel = $parse($scope.row.getQualifiedColField($scope.col)); //get original value from the cell origCellValue = cellModel($scope); html = $scope.col.editableCellTemplate; if ($scope.col.colDef.editModelField) { html = html.replace(uiGridConstants.MODEL_COL_FIELD, gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField)); } else { html = html.replace(uiGridConstants.MODEL_COL_FIELD, $scope.row.getQualifiedColField($scope.col)); } html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : ''; html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter); var inputType = 'text'; switch ($scope.col.colDef.type){ case 'boolean': inputType = 'checkbox'; break; case 'number': inputType = 'number'; break; case 'date': inputType = 'date'; break; } html = html.replace('INPUT_TYPE', inputType); var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath; if (editDropdownRowEntityOptionsArrayPath) { $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath); } else { $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray; } $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id'; $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value'; var cellElement; var createEditor = function(){ inEdit = true; cancelBeginEditEvents(); var cellElement = angular.element(html); $elm.append(cellElement); editCellScope = $scope.$new(); $compile(cellElement)(editCellScope); var gridCellContentsEl = angular.element($elm.children()[0]); gridCellContentsEl.addClass('ui-grid-cell-contents-hidden'); }; if (!$rootScope.$$phase) { $scope.$apply(createEditor); } else { createEditor(); } //stop editing when grid is scrolled var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function () { endEdit(); $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue); deregOnGridScroll(); deregOnEndCellEdit(); deregOnCancelCellEdit(); }); //end editing var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () { endEdit(); $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue); deregOnEndCellEdit(); deregOnGridScroll(); deregOnCancelCellEdit(); }); //cancel editing var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () { cancelEdit(); deregOnCancelCellEdit(); deregOnGridScroll(); deregOnEndCellEdit(); }); $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent); $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent); } function endEdit() { $scope.grid.disableScrolling = false; if (!inEdit) { return; } var gridCellContentsEl = angular.element($elm.children()[0]); //remove edit element editCellScope.$destroy(); angular.element($elm.children()[1]).remove(); gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden'); inEdit = false; registerBeginEditEvents(); $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.EDIT ); //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus //back to grid here if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { uiGridCtrl.focus(); } } function cancelEdit() { $scope.grid.disableScrolling = false; if (!inEdit) { return; } cellModel.assign($scope, origCellValue); $scope.$apply(); $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef); endEdit(); } // resolves a string path against the given object // shamelessly borrowed from // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key function resolveObjectFromPath(object, path) { path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties path = path.replace(/^\./, ''); // strip a leading dot var a = path.split('.'); while (a.length) { var n = a.shift(); if (n in object) { object = object[n]; } else { return; } } return object; } } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditor * @element div * @restrict A * * @description input editor directive for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditor', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', 'uiGridEditService', function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) { return { scope: true, require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'], compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl, renderContainerCtrl, ngModel; if (controllers[0]) { uiGridCtrl = controllers[0]; } if (controllers[1]) { renderContainerCtrl = controllers[1]; } if (controllers[2]) { ngModel = controllers[2]; } //set focus at start of edit $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function (evt,triggerEvent) { $timeout(function () { $elm[0].focus(); $elm[0].select(); }); //set the keystroke that started the edit event //we must do this because the BeginEdit is done in a different event loop than the intitial //keydown event //fire this event for the keypress that is received if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function (evt, rowCol) { if (uiGridEditService.isStartEditKey(evt)) { ngModel.$setViewValue(String.fromCharCode(evt.keyCode), evt); ngModel.$render(); } viewPortKeyDownUnregister(); }); } $elm.on('blur', function (evt) { $scope.stopEdit(evt); }); }); $scope.deepEdit = false; $scope.stopEdit = function (evt) { if ($scope.inputForm && !$scope.inputForm.$valid) { evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); } else { $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); } $scope.deepEdit = false; }; $elm.on('click', function (evt) { if ($elm[0].type !== 'checkbox') { $scope.deepEdit = true; $timeout(function () { $scope.grid.disableScrolling = true; }); } }); $elm.on('keydown', function (evt) { switch (evt.keyCode) { case uiGridConstants.keymap.ESC: evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); break; } if ($scope.deepEdit && (evt.keyCode === uiGridConstants.keymap.LEFT || evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.UP || evt.keyCode === uiGridConstants.keymap.DOWN)) { evt.stopPropagation(); } // Pass the keydown event off to the cellNav service, if it exists else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId; if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) { $scope.stopEdit(evt); } } else { //handle enter and tab for editing not using cellNav switch (evt.keyCode) { case uiGridConstants.keymap.ENTER: // Enter (Leave Field) case uiGridConstants.keymap.TAB: evt.stopPropagation(); evt.preventDefault(); $scope.stopEdit(evt); break; } } return true; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:input * @element input * @restrict E * * @description directive to provide binding between input[date] value and ng-model for angular 1.2 * It is similar to input[date] directive of angular 1.3 * * Supported date format for input is 'yyyy-MM-dd' * The directive will set the $valid property of input element and the enclosing form to false if * model is invalid date or value of input is entered wrong. * */ module.directive('uiGridEditor', ['$filter', function ($filter) { function parseDateString(dateString) { if (typeof(dateString) === 'undefined' || dateString === '') { return null; } var parts = dateString.split('-'); if (parts.length !== 3) { return null; } var year = parseInt(parts[0], 10); var month = parseInt(parts[1], 10); var day = parseInt(parts[2], 10); if (month < 1 || year < 1 || day < 1) { return null; } return new Date(year, (month - 1), day); } return { priority: -100, // run after default uiGridEditor directive require: '?ngModel', link: function (scope, element, attrs, ngModel) { if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) { ngModel.$formatters.push(function (modelValue) { ngModel.$setValidity(null,(!modelValue || !isNaN(modelValue.getTime()))); return $filter('date')(modelValue, 'yyyy-MM-dd'); }); ngModel.$parsers.push(function (viewValue) { if (viewValue && viewValue.length > 0) { var dateValue = parseDateString(viewValue); ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime()))); return dateValue; } else { ngModel.$setValidity(null, true); return null; } }); } } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditDropdown * @element div * @restrict A * * @description dropdown editor for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown, and any left/right nav * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditDropdown', ['uiGridConstants', 'uiGridEditConstants', function (uiGridConstants, uiGridEditConstants) { return { require: ['?^uiGrid', '?^uiGridRenderContainer'], scope: true, compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var renderContainerCtrl = controllers[1]; //set focus at start of edit $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () { $elm[0].focus(); $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px'; $elm.on('blur', function (evt) { $scope.stopEdit(evt); }); }); $scope.stopEdit = function (evt) { // no need to validate a dropdown - invalid values shouldn't be // available in the list $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); }; $elm.on('keydown', function (evt) { switch (evt.keyCode) { case uiGridConstants.keymap.ESC: evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); break; } if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId; if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) { $scope.stopEdit(evt); } } else { //handle enter and tab for editing not using cellNav switch (evt.keyCode) { case uiGridConstants.keymap.ENTER: // Enter (Leave Field) case uiGridConstants.keymap.TAB: evt.stopPropagation(); evt.preventDefault(); $scope.stopEdit(evt); break; } } return true; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditFileChooser * @element div * @restrict A * * @description input editor directive for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditFileChooser', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout) { return { scope: true, require: ['?^uiGrid', '?^uiGridRenderContainer'], compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl, renderContainerCtrl; if (controllers[0]) { uiGridCtrl = controllers[0]; } if (controllers[1]) { renderContainerCtrl = controllers[1]; } var grid = uiGridCtrl.grid; var handleFileSelect = function( event ){ var target = event.srcElement || event.target; if (target && target.files && target.files.length > 0) { /** * @ngdoc property * @name editFileChooserCallback * @propertyOf ui.grid.edit.api:ColumnDef * @description A function that should be called when any files have been chosen * by the user. You should use this to process the files appropriately for your * application. * * It passes the gridCol, the gridRow (from which you can get gridRow.entity), * and the files. The files are in the format as returned from the file chooser, * an array of files, with each having useful information such as: * - `files[0].lastModifiedDate` * - `files[0].name` * - `files[0].size` (appears to be in bytes) * - `files[0].type` (MIME type by the looks) * * Typically you would do something with these files - most commonly you would * use the filename or read the file itself in. The example function does both. * * @example * <pre> * editFileChooserCallBack: function(gridRow, gridCol, files ){ * // ignore all but the first file, it can only choose one anyway * // set the filename into this column * gridRow.entity.filename = file[0].name; * * // read the file and set it into a hidden column, which we may do stuff with later * var setFile = function(fileContent){ * gridRow.entity.file = fileContent.currentTarget.result; * }; * var reader = new FileReader(); * reader.onload = setFile; * reader.readAsText( files[0] ); * } * </pre> */ if ( typeof($scope.col.colDef.editFileChooserCallback) === 'function' ) { $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files); } else { gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser'); } target.form.reset(); $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); } else { $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); } }; $elm[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () { $elm[0].focus(); $elm[0].select(); $elm.on('blur', function (evt) { $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); }); }); } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.expandable * @description * * # ui.grid.expandable * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides the ability to create subgrids with the ability to expand a row * to show the subgrid. * * <div doc-module-components="ui.grid.expandable"></div> */ var module = angular.module('ui.grid.expandable', ['ui.grid']); /** * @ngdoc service * @name ui.grid.expandable.service:uiGridExpandableService * * @description Services for the expandable grid */ module.service('uiGridExpandableService', ['gridUtil', '$compile', function (gridUtil, $compile) { var service = { initializeGrid: function (grid) { grid.expandable = {}; grid.expandable.expandedAll = false; /** * @ngdoc object * @name enableExpandable * @propertyOf ui.grid.expandable.api:GridOptions * @description Whether or not to use expandable feature, allows you to turn off expandable on specific grids * within your application, or in specific modes on _this_ grid. Defaults to true. * @example * <pre> * $scope.gridOptions = { * enableExpandable: false * } * </pre> */ grid.options.enableExpandable = grid.options.enableExpandable !== false; /** * @ngdoc object * @name expandableRowHeight * @propertyOf ui.grid.expandable.api:GridOptions * @description Height in pixels of the expanded subgrid. Defaults to * 150 * @example * <pre> * $scope.gridOptions = { * expandableRowHeight: 150 * } * </pre> */ grid.options.expandableRowHeight = grid.options.expandableRowHeight || 150; /** * @ngdoc object * @name * @propertyOf ui.grid.expandable.api:GridOptions * @description Width in pixels of the expandable column. Defaults to 40 * @example * <pre> * $scope.gridOptions = { * expandableRowHeaderWidth: 40 * } * </pre> */ grid.options.expandableRowHeaderWidth = grid.options.expandableRowHeaderWidth || 40; /** * @ngdoc object * @name expandableRowTemplate * @propertyOf ui.grid.expandable.api:GridOptions * @description Mandatory. The template for your expanded row * @example * <pre> * $scope.gridOptions = { * expandableRowTemplate: 'expandableRowTemplate.html' * } * </pre> */ if ( grid.options.enableExpandable && !grid.options.expandableRowTemplate ){ gridUtil.logError( 'You have not set the expandableRowTemplate, disabling expandable module' ); grid.options.enableExpandable = false; } /** * @ngdoc object * @name ui.grid.expandable.api:PublicApi * * @description Public Api for expandable feature */ /** * @ngdoc object * @name ui.grid.expandable.api:GridOptions * * @description Options for configuring the expandable feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ var publicApi = { events: { expandable: { /** * @ngdoc event * @name rowExpandedStateChanged * @eventOf ui.grid.expandable.api:PublicApi * @description raised when cell editing is complete * <pre> * gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){}) * </pre> * @param {GridRow} row the row that was expanded */ rowExpandedStateChanged: function (scope, row) { } } }, methods: { expandable: { /** * @ngdoc method * @name toggleRowExpansion * @methodOf ui.grid.expandable.api:PublicApi * @description Toggle a specific row * <pre> * gridApi.expandable.toggleRowExpansion(rowEntity); * </pre> * @param {object} rowEntity the data entity for the row you want to expand */ toggleRowExpansion: function (rowEntity) { var row = grid.getRow(rowEntity); if (row !== null) { service.toggleRowExpansion(grid, row); } }, /** * @ngdoc method * @name expandAllRows * @methodOf ui.grid.expandable.api:PublicApi * @description Expand all subgrids. * <pre> * gridApi.expandable.expandAllRows(); * </pre> */ expandAllRows: function() { service.expandAllRows(grid); }, /** * @ngdoc method * @name collapseAllRows * @methodOf ui.grid.expandable.api:PublicApi * @description Collapse all subgrids. * <pre> * gridApi.expandable.collapseAllRows(); * </pre> */ collapseAllRows: function() { service.collapseAllRows(grid); }, /** * @ngdoc method * @name toggleAllRows * @methodOf ui.grid.expandable.api:PublicApi * @description Toggle all subgrids. * <pre> * gridApi.expandable.toggleAllRows(); * </pre> */ toggleAllRows: function() { service.toggleAllRows(grid); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, toggleRowExpansion: function (grid, row) { row.isExpanded = !row.isExpanded; if (row.isExpanded) { row.height = row.grid.options.rowHeight + grid.options.expandableRowHeight; } else { row.height = row.grid.options.rowHeight; grid.expandable.expandedAll = false; } grid.api.expandable.raise.rowExpandedStateChanged(row); }, expandAllRows: function(grid, $scope) { grid.renderContainers.body.visibleRowCache.forEach( function(row) { if (!row.isExpanded) { service.toggleRowExpansion(grid, row); } }); grid.expandable.expandedAll = true; grid.queueGridRefresh(); }, collapseAllRows: function(grid) { grid.renderContainers.body.visibleRowCache.forEach( function(row) { if (row.isExpanded) { service.toggleRowExpansion(grid, row); } }); grid.expandable.expandedAll = false; grid.queueGridRefresh(); }, toggleAllRows: function(grid) { if (grid.expandable.expandedAll) { service.collapseAllRows(grid); } else { service.expandAllRows(grid); } } }; return service; }]); /** * @ngdoc object * @name enableExpandableRowHeader * @propertyOf ui.grid.expandable.api:GridOptions * @description Show a rowHeader to provide the expandable buttons. If set to false then implies * you're going to use a custom method for expanding and collapsing the subgrids. Defaults to true. * @example * <pre> * $scope.gridOptions = { * enableExpandableRowHeader: false * } * </pre> */ module.directive('uiGridExpandable', ['uiGridExpandableService', '$templateCache', function (uiGridExpandableService, $templateCache) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if ( uiGridCtrl.grid.options.enableExpandableRowHeader !== false ) { var expandableRowHeaderColDef = { name: 'expandableButtons', displayName: '', exporterSuppressExport: true, enableColumnResizing: false, enableColumnMenu: false, width: uiGridCtrl.grid.options.expandableRowHeaderWidth || 40 }; expandableRowHeaderColDef.cellTemplate = $templateCache.get('ui-grid/expandableRowHeader'); expandableRowHeaderColDef.headerCellTemplate = $templateCache.get('ui-grid/expandableTopRowHeader'); uiGridCtrl.grid.addRowHeaderColumn(expandableRowHeaderColDef); } uiGridExpandableService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGrid * @description stacks on the uiGrid directive to register child grid with parent row when child is created */ module.directive('uiGrid', ['uiGridExpandableService', '$templateCache', function (uiGridExpandableService, $templateCache) { return { replace: true, priority: 599, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridCtrl.grid.api.core.on.renderingComplete($scope, function() { //if a parent grid row is on the scope, then add the parentRow property to this childGrid if ($scope.row && $scope.row.grid && $scope.row.grid.options && $scope.row.grid.options.enableExpandable) { /** * @ngdoc directive * @name ui.grid.expandable.class:Grid * @description Additional Grid properties added by expandable module */ /** * @ngdoc object * @name parentRow * @propertyOf ui.grid.expandable.class:Grid * @description reference to the expanded parent row that owns this grid */ uiGridCtrl.grid.parentRow = $scope.row; //todo: adjust height on parent row when child grid height changes. we need some sort of gridHeightChanged event // uiGridCtrl.grid.core.on.canvasHeightChanged($scope, function(oldHeight, newHeight) { // uiGridCtrl.grid.parentRow = newHeight; // }); } }); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGridExpandableRow * @description directive to render the expandable row template */ module.directive('uiGridExpandableRow', ['uiGridExpandableService', '$timeout', '$compile', 'uiGridConstants','gridUtil','$interval', '$log', function (uiGridExpandableService, $timeout, $compile, uiGridConstants, gridUtil, $interval, $log) { return { replace: false, priority: 0, scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { gridUtil.getTemplate($scope.grid.options.expandableRowTemplate).then( function (template) { if ($scope.grid.options.expandableRowScope) { var expandableRowScope = $scope.grid.options.expandableRowScope; for (var property in expandableRowScope) { if (expandableRowScope.hasOwnProperty(property)) { $scope[property] = expandableRowScope[property]; } } } var expandedRowElement = $compile(template)($scope); $elm.append(expandedRowElement); $scope.row.expandedRendered = true; }); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { $scope.$on('$destroy', function() { $scope.row.expandedRendered = false; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGridRow * @description stacks on the uiGridRow directive to add support for expandable rows */ module.directive('uiGridRow', ['$compile', 'gridUtil', '$templateCache', function ($compile, gridUtil, $templateCache) { return { priority: -200, scope: false, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, controllers) { $scope.expandableRow = {}; $scope.expandableRow.shouldRenderExpand = function () { var ret = $scope.colContainer.name === 'body' && $scope.grid.options.enableExpandable !== false && $scope.row.isExpanded && (!$scope.grid.isScrollingVertically || $scope.row.expandedRendered); return ret; }; $scope.expandableRow.shouldRenderFiller = function () { var ret = $scope.row.isExpanded && ( $scope.colContainer.name !== 'body' || ($scope.grid.isScrollingVertically && !$scope.row.expandedRendered)); return ret; }; /* * Commented out @PaulL1. This has no purpose that I can see, and causes #2964. If this code needs to be reinstated for some * reason it needs to use drawnWidth, not width, and needs to check column visibility. It should really use render container * visible column cache also instead of checking column.renderContainer. function updateRowContainerWidth() { var grid = $scope.grid; var colWidth = 0; grid.columns.forEach( function (column) { if (column.renderContainer === 'left') { colWidth += column.width; } }); colWidth = Math.floor(colWidth); return '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ', .grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ' .ui-grid-render-container-' + $scope.colContainer.name + ' .ui-grid-viewport .ui-grid-canvas .ui-grid-row { width: ' + colWidth + 'px; }'; } if ($scope.colContainer.name === 'left') { $scope.grid.registerStyleComputation({ priority: 15, func: updateRowContainerWidth }); }*/ }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.expandable.directive:uiGridViewport * @description stacks on the uiGridViewport directive to append the expandable row html elements to the * default gridRow template */ module.directive('uiGridViewport', ['$compile', 'gridUtil', '$templateCache', function ($compile, gridUtil, $templateCache) { return { priority: -200, scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var expandedRowFillerElement = $templateCache.get('ui-grid/expandableScrollFiller'); var expandedRowElement = $templateCache.get('ui-grid/expandableRow'); rowRepeatDiv.append(expandedRowElement); rowRepeatDiv.append(expandedRowFillerElement); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); /* global console */ (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.exporter * @description * * # ui.grid.exporter * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides the ability to exporter data from the grid. * * Data can be exported in a range of formats, and all data, visible * data, or selected rows can be exported, with all columns or visible * columns. * * No UI is provided, the caller should provide their own UI/buttons * as appropriate, or enable the gridMenu * * <br/> * <br/> * * <div doc-module-components="ui.grid.exporter"></div> */ var module = angular.module('ui.grid.exporter', ['ui.grid']); /** * @ngdoc object * @name ui.grid.exporter.constant:uiGridExporterConstants * * @description constants available in exporter module */ /** * @ngdoc property * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants * @name ALL * @description export all data, including data not visible. Can * be set for either rowTypes or colTypes */ /** * @ngdoc property * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants * @name VISIBLE * @description export only visible data, including data not visible. Can * be set for either rowTypes or colTypes */ /** * @ngdoc property * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants * @name SELECTED * @description export all data, including data not visible. Can * be set only for rowTypes, selection of only some columns is * not supported */ module.constant('uiGridExporterConstants', { featureName: 'exporter', ALL: 'all', VISIBLE: 'visible', SELECTED: 'selected', CSV_CONTENT: 'CSV_CONTENT', BUTTON_LABEL: 'BUTTON_LABEL', FILE_NAME: 'FILE_NAME' }); /** * @ngdoc service * @name ui.grid.exporter.service:uiGridExporterService * * @description Services for exporter feature */ module.service('uiGridExporterService', ['$q', 'uiGridExporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService', function ($q, uiGridExporterConstants, gridUtil, $compile, $interval, i18nService) { var service = { delay: 100, initializeGrid: function (grid) { //add feature namespace and any properties to grid for needed state grid.exporter = {}; this.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.exporter.api:PublicApi * * @description Public Api for exporter feature */ var publicApi = { events: { exporter: { } }, methods: { exporter: { /** * @ngdoc function * @name csvExport * @methodOf ui.grid.exporter.api:PublicApi * @description Exports rows from the grid in csv format, * the data exported is selected based on the provided options * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE */ csvExport: function (rowTypes, colTypes) { service.csvExport(grid, rowTypes, colTypes); }, /** * @ngdoc function * @name pdfExport * @methodOf ui.grid.exporter.api:PublicApi * @description Exports rows from the grid in pdf format, * the data exported is selected based on the provided options * Note that this function has a dependency on pdfMake, all * going well this has been installed for you. * The resulting pdf opens in a new browser window. * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE */ pdfExport: function (rowTypes, colTypes) { service.pdfExport(grid, rowTypes, colTypes); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); if (grid.api.core.addToGridMenu){ service.addToMenu( grid ); } else { // order of registration is not guaranteed, register in a little while $interval( function() { if (grid.api.core.addToGridMenu){ service.addToMenu( grid ); } }, this.delay, 1); } }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.exporter.api:GridOptions * * @description GridOptions for exporter feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name ui.grid.exporter.api:ColumnDef * @description ColumnDef settings for exporter */ /** * @ngdoc object * @name exporterSuppressMenu * @propertyOf ui.grid.exporter.api:GridOptions * @description Don't show the export menu button, implying the user * will roll their own UI for calling the exporter * <br/>Defaults to false */ gridOptions.exporterSuppressMenu = gridOptions.exporterSuppressMenu === true; /** * @ngdoc object * @name exporterMenuLabel * @propertyOf ui.grid.exporter.api:GridOptions * @description The text to show on the exporter menu button * link * <br/>Defaults to 'Export' */ gridOptions.exporterMenuLabel = gridOptions.exporterMenuLabel ? gridOptions.exporterMenuLabel : 'Export'; /** * @ngdoc object * @name exporterSuppressColumns * @propertyOf ui.grid.exporter.api:GridOptions * @description Columns that should not be exported. The selectionRowHeader is already automatically * suppressed, but if you had a button column or some other "system" column that shouldn't be shown in the * output then add it in this list. You should provide an array of column names. * <br/>Defaults to: [] * <pre> * gridOptions.exporterSuppressColumns = [ 'buttons' ]; * </pre> */ gridOptions.exporterSuppressColumns = gridOptions.exporterSuppressColumns ? gridOptions.exporterSuppressColumns : []; /** * @ngdoc object * @name exporterCsvColumnSeparator * @propertyOf ui.grid.exporter.api:GridOptions * @description The character to use as column separator * link * <br/>Defaults to ',' */ gridOptions.exporterCsvColumnSeparator = gridOptions.exporterCsvColumnSeparator ? gridOptions.exporterCsvColumnSeparator : ','; /** * @ngdoc object * @name exporterCsvFilename * @propertyOf ui.grid.exporter.api:GridOptions * @description The default filename to use when saving the downloaded csv. * This will only work in some browsers. * <br/>Defaults to 'download.csv' */ gridOptions.exporterCsvFilename = gridOptions.exporterCsvFilename ? gridOptions.exporterCsvFilename : 'download.csv'; /** * @ngdoc object * @name exporterPdfFilename * @propertyOf ui.grid.exporter.api:GridOptions * @description The default filename to use when saving the downloaded pdf, only used in IE (other browsers open pdfs in a new window) * <br/>Defaults to 'download.pdf' */ gridOptions.exporterPdfFilename = gridOptions.exporterPdfFilename ? gridOptions.exporterPdfFilename : 'download.pdf'; /** * @ngdoc object * @name exporterOlderExcelCompatibility * @propertyOf ui.grid.exporter.api:GridOptions * @description Some versions of excel don't like the utf-16 BOM on the front, and it comes * through as  in the first column header. Setting this option to false will suppress this, at the * expense of proper utf-16 handling in applications that do recognise the BOM * <br/>Defaults to false */ gridOptions.exporterOlderExcelCompatibility = gridOptions.exporterOlderExcelCompatibility === true; /** * @ngdoc object * @name exporterPdfDefaultStyle * @propertyOf ui.grid.exporter.api:GridOptions * @description The default style in pdfMake format * <br/>Defaults to: * <pre> * { * fontSize: 11 * } * </pre> */ gridOptions.exporterPdfDefaultStyle = gridOptions.exporterPdfDefaultStyle ? gridOptions.exporterPdfDefaultStyle : { fontSize: 11 }; /** * @ngdoc object * @name exporterPdfTableStyle * @propertyOf ui.grid.exporter.api:GridOptions * @description The table style in pdfMake format * <br/>Defaults to: * <pre> * { * margin: [0, 5, 0, 15] * } * </pre> */ gridOptions.exporterPdfTableStyle = gridOptions.exporterPdfTableStyle ? gridOptions.exporterPdfTableStyle : { margin: [0, 5, 0, 15] }; /** * @ngdoc object * @name exporterPdfTableHeaderStyle * @propertyOf ui.grid.exporter.api:GridOptions * @description The tableHeader style in pdfMake format * <br/>Defaults to: * <pre> * { * bold: true, * fontSize: 12, * color: 'black' * } * </pre> */ gridOptions.exporterPdfTableHeaderStyle = gridOptions.exporterPdfTableHeaderStyle ? gridOptions.exporterPdfTableHeaderStyle : { bold: true, fontSize: 12, color: 'black' }; /** * @ngdoc object * @name exporterPdfHeader * @propertyOf ui.grid.exporter.api:GridOptions * @description The header section for pdf exports. Can be * simple text: * <pre> * gridOptions.exporterPdfHeader = 'My Header'; * </pre> * Can be a more complex object in pdfMake format: * <pre> * gridOptions.exporterPdfHeader = { * columns: [ * 'Left part', * { text: 'Right part', alignment: 'right' } * ] * }; * </pre> * Or can be a function, allowing page numbers and the like * <pre> * gridOptions.exporterPdfHeader: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }; * </pre> */ gridOptions.exporterPdfHeader = gridOptions.exporterPdfHeader ? gridOptions.exporterPdfHeader : null; /** * @ngdoc object * @name exporterPdfFooter * @propertyOf ui.grid.exporter.api:GridOptions * @description The header section for pdf exports. Can be * simple text: * <pre> * gridOptions.exporterPdfFooter = 'My Footer'; * </pre> * Can be a more complex object in pdfMake format: * <pre> * gridOptions.exporterPdfFooter = { * columns: [ * 'Left part', * { text: 'Right part', alignment: 'right' } * ] * }; * </pre> * Or can be a function, allowing page numbers and the like * <pre> * gridOptions.exporterPdfFooter: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; }; * </pre> */ gridOptions.exporterPdfFooter = gridOptions.exporterPdfFooter ? gridOptions.exporterPdfFooter : null; /** * @ngdoc object * @name exporterPdfOrientation * @propertyOf ui.grid.exporter.api:GridOptions * @description The orientation, should be a valid pdfMake value, * 'landscape' or 'portrait' * <br/>Defaults to landscape */ gridOptions.exporterPdfOrientation = gridOptions.exporterPdfOrientation ? gridOptions.exporterPdfOrientation : 'landscape'; /** * @ngdoc object * @name exporterPdfPageSize * @propertyOf ui.grid.exporter.api:GridOptions * @description The orientation, should be a valid pdfMake * paper size, usually 'A4' or 'LETTER' * {@link https://github.com/bpampuch/pdfmake/blob/master/src/standardPageSizes.js pdfMake page sizes} * <br/>Defaults to A4 */ gridOptions.exporterPdfPageSize = gridOptions.exporterPdfPageSize ? gridOptions.exporterPdfPageSize : 'A4'; /** * @ngdoc object * @name exporterPdfMaxGridWidth * @propertyOf ui.grid.exporter.api:GridOptions * @description The maxium grid width - the current grid width * will be scaled to match this, with any fixed width columns * being adjusted accordingly. * <br/>Defaults to 720 (for A4 landscape), use 670 for LETTER */ gridOptions.exporterPdfMaxGridWidth = gridOptions.exporterPdfMaxGridWidth ? gridOptions.exporterPdfMaxGridWidth : 720; /** * @ngdoc object * @name exporterPdfTableLayout * @propertyOf ui.grid.exporter.api:GridOptions * @description A tableLayout in pdfMake format, * controls gridlines and the like. We use the default * layout usually. * <br/>Defaults to null, which means no layout */ /** * @ngdoc object * @name exporterMenuAllData * @porpertyOf ui.grid.exporter.api:GridOptions * @description Add export all data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true. */ gridOptions.exporterMenuAllData = gridOptions.exporterMenuAllData !== undefined ? gridOptions.exporterMenuAllData : true; /** * @ngdoc object * @name exporterMenuCsv * @propertyOf ui.grid.exporter.api:GridOptions * @description Add csv export menu items to the ui-grid grid menu, if it's present. Defaults to true. */ gridOptions.exporterMenuCsv = gridOptions.exporterMenuCsv !== undefined ? gridOptions.exporterMenuCsv : true; /** * @ngdoc object * @name exporterMenuPdf * @propertyOf ui.grid.exporter.api:GridOptions * @description Add pdf export menu items to the ui-grid grid menu, if it's present. Defaults to true. */ gridOptions.exporterMenuPdf = gridOptions.exporterMenuPdf !== undefined ? gridOptions.exporterMenuPdf : true; /** * @ngdoc object * @name exporterPdfCustomFormatter * @propertyOf ui.grid.exporter.api:GridOptions * @description A custom callback routine that changes the pdf document, adding any * custom styling or content that is supported by pdfMake. Takes in the complete docDefinition, and * must return an updated docDefinition ready for pdfMake. * @example * In this example we add a style to the style array, so that we can use it in our * footer definition. * <pre> * gridOptions.exporterPdfCustomFormatter = function ( docDefinition ) { * docDefinition.styles.footerStyle = { bold: true, fontSize: 10 }; * return docDefinition; * } * * gridOptions.exporterPdfFooter = { text: 'My footer', style: 'footerStyle' } * </pre> */ gridOptions.exporterPdfCustomFormatter = ( gridOptions.exporterPdfCustomFormatter && typeof( gridOptions.exporterPdfCustomFormatter ) === 'function' ) ? gridOptions.exporterPdfCustomFormatter : function ( docDef ) { return docDef; }; /** * @ngdoc object * @name exporterHeaderFilterUseName * @propertyOf ui.grid.exporter.api:GridOptions * @description Defaults to false, which leads to `displayName` being passed into the headerFilter. * If set to true, then will pass `name` instead. * * * @example * <pre> * gridOptions.exporterHeaderFilterUseName = true; * </pre> */ gridOptions.exporterHeaderFilterUseName = gridOptions.exporterHeaderFilterUseName === true; /** * @ngdoc object * @name exporterHeaderFilter * @propertyOf ui.grid.exporter.api:GridOptions * @description A function to apply to the header displayNames before exporting. Useful for internationalisation, * for example if you were using angular-translate you'd set this to `$translate.instant`. Note that this * call must be synchronous, it cannot be a call that returns a promise. * * Behaviour can be changed to pass in `name` instead of `displayName` through use of `exporterHeaderFilterUseName: true`. * * @example * <pre> * gridOptions.exporterHeaderFilter = function( displayName ){ return 'col: ' + name; }; * </pre> * OR * <pre> * gridOptions.exporterHeaderFilter = $translate.instant; * </pre> */ /** * @ngdoc function * @name exporterFieldCallback * @propertyOf ui.grid.exporter.api:GridOptions * @description A function to call for each field before exporting it. Allows * massaging of raw data into a display format, for example if you have applied * filters to convert codes into decodes, or you require * a specific date format in the exported content. * * The method is called once for each field exported, and provides the grid, the * gridCol and the GridRow for you to use as context in massaging the data. * * @param {Grid} grid provides the grid in case you have need of it * @param {GridRow} row the row from which the data comes * @param {GridCol} col the column from which the data comes * @param {object} value the value for your massaging * @returns {object} you must return the massaged value ready for exporting * * @example * <pre> * gridOptions.exporterFieldCallback = function ( grid, row, col, value ){ * if ( col.name === 'status' ){ * value = decodeStatus( value ); * } * return value; * } * </pre> */ gridOptions.exporterFieldCallback = gridOptions.exporterFieldCallback ? gridOptions.exporterFieldCallback : function( grid, row, col, value ) { return value; }; /** * @ngdoc function * @name exporterAllDataFn * @propertyOf ui.grid.exporter.api:GridOptions * @description This promise is needed when exporting all rows, * and the data need to be provided by server side. Default is null. * @returns {Promise} a promise to load all data from server * * @example * <pre> * gridOptions.exporterAllDataFn = function () { * return $http.get('/data/100.json') * } * </pre> */ gridOptions.exporterAllDataFn = gridOptions.exporterAllDataFn ? gridOptions.exporterAllDataFn : null; /** * @ngdoc function * @name exporterAllDataPromise * @propertyOf ui.grid.exporter.api:GridOptions * @description DEPRECATED - exporterAllDataFn used to be * called this, but it wasn't a promise, it was a function that returned * a promise. Deprecated, but supported for backward compatibility, use * exporterAllDataFn instead. * @returns {Promise} a promise to load all data from server * * @example * <pre> * gridOptions.exporterAllDataFn = function () { * return $http.get('/data/100.json') * } * </pre> */ if ( gridOptions.exporterAllDataFn == null && gridOptions.exporterAllDataPromise ) { gridOptions.exporterAllDataFn = gridOptions.exporterAllDataPromise; } }, /** * @ngdoc function * @name addToMenu * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Adds export items to the grid menu, * allowing the user to select export options * @param {Grid} grid the grid from which data should be exported */ addToMenu: function ( grid ) { grid.api.core.addToGridMenu( grid, [ { title: i18nService.getSafeText('gridMenu.exporterAllAsCsv'), action: function ($event) { this.grid.api.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL ); }, shown: function() { return this.grid.options.exporterMenuCsv && this.grid.options.exporterMenuAllData; }, order: 200 }, { title: i18nService.getSafeText('gridMenu.exporterVisibleAsCsv'), action: function ($event) { this.grid.api.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuCsv; }, order: 201 }, { title: i18nService.getSafeText('gridMenu.exporterSelectedAsCsv'), action: function ($event) { this.grid.api.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuCsv && ( this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0 ); }, order: 202 }, { title: i18nService.getSafeText('gridMenu.exporterAllAsPdf'), action: function ($event) { this.grid.api.exporter.pdfExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL ); }, shown: function() { return this.grid.options.exporterMenuPdf && this.grid.options.exporterMenuAllData; }, order: 203 }, { title: i18nService.getSafeText('gridMenu.exporterVisibleAsPdf'), action: function ($event) { this.grid.api.exporter.pdfExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuPdf; }, order: 204 }, { title: i18nService.getSafeText('gridMenu.exporterSelectedAsPdf'), action: function ($event) { this.grid.api.exporter.pdfExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE ); }, shown: function() { return this.grid.options.exporterMenuPdf && ( this.grid.api.selection && this.grid.api.selection.getSelectedRows().length > 0 ); }, order: 205 } ]); }, /** * @ngdoc function * @name csvExport * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Exports rows from the grid in csv format, * the data exported is selected based on the provided options * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ csvExport: function (grid, rowTypes, colTypes) { var self = this; this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function() { var exportColumnHeaders = self.getColumnHeaders(grid, colTypes); var exportData = self.getData(grid, rowTypes, colTypes); var csvContent = self.formatAsCsv(exportColumnHeaders, exportData, grid.options.exporterCsvColumnSeparator); self.downloadFile (grid.options.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility); }); }, /** * @ngdoc function * @name loadAllDataIfNeeded * @methodOf ui.grid.exporter.service:uiGridExporterService * @description When using server side pagination, use exporterAllDataFn to * load all data before continuing processing. * When using client side pagination, return a resolved promise so processing * continues immediately * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ loadAllDataIfNeeded: function (grid, rowTypes, colTypes) { if ( rowTypes === uiGridExporterConstants.ALL && grid.rows.length !== grid.options.totalItems && grid.options.exporterAllDataFn) { return grid.options.exporterAllDataFn() .then(function() { grid.modifyRows(grid.options.data); }); } else { var deferred = $q.defer(); deferred.resolve(); return deferred.promise; } }, /** * @ngdoc property * @propertyOf ui.grid.exporter.api:ColumnDef * @name exporterSuppressExport * @description Suppresses export for this column. Used by selection and expandable. */ /** * @ngdoc function * @name getColumnHeaders * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Gets the column headers from the grid to use * as a title row for the exported file, all headers have * headerCellFilters applied as appropriate. * * Column headers are an array of objects, each object has * name, displayName, width and align attributes. Only name is * used for csv, all attributes are used for pdf. * * @param {Grid} grid the grid from which data should be exported * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ getColumnHeaders: function (grid, colTypes) { var headers = []; var columns; if ( colTypes === uiGridExporterConstants.ALL ){ columns = grid.columns; } else { columns = grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ); } columns.forEach( function( gridCol, index ) { if ( gridCol.colDef.exporterSuppressExport !== true && grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){ headers.push({ name: gridCol.field, displayName: grid.options.exporterHeaderFilter ? ( grid.options.exporterHeaderFilterUseName ? grid.options.exporterHeaderFilter(gridCol.name) : grid.options.exporterHeaderFilter(gridCol.displayName) ) : gridCol.displayName, width: gridCol.drawnWidth ? gridCol.drawnWidth : gridCol.width, align: gridCol.colDef.type === 'number' ? 'right' : 'left' }); } }); return headers; }, /** * @ngdoc property * @propertyOf ui.grid.exporter.api:ColumnDef * @name exporterPdfAlign * @description the alignment you'd like for this specific column when * exported into a pdf. Can be 'left', 'right', 'center' or any other * valid pdfMake alignment option. */ /** * @ngdoc object * @name ui.grid.exporter.api:GridRow * @description GridRow settings for exporter */ /** * @ngdoc object * @name exporterEnableExporting * @propertyOf ui.grid.exporter.api:GridRow * @description If set to false, then don't export this row, notwithstanding visible or * other settings * <br/>Defaults to true */ /** * @ngdoc function * @name getData * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Gets data from the grid based on the provided options, * all cells have cellFilters applied as appropriate. Any rows marked * `exporterEnableExporting: false` will not be exported * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ getData: function (grid, rowTypes, colTypes) { var data = []; var rows; var columns; switch ( rowTypes ) { case uiGridExporterConstants.ALL: rows = grid.rows; break; case uiGridExporterConstants.VISIBLE: rows = grid.getVisibleRows(); break; case uiGridExporterConstants.SELECTED: if ( grid.api.selection ){ rows = grid.api.selection.getSelectedGridRows(); } else { gridUtil.logError('selection feature must be enabled to allow selected rows to be exported'); } break; } if ( colTypes === uiGridExporterConstants.ALL ){ columns = grid.columns; } else { columns = grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ); } rows.forEach( function( row, index ) { if (row.exporterEnableExporting !== false) { var extractedRow = []; columns.forEach( function( gridCol, index ) { if ( (gridCol.visible || colTypes === uiGridExporterConstants.ALL ) && gridCol.colDef.exporterSuppressExport !== true && grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){ var extractedField = { value: grid.options.exporterFieldCallback( grid, row, gridCol, grid.getCellValue( row, gridCol ) ) }; if ( gridCol.colDef.exporterPdfAlign ) { extractedField.alignment = gridCol.colDef.exporterPdfAlign; } extractedRow.push(extractedField); } }); data.push(extractedRow); } }); return data; }, /** * @ngdoc function * @name formatAsCSV * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Formats the column headers and data as a CSV, * and sends that data to the user * @param {array} exportColumnHeaders an array of column headers, * where each header is an object with name, width and maybe alignment * @param {array} exportData an array of rows, where each row is * an array of column data * @returns {string} csv the formatted csv as a string */ formatAsCsv: function (exportColumnHeaders, exportData, separator) { var self = this; var bareHeaders = exportColumnHeaders.map(function(header){return { value: header.displayName };}); var csv = self.formatRowAsCsv(this, separator)(bareHeaders) + '\n'; csv += exportData.map(this.formatRowAsCsv(this, separator)).join('\n'); return csv; }, /** * @ngdoc function * @name formatRowAsCsv * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a single field as a csv field, including * quotes around the value * @param {exporterService} exporter pass in exporter * @param {array} row the row to be turned into a csv string * @returns {string} a csv-ified version of the row */ formatRowAsCsv: function (exporter, separator) { return function (row) { return row.map(exporter.formatFieldAsCsv).join(separator); }; }, /** * @ngdoc function * @name formatFieldAsCsv * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a single field as a csv field, including * quotes around the value * @param {field} field the field to be turned into a csv string, * may be of any type * @returns {string} a csv-ified version of the field */ formatFieldAsCsv: function (field) { if (field.value == null) { // we want to catch anything null-ish, hence just == not === return ''; } if (typeof(field.value) === 'number') { return field.value; } if (typeof(field.value) === 'boolean') { return (field.value ? 'TRUE' : 'FALSE') ; } if (typeof(field.value) === 'string') { return '"' + field.value.replace(/"/g,'""') + '"'; } return JSON.stringify(field.value); }, /** * @ngdoc function * @name isIE * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Checks whether current browser is IE and returns it's version if it is */ isIE: function () { var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/); return match ? parseInt(match[1]) : false; }, /** * @ngdoc function * @name downloadFile * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Triggers download of a csv file. Logic provided * by @cssensei (from his colleagues at https://github.com/ifeelgoods) in issue #2391 * @param {string} fileName the filename we'd like our file to be * given * @param {string} csvContent the csv content that we'd like to * download as a file * @param {boolean} exporterOlderExcelCompatibility whether or not we put a utf-16 BOM on the from (\uFEFF) */ downloadFile: function (fileName, csvContent, exporterOlderExcelCompatibility) { var D = document; var a = D.createElement('a'); var strMimeType = 'application/octet-stream;charset=utf-8'; var rawFile; var ieVersion; ieVersion = this.isIE(); if (ieVersion && ieVersion < 10) { var frame = D.createElement('iframe'); document.body.appendChild(frame); frame.contentWindow.document.open("text/html", "replace"); frame.contentWindow.document.write('sep=,\r\n' + csvContent); frame.contentWindow.document.close(); frame.contentWindow.focus(); frame.contentWindow.document.execCommand('SaveAs', true, fileName); document.body.removeChild(frame); return true; } // IE10+ if (navigator.msSaveBlob) { return navigator.msSaveBlob( new Blob( [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent], { type: strMimeType } ), fileName ); } //html5 A[download] if ('download' in a) { var blob = new Blob( [exporterOlderExcelCompatibility ? "\uFEFF" : '', csvContent], { type: strMimeType } ); rawFile = URL.createObjectURL(blob); a.setAttribute('download', fileName); } else { rawFile = 'data:' + strMimeType + ',' + encodeURIComponent(csvContent); a.setAttribute('target', '_blank'); } a.href = rawFile; a.setAttribute('style', 'display:none;'); D.body.appendChild(a); setTimeout(function() { if (a.click) { a.click(); // Workaround for Safari 5 } else if (document.createEvent) { var eventObj = document.createEvent('MouseEvents'); eventObj.initEvent('click', true, true); a.dispatchEvent(eventObj); } D.body.removeChild(a); }, this.delay); }, /** * @ngdoc function * @name pdfExport * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Exports rows from the grid in pdf format, * the data exported is selected based on the provided options. * Note that this function has a dependency on pdfMake, which must * be installed. The resulting pdf opens in a new * browser window. * @param {Grid} grid the grid from which data should be exported * @param {string} rowTypes which rows to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED * @param {string} colTypes which columns to export, valid values are * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, * uiGridExporterConstants.SELECTED */ pdfExport: function (grid, rowTypes, colTypes) { var self = this; this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function () { var exportColumnHeaders = self.getColumnHeaders(grid, colTypes); var exportData = self.getData(grid, rowTypes, colTypes); var docDefinition = self.prepareAsPdf(grid, exportColumnHeaders, exportData); if (self.isIE()) { self.downloadPDF(grid.options.exporterPdfFilename, docDefinition); } else { pdfMake.createPdf(docDefinition).open(); } }); }, /** * @ngdoc function * @name downloadPdf * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Generates and retrieves the pdf as a blob, then downloads * it as a file. Only used in IE, in all other browsers we use the native * pdfMake.open function to just open the PDF * @param {string} fileName the filename to give to the pdf, can be set * through exporterPdfFilename * @param {object} docDefinition a pdf docDefinition that we can generate * and get a blob from */ downloadPDF: function (fileName, docDefinition) { var D = document; var a = D.createElement('a'); var strMimeType = 'application/octet-stream;charset=utf-8'; var rawFile; var ieVersion; ieVersion = this.isIE(); var doc = pdfMake.createPdf(docDefinition); var blob; doc.getBuffer( function (buffer) { blob = new Blob([buffer]); if (ieVersion && ieVersion < 10) { var frame = D.createElement('iframe'); document.body.appendChild(frame); frame.contentWindow.document.open("text/html", "replace"); frame.contentWindow.document.write(blob); frame.contentWindow.document.close(); frame.contentWindow.focus(); frame.contentWindow.document.execCommand('SaveAs', true, fileName); document.body.removeChild(frame); return true; } // IE10+ if (navigator.msSaveBlob) { return navigator.msSaveBlob( blob, fileName ); } }); }, /** * @ngdoc function * @name renderAsPdf * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders the data into a pdf, and opens that pdf. * * @param {Grid} grid the grid from which data should be exported * @param {array} exportColumnHeaders an array of column headers, * where each header is an object with name, width and maybe alignment * @param {array} exportData an array of rows, where each row is * an array of column data * @returns {object} a pdfMake format document definition, ready * for generation */ prepareAsPdf: function(grid, exportColumnHeaders, exportData) { var headerWidths = this.calculatePdfHeaderWidths( grid, exportColumnHeaders ); var headerColumns = exportColumnHeaders.map( function( header ) { return { text: header.displayName, style: 'tableHeader' }; }); var stringData = exportData.map(this.formatRowAsPdf(this)); var allData = [headerColumns].concat(stringData); var docDefinition = { pageOrientation: grid.options.exporterPdfOrientation, pageSize: grid.options.exporterPdfPageSize, content: [{ style: 'tableStyle', table: { headerRows: 1, widths: headerWidths, body: allData } }], styles: { tableStyle: grid.options.exporterPdfTableStyle, tableHeader: grid.options.exporterPdfTableHeaderStyle }, defaultStyle: grid.options.exporterPdfDefaultStyle }; if ( grid.options.exporterPdfLayout ){ docDefinition.layout = grid.options.exporterPdfLayout; } if ( grid.options.exporterPdfHeader ){ docDefinition.header = grid.options.exporterPdfHeader; } if ( grid.options.exporterPdfFooter ){ docDefinition.footer = grid.options.exporterPdfFooter; } if ( grid.options.exporterPdfCustomFormatter ){ docDefinition = grid.options.exporterPdfCustomFormatter( docDefinition ); } return docDefinition; }, /** * @ngdoc function * @name calculatePdfHeaderWidths * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Determines the column widths base on the * widths we got from the grid. If the column is drawn * then we have a drawnWidth. If the column is not visible * then we have '*', 'x%' or a width. When columns are * not visible they don't contribute to the overall gridWidth, * so we need to adjust to allow for extra columns * * Our basic heuristic is to take the current gridWidth, plus * numeric columns and call this the base gridwidth. * * To that we add 100 for any '*' column, and x% of the base gridWidth * for any column that is a % * * @param {Grid} grid the grid from which data should be exported * @param {array} exportHeaders array of header information * @returns {object} an array of header widths */ calculatePdfHeaderWidths: function ( grid, exportHeaders ) { var baseGridWidth = 0; exportHeaders.forEach( function(value){ if (typeof(value.width) === 'number'){ baseGridWidth += value.width; } }); var extraColumns = 0; exportHeaders.forEach( function(value){ if (value.width === '*'){ extraColumns += 100; } if (typeof(value.width) === 'string' && value.width.match(/(\d)*%/)) { var percent = parseInt(value.width.match(/(\d)*%/)[0]); value.width = baseGridWidth * percent / 100; extraColumns += value.width; } }); var gridWidth = baseGridWidth + extraColumns; return exportHeaders.map(function( header ) { return header.width === '*' ? header.width : header.width * grid.options.exporterPdfMaxGridWidth / gridWidth; }); }, /** * @ngdoc function * @name formatRowAsPdf * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a row in a format consumable by PDF, * mainly meaning casting everything to a string * @param {exporterService} exporter pass in exporter * @param {array} row the row to be turned into a csv string * @returns {string} a csv-ified version of the row */ formatRowAsPdf: function ( exporter ) { return function( row ) { return row.map(exporter.formatFieldAsPdfString); }; }, /** * @ngdoc function * @name formatFieldAsCsv * @methodOf ui.grid.exporter.service:uiGridExporterService * @description Renders a single field as a pdf-able field, which * is different from a csv field only in that strings don't have quotes * around them * @param {field} field the field to be turned into a pdf string, * may be of any type * @returns {string} a string-ified version of the field */ formatFieldAsPdfString: function (field) { var returnVal; if (field.value == null) { // we want to catch anything null-ish, hence just == not === returnVal = ''; } else if (typeof(field.value) === 'number') { returnVal = field.value.toString(); } else if (typeof(field.value) === 'boolean') { returnVal = (field.value ? 'TRUE' : 'FALSE') ; } else if (typeof(field.value) === 'string') { returnVal = field.value.replace(/"/g,'""'); } else { returnVal = JSON.stringify(field.value).replace(/^"/,'').replace(/"$/,''); } if (field.alignment && typeof(field.alignment) === 'string' ){ returnVal = { text: returnVal, alignment: field.alignment }; } return returnVal; } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.exporter.directive:uiGridExporter * @element div * @restrict A * * @description Adds exporter features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.exporter']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.gridOptions = { enableGridMenu: true, exporterMenuCsv: false, columnDefs: [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ], data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-exporter></div> </div> </file> </example> */ module.directive('uiGridExporter', ['uiGridExporterConstants', 'uiGridExporterService', 'gridUtil', '$compile', function (uiGridExporterConstants, uiGridExporterService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridExporterService.initializeGrid(uiGridCtrl.grid); uiGridCtrl.grid.exporter.$scope = $scope; } }; } ]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.grouping * @description * * # ui.grid.grouping * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides grouping of rows based on the data in them, similar * in concept to excel grouping. You can group multiple columns, resulting in * nested grouping. * * In concept this feature is similar to sorting + grid footer/aggregation, it * sorts the data based on the grouped columns, then creates group rows that * reflect a break in the data. Each of those group rows can have aggregations for * the data within that group. * * This feature leverages treeBase to provide the tree functionality itself, * the key thing this feature does therefore is to set treeLevels on the rows * and insert the group headers. * * Design information: * ------------------- * * Each column will get new menu items - group by, and aggregate by. Group by * will cause this column to be sorted (if not already), and will move this column * to the front of the sorted columns (i.e. grouped columns take precedence over * sorted columns). It will respect the sort order already set if there is one, * and it will allow the sorting logic to change that sort order, it just forces * the column to the front of the sorting. You can group by multiple columns, the * logic will add this column to the sorting after any already grouped columns. * * Once a grouping is defined, grouping logic is added to the rowsProcessors. This * will process the rows, identifying a break in the data value, and inserting a grouping row. * Grouping rows have specific attributes on them: * * - internalRow = true: tells us that this isn't a real row, so we can ignore it * from any processing that it looking at core data rows. This is used by the core * logic (or will be one day), as it's not grouping specific * - groupHeader = true: tells us this is a groupHeader. This is used by the grouping logic * to know if this is a groupHeader row or not * * Since the logic is baked into the rowsProcessors, it should get triggered whenever * row order or filtering or anything like that is changed. In order to avoid the row instantiation * time, and to preserve state across invocations, we hold a cache of the rows that we created * last time, and we use them again this time if we can. * * By default rows are collapsed, which means all data rows have their visible property * set to false, and only level 0 group rows are set to visible. * * <br/> * <br/> * * <div doc-module-components="ui.grid.grouping"></div> */ var module = angular.module('ui.grid.grouping', ['ui.grid', 'ui.grid.treeBase']); /** * @ngdoc object * @name ui.grid.grouping.constant:uiGridGroupingConstants * * @description constants available in grouping module, this includes * all the constants declared in the treeBase module (these are manually copied * as there isn't an easy way to include constants in another constants file, and * we don't want to make users include treeBase) * */ module.constant('uiGridGroupingConstants', { featureName: "grouping", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.grouping.service:uiGridGroupingService * * @description Services for grouping features */ module.service('uiGridGroupingService', ['$q', 'uiGridGroupingConstants', 'gridUtil', 'rowSorter', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'uiGridTreeBaseService', function ($q, uiGridGroupingConstants, gridUtil, rowSorter, GridRow, gridClassFactory, i18nService, uiGridConstants, uiGridTreeBaseService) { var service = { initializeGrid: function (grid, $scope) { uiGridTreeBaseService.initializeGrid( grid, $scope ); //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.grouping.grid:grouping * * @description Grid properties and functions added for grouping */ grid.grouping = {}; /** * @ngdoc property * @propertyOf ui.grid.grouping.grid:grouping * @name groupHeaderCache * * @description Cache that holds the group header rows we created last time, we'll * reuse these next time, not least because they hold our expanded states. * * We need to take care with these that they don't become a memory leak, we * create a new cache each time using the values from the old cache. This works * so long as we're creating group rows for invisible rows as well. * * The cache is a nested hash, indexed on the value we grouped by. So if we * grouped by gender then age, we'd maybe have something like: * ``` * { * male: { * row: <pointer to the old row>, * children: { * 22: { row: <pointer to the old row> }, * 31: { row: <pointer to the old row> } * }, * female: { * row: <pointer to the old row>, * children: { * 28: { row: <pointer to the old row> }, * 55: { row: <pointer to the old row> } * } * } * ``` * * We create new rows for any missing rows, this means that they come in as collapsed. * */ grid.grouping.groupHeaderCache = {}; service.defaultGridOptions(grid.options); grid.registerRowsProcessor(service.groupRows, 400); grid.registerColumnBuilder( service.groupingColumnBuilder); grid.registerColumnsProcessor(service.groupingColumnProcessor, 400); /** * @ngdoc object * @name ui.grid.grouping.api:PublicApi * * @description Public Api for grouping feature */ var publicApi = { events: { grouping: { /** * @ngdoc event * @eventOf ui.grid.grouping.api:PublicApi * @name aggregationChanged * @description raised whenever aggregation is changed, added or removed from a column * * <pre> * gridApi.grouping.on.aggregationChanged(scope,function(col){}) * </pre> * @param {gridCol} col the column which on which aggregation changed. The aggregation * type is available as `col.treeAggregation.type` */ aggregationChanged: {}, /** * @ngdoc event * @eventOf ui.grid.grouping.api:PublicApi * @name groupingChanged * @description raised whenever the grouped columns changes * * <pre> * gridApi.grouping.on.groupingChanged(scope,function(col){}) * </pre> * @param {gridCol} col the column which on which grouping changed. The new grouping is * available as `col.grouping` */ groupingChanged: {} } }, methods: { grouping: { /** * @ngdoc function * @name getGrouping * @methodOf ui.grid.grouping.api:PublicApi * @description Get the grouping configuration for this grid, * used by the saveState feature. Adds expandedState to the information * provided by the internal getGrouping, and removes any aggregations that have a source * of grouping (i.e. will be automatically reapplied when we regroup the column) * Returned grouping is an object * `{ grouping: groupArray, treeAggregations: aggregateArray, expandedState: hash }` * where grouping contains an array of objects: * `{ field: column.field, colName: column.name, groupPriority: column.grouping.groupPriority }` * and aggregations contains an array of objects: * `{ field: column.field, colName: column.name, aggregation: column.grouping.aggregation }` * and expandedState is a hash of the currently expanded nodes * * The groupArray will be sorted by groupPriority. * * @param {boolean} getExpanded whether or not to return the expanded state * @returns {object} grouping configuration */ getGrouping: function ( getExpanded ) { var grouping = service.getGrouping(grid); grouping.grouping.forEach( function( group ) { group.colName = group.col.name; delete group.col; }); grouping.aggregations.forEach( function( aggregation ) { aggregation.colName = aggregation.col.name; delete aggregation.col; }); grouping.aggregations = grouping.aggregations.filter( function( aggregation ){ return !aggregation.aggregation.source || aggregation.aggregation.source !== 'grouping'; }); if ( getExpanded ){ grouping.rowExpandedStates = service.getRowExpandedStates( grid.grouping.groupingHeaderCache ); } return grouping; }, /** * @ngdoc function * @name setGrouping * @methodOf ui.grid.grouping.api:PublicApi * @description Set the grouping configuration for this grid, * used by the saveState feature, but can also be used by any * user to specify a combined grouping and aggregation configuration * @param {object} config the config you want to apply, in the format * provided out by getGrouping */ setGrouping: function ( config ) { service.setGrouping(grid, config); }, /** * @ngdoc function * @name groupColumn * @methodOf ui.grid.grouping.api:PublicApi * @description Adds this column to the existing grouping, at the end of the priority order. * If the column doesn't have a sort, adds one, by default ASC * * This column will move to the left of any non-group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {string} columnName the name of the column we want to group */ groupColumn: function( columnName ) { var column = grid.getColumn(columnName); service.groupColumn(grid, column); }, /** * @ngdoc function * @name ungroupColumn * @methodOf ui.grid.grouping.api:PublicApi * @description Removes the groupPriority from this column. If the * column was previously aggregated the aggregation will come back. * The sort will remain. * * This column will move to the right of any other group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {string} columnName the name of the column we want to ungroup */ ungroupColumn: function( columnName ) { var column = grid.getColumn(columnName); service.ungroupColumn(grid, column); }, /** * @ngdoc function * @name clearGrouping * @methodOf ui.grid.grouping.api:PublicApi * @description Clear any grouped columns and any aggregations. Doesn't remove sorting, * as we don't know whether that sorting was added by grouping or was there beforehand * */ clearGrouping: function() { service.clearGrouping(grid); }, /** * @ngdoc function * @name aggregateColumn * @methodOf ui.grid.grouping.api:PublicApi * @description Sets the aggregation type on a column, if the * column is currently grouped then it removes the grouping first. * If the aggregationDef is null then will result in the aggregation * being removed * * @param {string} columnName the column we want to aggregate * @param {string} or {function} aggregationDef one of the recognised types * from uiGridGroupingConstants or a custom aggregation function. * @param {string} aggregationLabel (optional) The label to use for this aggregation. */ aggregateColumn: function( columnName, aggregationDef, aggregationLabel){ var column = grid.getColumn(columnName); service.aggregateColumn( grid, column, aggregationDef, aggregationLabel); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); grid.api.core.on.sortChanged( $scope, service.tidyPriorities); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.grouping.api:GridOptions * * @description GridOptions for grouping feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableGrouping * @propertyOf ui.grid.grouping.api:GridOptions * @description Enable row grouping for entire grid. * <br/>Defaults to true */ gridOptions.enableGrouping = gridOptions.enableGrouping !== false; /** * @ngdoc object * @name groupingShowCounts * @propertyOf ui.grid.grouping.api:GridOptions * @description shows counts on the groupHeader rows. Not that if you are using a cellFilter or a * sortingAlgorithm which relies on a specific format or data type, showing counts may cause that * to break, since the group header rows will always be a string with groupingShowCounts enabled. * <br/>Defaults to true except on columns of type 'date' */ gridOptions.groupingShowCounts = gridOptions.groupingShowCounts !== false; /** * @ngdoc object * @name groupingNullLabel * @propertyOf ui.grid.grouping.api:GridOptions * @description The string to use for the grouping header row label on rows which contain a null or undefined value in the grouped column. * <br/>Defaults to "Null" */ gridOptions.groupingNullLabel = typeof(gridOptions.groupingNullLabel) === 'undefined' ? 'Null' : gridOptions.groupingNullLabel; /** * @ngdoc object * @name enableGroupHeaderSelection * @propertyOf ui.grid.grouping.api:GridOptions * @description Allows group header rows to be selected. * <br/>Defaults to false */ gridOptions.enableGroupHeaderSelection = gridOptions.enableGroupHeaderSelection === true; }, /** * @ngdoc function * @name groupingColumnBuilder * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Sets the grouping defaults based on the columnDefs * * @param {object} colDef columnDef we're basing on * @param {GridCol} col the column we're to update * @param {object} gridOptions the options we should use * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved */ groupingColumnBuilder: function (colDef, col, gridOptions) { /** * @ngdoc object * @name ui.grid.grouping.api:ColumnDef * * @description ColumnDef for grouping feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableGrouping * @propertyOf ui.grid.grouping.api:ColumnDef * @description Enable grouping on this column * <br/>Defaults to true. */ if (colDef.enableGrouping === false){ return; } /** * @ngdoc object * @name grouping * @propertyOf ui.grid.grouping.api:ColumnDef * @description Set the grouping for a column. Format is: * ``` * { * groupPriority: <number, starts at 0, if less than 0 or undefined then we're aggregating in this column> * } * ``` * * **Note that aggregation used to be included in grouping, but is now separately set on the column via treeAggregation * setting in treeBase** * * We group in the priority order given, this will also put these columns to the high order of the sort irrespective * of the sort priority given them. If there is no sort defined then we sort ascending, if there is a sort defined then * we use that sort. * * If the groupPriority is undefined or less than 0, then we expect to be aggregating, and we look at the * aggregation types to determine what sort of aggregation we can do. Values are in the constants file, but * include SUM, COUNT, MAX, MIN * * groupPriorities should generally be sequential, if they're not then the next time getGrouping is called * we'll renumber them to be sequential. * <br/>Defaults to undefined. */ if ( typeof(col.grouping) === 'undefined' && typeof(colDef.grouping) !== 'undefined') { col.grouping = angular.copy(colDef.grouping); if ( typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority > -1 ){ col.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn; col.treeAggregationFinalizerFn = service.groupedFinalizerFn; } } else if (typeof(col.grouping) === 'undefined'){ col.grouping = {}; } if (typeof(col.grouping) !== 'undefined' && typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority >= 0){ col.suppressRemoveSort = true; } var groupColumn = { name: 'ui.grid.grouping.group', title: i18nService.get().grouping.group, icon: 'ui-grid-icon-indent-right', shown: function () { return typeof(this.context.col.grouping) === 'undefined' || typeof(this.context.col.grouping.groupPriority) === 'undefined' || this.context.col.grouping.groupPriority < 0; }, action: function () { service.groupColumn( this.context.col.grid, this.context.col ); } }; var ungroupColumn = { name: 'ui.grid.grouping.ungroup', title: i18nService.get().grouping.ungroup, icon: 'ui-grid-icon-indent-left', shown: function () { return typeof(this.context.col.grouping) !== 'undefined' && typeof(this.context.col.grouping.groupPriority) !== 'undefined' && this.context.col.grouping.groupPriority >= 0; }, action: function () { service.ungroupColumn( this.context.col.grid, this.context.col ); } }; var aggregateRemove = { name: 'ui.grid.grouping.aggregateRemove', title: i18nService.get().grouping.aggregate_remove, shown: function () { return typeof(this.context.col.treeAggregationFn) !== 'undefined'; }, action: function () { service.aggregateColumn( this.context.col.grid, this.context.col, null); } }; // generic adder for the aggregation menus, which follow a pattern var addAggregationMenu = function(type, title){ title = title || i18nService.get().grouping['aggregate_' + type] || type; var menuItem = { name: 'ui.grid.grouping.aggregate' + type, title: title, shown: function () { return typeof(this.context.col.treeAggregation) === 'undefined' || typeof(this.context.col.treeAggregation.type) === 'undefined' || this.context.col.treeAggregation.type !== type; }, action: function () { service.aggregateColumn( this.context.col.grid, this.context.col, type); } }; if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregate' + type)) { col.menuItems.push(menuItem); } }; /** * @ngdoc object * @name groupingShowGroupingMenu * @propertyOf ui.grid.grouping.api:ColumnDef * @description Show the grouping (group and ungroup items) menu on this column * <br/>Defaults to true. */ if ( col.colDef.groupingShowGroupingMenu !== false ){ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.group')) { col.menuItems.push(groupColumn); } if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.ungroup')) { col.menuItems.push(ungroupColumn); } } /** * @ngdoc object * @name groupingShowAggregationMenu * @propertyOf ui.grid.grouping.api:ColumnDef * @description Show the aggregation menu on this column * <br/>Defaults to true. */ if ( col.colDef.groupingShowAggregationMenu !== false ){ angular.forEach(uiGridTreeBaseService.nativeAggregations(), function(aggregationDef, name){ addAggregationMenu(name); }); angular.forEach(gridOptions.treeCustomAggregations, function(aggregationDef, name){ addAggregationMenu(name, aggregationDef.menuTitle); }); if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregateRemove')) { col.menuItems.push(aggregateRemove); } } }, /** * @ngdoc function * @name groupingColumnProcessor * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Moves the columns around based on which are grouped * * @param {array} columns the columns to consider rendering * @param {array} rows the grid rows, which we don't use but are passed to us * @returns {array} updated columns array */ groupingColumnProcessor: function( columns, rows ) { var grid = this; columns = service.moveGroupColumns(this, columns, rows); return columns; }, /** * @ngdoc function * @name groupedFinalizerFn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Used on group columns to display the rendered value and optionally * display the count of rows. * * @param {aggregation} the aggregation entity for a grouped column */ groupedFinalizerFn: function( aggregation ){ var col = this; if ( typeof(aggregation.groupVal) !== 'undefined') { aggregation.rendered = aggregation.groupVal; if ( col.grid.options.groupingShowCounts && col.colDef.type !== 'date' ){ aggregation.rendered += (' (' + aggregation.value + ')'); } } else { aggregation.rendered = null; } }, /** * @ngdoc function * @name moveGroupColumns * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Moves the column order so that the grouped columns are lined up * to the left (well, unless you're RTL, then it's the right). By doing this in * the columnsProcessor, we make it transient - when the column is ungrouped it'll * go back to where it was. * * Does nothing if the option `moveGroupColumns` is set to false. * * @param {Grid} grid grid object * @param {array} columns the columns that we should process/move * @param {array} rows the grid rows * @returns {array} updated columns */ moveGroupColumns: function( grid, columns, rows ){ if ( grid.options.moveGroupColumns === false){ return; } columns.forEach( function(column, index){ // position used to make stable sort in moveGroupColumns column.groupingPosition = index; }); columns.sort(function(a, b){ var a_group, b_group; if (a.isRowHeader){ a_group = -1000; } else if ( typeof(a.grouping) === 'undefined' || typeof(a.grouping.groupPriority) === 'undefined' || a.grouping.groupPriority < 0){ a_group = null; } else { a_group = a.grouping.groupPriority; } if (b.isRowHeader){ b_group = -1000; } else if ( typeof(b.grouping) === 'undefined' || typeof(b.grouping.groupPriority) === 'undefined' || b.grouping.groupPriority < 0){ b_group = null; } else { b_group = b.grouping.groupPriority; } // groups get sorted to the top if ( a_group !== null && b_group === null) { return -1; } if ( b_group !== null && a_group === null) { return 1; } if ( a_group !== null && b_group !== null) {return a_group - b_group; } return a.groupingPosition - b.groupingPosition; }); columns.forEach( function(column, index) { delete column.groupingPosition; }); return columns; }, /** * @ngdoc function * @name groupColumn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Adds this column to the existing grouping, at the end of the priority order. * If the column doesn't have a sort, adds one, by default ASC * * This column will move to the left of any non-group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {Grid} grid grid object * @param {GridCol} column the column we want to group */ groupColumn: function( grid, column){ if ( typeof(column.grouping) === 'undefined' ){ column.grouping = {}; } // set the group priority to the next number in the hierarchy var existingGrouping = service.getGrouping( grid ); column.grouping.groupPriority = existingGrouping.grouping.length; // add sort if not present if ( !column.sort ){ column.sort = { direction: uiGridConstants.ASC }; } else if ( typeof(column.sort.direction) === 'undefined' || column.sort.direction === null ){ column.sort.direction = uiGridConstants.ASC; } service.tidyPriorities( grid ); column.treeAggregation = { type: uiGridGroupingConstants.aggregation.COUNT, source: 'grouping' }; column.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn; column.treeAggregationFinalizerFn = service.groupedFinalizerFn; grid.api.grouping.raise.groupingChanged(column); grid.queueGridRefresh(); }, /** * @ngdoc function * @name ungroupColumn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Removes the groupPriority from this column. If the * column was previously aggregated the aggregation will come back. * The sort will remain. * * This column will move to the right of any other group columns, the * move is handled in a columnProcessor, so gets called as part of refresh * * @param {Grid} grid grid object * @param {GridCol} column the column we want to ungroup */ ungroupColumn: function( grid, column){ if ( typeof(column.grouping) === 'undefined' ){ return; } delete column.grouping.groupPriority; delete column.treeAggregation; delete column.customTreeAggregationFinalizer; service.tidyPriorities( grid ); grid.api.grouping.raise.groupingChanged(column); grid.queueGridRefresh(); }, /** * @ngdoc function * @name aggregateColumn * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Sets the aggregation type on a column, if the * column is currently grouped then it removes the grouping first. * * @param {Grid} grid grid object * @param {GridCol} column the column we want to aggregate * @param {string} one of the recognised types from uiGridGroupingConstants or one of the custom aggregations from gridOptions */ aggregateColumn: function( grid, column, aggregationType){ if (typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){ service.ungroupColumn( grid, column ); } var aggregationDef = {}; if ( typeof(grid.options.treeCustomAggregations[aggregationType]) !== 'undefined' ){ aggregationDef = grid.options.treeCustomAggregations[aggregationType]; } else if ( typeof(uiGridTreeBaseService.nativeAggregations()[aggregationType]) !== 'undefined' ){ aggregationDef = uiGridTreeBaseService.nativeAggregations()[aggregationType]; } column.treeAggregation = { type: aggregationType, label: i18nService.get().aggregation[aggregationDef.label] || aggregationDef.label }; column.treeAggregationFn = aggregationDef.aggregationFn; column.treeAggregationFinalizerFn = aggregationDef.finalizerFn; grid.api.grouping.raise.aggregationChanged(column); grid.queueGridRefresh(); }, /** * @ngdoc function * @name setGrouping * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Set the grouping based on a config object, used by the save state feature * (more specifically, by the restore function in that feature ) * * @param {Grid} grid grid object * @param {object} config the config we want to set, same format as that returned by getGrouping */ setGrouping: function ( grid, config ){ if ( typeof(config) === 'undefined' ){ return; } // first remove any existing grouping service.clearGrouping(grid); if ( config.grouping && config.grouping.length && config.grouping.length > 0 ){ config.grouping.forEach( function( group ) { var col = grid.getColumn(group.colName); if ( col ) { service.groupColumn( grid, col ); } }); } if ( config.aggregations && config.aggregations.length ){ config.aggregations.forEach( function( aggregation ) { var col = grid.getColumn(aggregation.colName); if ( col ) { service.aggregateColumn( grid, col, aggregation.aggregation.type ); } }); } if ( config.rowExpandedStates ){ service.applyRowExpandedStates( grid.grouping.groupingHeaderCache, config.rowExpandedStates ); } }, /** * @ngdoc function * @name clearGrouping * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Clear any grouped columns and any aggregations. Doesn't remove sorting, * as we don't know whether that sorting was added by grouping or was there beforehand * * @param {Grid} grid grid object */ clearGrouping: function( grid ) { var currentGrouping = service.getGrouping(grid); if ( currentGrouping.grouping.length > 0 ){ currentGrouping.grouping.forEach( function( group ) { if (!group.col){ // should have a group.colName if there's no col group.col = grid.getColumn(group.colName); } service.ungroupColumn(grid, group.col); }); } if ( currentGrouping.aggregations.length > 0 ){ currentGrouping.aggregations.forEach( function( aggregation ){ if (!aggregation.col){ // should have a group.colName if there's no col aggregation.col = grid.getColumn(aggregation.colName); } service.aggregateColumn(grid, aggregation.col, null); }); } }, /** * @ngdoc function * @name tidyPriorities * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Renumbers groupPriority and sortPriority such that * groupPriority is contiguous, and sortPriority either matches * groupPriority (for group columns), and otherwise is contiguous and * higher than groupPriority. * * @param {Grid} grid grid object */ tidyPriorities: function( grid ){ // if we're called from sortChanged, grid is in this, not passed as param, the param can be a column or undefined if ( ( typeof(grid) === 'undefined' || typeof(grid.grid) !== 'undefined' ) && typeof(this.grid) !== 'undefined' ) { grid = this.grid; } var groupArray = []; var sortArray = []; grid.columns.forEach( function(column, index){ if ( typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){ groupArray.push(column); } else if ( typeof(column.sort) !== 'undefined' && typeof(column.sort.priority) !== 'undefined' && column.sort.priority >= 0){ sortArray.push(column); } }); groupArray.sort(function(a, b){ return a.grouping.groupPriority - b.grouping.groupPriority; }); groupArray.forEach( function(column, index){ column.grouping.groupPriority = index; column.suppressRemoveSort = true; if ( typeof(column.sort) === 'undefined'){ column.sort = {}; } column.sort.priority = index; }); var i = groupArray.length; sortArray.sort(function(a, b){ return a.sort.priority - b.sort.priority; }); sortArray.forEach( function(column, index){ column.sort.priority = i; column.suppressRemoveSort = column.colDef.suppressRemoveSort; i++; }); }, /** * @ngdoc function * @name groupRows * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description The rowProcessor that creates the groupHeaders (i.e. does * the actual grouping). * * Assumes it is always called after the sorting processor, guaranteed by the priority setting * * Processes all the rows in order, inserting a groupHeader row whenever there is a change * in value of a grouped row, based on the sortAlgorithm used for the column. The group header row * is looked up in the groupHeaderCache, and used from there if there is one. The entity is reset * to {} if one is found. * * As it processes it maintains a `processingState` array. This records, for each level of grouping we're * working with, the following information: * ``` * { * fieldName: name, * col: col, * initialised: boolean, * currentValue: value, * currentRow: gridRow, * } * ``` * We look for changes in the currentValue at any of the levels. Where we find a change we: * * - create a new groupHeader row in the array * * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor * @returns {array} the updated rows, including our new group rows */ groupRows: function( renderableRows ) { if (renderableRows.length === 0){ return renderableRows; } var grid = this; grid.grouping.oldGroupingHeaderCache = grid.grouping.groupingHeaderCache || {}; grid.grouping.groupingHeaderCache = {}; var processingState = service.initialiseProcessingState( grid ); // processes each of the fields we are grouping by, checks if the value has changed and inserts a groupHeader // Broken out as shouldn't create functions in a loop. var updateProcessingState = function( groupFieldState, stateIndex ) { var fieldValue = grid.getCellValue(row, groupFieldState.col); // look for change of value - and insert a header if ( !groupFieldState.initialised || rowSorter.getSortFn(grid, groupFieldState.col, renderableRows)(fieldValue, groupFieldState.currentValue) !== 0 ){ service.insertGroupHeader( grid, renderableRows, i, processingState, stateIndex ); i++; } }; // use a for loop because it's tolerant of the array length changing whilst we go - we can // manipulate the iterator when we insert groupHeader rows for (var i = 0; i < renderableRows.length; i++ ){ var row = renderableRows[i]; if ( row.visible ){ processingState.forEach( updateProcessingState ); } } delete grid.grouping.oldGroupingHeaderCache; return renderableRows; }, /** * @ngdoc function * @name initialiseProcessingState * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Creates the processing state array that is used * for groupRows. * * @param {Grid} grid grid object * @returns {array} an array in the format described in the groupRows method, * initialised with blank values */ initialiseProcessingState: function( grid ){ var processingState = []; var columnSettings = service.getGrouping( grid ); columnSettings.grouping.forEach( function( groupItem, index){ processingState.push({ fieldName: groupItem.field, col: groupItem.col, initialised: false, currentValue: null, currentRow: null }); }); return processingState; }, /** * @ngdoc function * @name getGrouping * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Get the grouping settings from the columns. As a side effect * this always renumbers the grouping starting at 0 * @param {Grid} grid grid object * @returns {array} an array of the group fields, in order of priority */ getGrouping: function( grid ){ var groupArray = []; var aggregateArray = []; // get all the grouping grid.columns.forEach( function(column, columnIndex){ if ( column.grouping ){ if ( typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){ groupArray.push({ field: column.field, col: column, groupPriority: column.grouping.groupPriority, grouping: column.grouping }); } } if ( column.treeAggregation && column.treeAggregation.type ){ aggregateArray.push({ field: column.field, col: column, aggregation: column.treeAggregation }); } }); // sort grouping into priority order groupArray.sort( function(a, b){ return a.groupPriority - b.groupPriority; }); // renumber the priority in case it was somewhat messed up, then remove the grouping reference groupArray.forEach( function( group, index) { group.grouping.groupPriority = index; group.groupPriority = index; delete group.grouping; }); return { grouping: groupArray, aggregations: aggregateArray }; }, /** * @ngdoc function * @name insertGroupHeader * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Create a group header row, and link it to the various configuration * items that we use. * * Look for the row in the oldGroupingHeaderCache, write the row into the new groupingHeaderCache. * * @param {Grid} grid grid object * @param {array} renderableRows the rows that we are processing * @param {number} rowIndex the row we were up to processing * @param {array} processingState the current processing state * @param {number} stateIndex the processing state item that we were on when we triggered a new group header - * i.e. the column that we want to create a header for */ insertGroupHeader: function( grid, renderableRows, rowIndex, processingState, stateIndex ) { // set the value that caused the end of a group into the header row and the processing state var fieldName = processingState[stateIndex].fieldName; var col = processingState[stateIndex].col; var newValue = grid.getCellValue(renderableRows[rowIndex], col); var newDisplayValue = newValue; if ( typeof(newValue) === 'undefined' || newValue === null ) { newDisplayValue = grid.options.groupingNullLabel; } var cacheItem = grid.grouping.oldGroupingHeaderCache; for ( var i = 0; i < stateIndex; i++ ){ if ( cacheItem && cacheItem[processingState[i].currentValue] ){ cacheItem = cacheItem[processingState[i].currentValue].children; } } var headerRow; if ( cacheItem && cacheItem[newValue]){ headerRow = cacheItem[newValue].row; headerRow.entity = {}; } else { headerRow = new GridRow( {}, null, grid ); gridClassFactory.rowTemplateAssigner.call(grid, headerRow); } headerRow.entity['$$' + processingState[stateIndex].col.uid] = { groupVal: newDisplayValue }; headerRow.treeLevel = stateIndex; headerRow.groupHeader = true; headerRow.internalRow = true; headerRow.enableCellEdit = false; headerRow.enableSelection = grid.options.enableGroupHeaderSelection; processingState[stateIndex].initialised = true; processingState[stateIndex].currentValue = newValue; processingState[stateIndex].currentRow = headerRow; // set all processing states below this one to not be initialised - change of this state // means all those need to start again service.finaliseProcessingState( processingState, stateIndex + 1); // insert our new header row renderableRows.splice(rowIndex, 0, headerRow); // add our new header row to the cache cacheItem = grid.grouping.groupingHeaderCache; for ( i = 0; i < stateIndex; i++ ){ cacheItem = cacheItem[processingState[i].currentValue].children; } cacheItem[newValue] = { row: headerRow, children: {} }; }, /** * @ngdoc function * @name finaliseProcessingState * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Set all processing states lower than the one that had a break in value to * no longer be initialised. Render the counts into the entity ready for display. * * @param {Grid} grid grid object * @param {array} processingState the current processing state * @param {number} stateIndex the processing state item that we were on when we triggered a new group header, all * processing states after this need to be finalised */ finaliseProcessingState: function( processingState, stateIndex ){ for ( var i = stateIndex; i < processingState.length; i++){ processingState[i].initialised = false; processingState[i].currentRow = null; processingState[i].currentValue = null; } }, /** * @ngdoc function * @name getRowExpandedStates * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Extract the groupHeaderCache hash, pulling out only the states. * * The example below shows a grid that is grouped by gender then age * * <pre> * { * male: { * state: 'expanded', * children: { * 22: { state: 'expanded' }, * 30: { state: 'collapsed' } * } * }, * female: { * state: 'expanded', * children: { * 28: { state: 'expanded' }, * 55: { state: 'collapsed' } * } * } * } * </pre> * * @param {Grid} grid grid object * @returns {hash} the expanded states as a hash */ getRowExpandedStates: function(treeChildren){ if ( typeof(treeChildren) === 'undefined' ){ return {}; } var newChildren = {}; angular.forEach( treeChildren, function( value, key ){ newChildren[key] = { state: value.row.treeNode.state }; if ( value.children ){ newChildren[key].children = service.getRowExpandedStates( value.children ); } else { newChildren[key].children = {}; } }); return newChildren; }, /** * @ngdoc function * @name applyRowExpandedStates * @methodOf ui.grid.grouping.service:uiGridGroupingService * @description Take a hash in the format as created by getRowExpandedStates, * and apply it to the grid.grouping.groupHeaderCache. * * Takes a treeSubset, and applies to a treeSubset - so can be called * recursively. * * @param {object} currentNode can be grid.grouping.groupHeaderCache, or any of * the children of that hash * @returns {hash} expandedStates can be the full expanded states, or children * of that expanded states (which hopefully matches the subset of the groupHeaderCache) */ applyRowExpandedStates: function( currentNode, expandedStates ){ if ( typeof(expandedStates) === 'undefined' ){ return; } angular.forEach(expandedStates, function( value, key ) { if ( currentNode[key] ){ currentNode[key].row.treeNode.state = value.state; if (value.children && currentNode[key].children){ service.applyRowExpandedStates( currentNode[key].children, value.children ); } } }); } }; return service; }]); /** * @ngdoc directive * @name ui.grid.grouping.directive:uiGridGrouping * @element div * @restrict A * * @description Adds grouping features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.grouping']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-grouping></div> </div> </file> </example> */ module.directive('uiGridGrouping', ['uiGridGroupingConstants', 'uiGridGroupingService', '$templateCache', function (uiGridGroupingConstants, uiGridGroupingService, $templateCache) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if (uiGridCtrl.grid.options.enableGrouping !== false){ uiGridGroupingService.initializeGrid(uiGridCtrl.grid, $scope); } }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.importer * @description * * # ui.grid.importer * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides the ability to import data into the grid. It * uses the column defs to work out which data belongs in which column, * and creates entities from a configured class (typically a $resource). * * If the rowEdit feature is enabled, it also calls save on those newly * created objects, and then displays any errors in the imported data. * * Currently the importer imports only CSV and json files, although provision has been * made to process other file formats, and these can be added over time. * * For json files, the properties within each object in the json must match the column names * (to put it another way, the importer doesn't process the json, it just copies the objects * within the json into a new instance of the specified object type) * * For CSV import, the default column identification relies on each column in the * header row matching a column.name or column.displayName. Optionally, a column identification * callback can be used. This allows matching using other attributes, which is particularly * useful if your application has internationalised column headings (i.e. the headings that * the user sees don't match the column names). * * The importer makes use of the grid menu as the UI for requesting an * import. * * <div ui-grid-importer></div> */ var module = angular.module('ui.grid.importer', ['ui.grid']); /** * @ngdoc object * @name ui.grid.importer.constant:uiGridImporterConstants * * @description constants available in importer module */ module.constant('uiGridImporterConstants', { featureName: 'importer' }); /** * @ngdoc service * @name ui.grid.importer.service:uiGridImporterService * * @description Services for importer feature */ module.service('uiGridImporterService', ['$q', 'uiGridConstants', 'uiGridImporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService', '$window', function ($q, uiGridConstants, uiGridImporterConstants, gridUtil, $compile, $interval, i18nService, $window) { var service = { initializeGrid: function ($scope, grid) { //add feature namespace and any properties to grid for needed state grid.importer = { $scope: $scope }; this.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.importer.api:PublicApi * * @description Public Api for importer feature */ var publicApi = { events: { importer: { } }, methods: { importer: { /** * @ngdoc function * @name importFile * @methodOf ui.grid.importer.api:PublicApi * @description Imports a file into the grid using the file object * provided. Bypasses the grid menu * @param {File} fileObject the file we want to import, as a javascript * File object */ importFile: function ( fileObject ) { service.importThisFile( grid, fileObject ); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); if ( grid.options.enableImporter && grid.options.importerShowMenu ){ if ( grid.api.core.addToGridMenu ){ service.addToMenu( grid ); } else { // order of registration is not guaranteed, register in a little while $interval( function() { if (grid.api.core.addToGridMenu){ service.addToMenu( grid ); } }, 100, 1); } } }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.importer.api:GridOptions * * @description GridOptions for importer feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc property * @propertyOf ui.grid.importer.api:GridOptions * @name enableImporter * @description Whether or not importer is enabled. Automatically set * to false if the user's browser does not support the required fileApi. * Otherwise defaults to true. * */ if (gridOptions.enableImporter || gridOptions.enableImporter === undefined) { if ( !($window.hasOwnProperty('File') && $window.hasOwnProperty('FileReader') && $window.hasOwnProperty('FileList') && $window.hasOwnProperty('Blob')) ) { gridUtil.logError('The File APIs are not fully supported in this browser, grid importer cannot be used.'); gridOptions.enableImporter = false; } else { gridOptions.enableImporter = true; } } else { gridOptions.enableImporter = false; } /** * @ngdoc method * @name importerProcessHeaders * @methodOf ui.grid.importer.api:GridOptions * @description A callback function that will process headers using custom * logic. Set this callback function if the headers that your user will provide in their * import file don't necessarily match the grid header or field names. This might commonly * occur where your application is internationalised, and therefore the field names * that the user recognises are in a different language than the field names that * ui-grid knows about. * * Defaults to the internal `processHeaders` method, which seeks to match using both * displayName and column.name. Any non-matching columns are discarded. * * Your callback routine should respond by processing the header array, and returning an array * of matching column names. A null value in any given position means "don't import this column" * * <pre> * gridOptions.importerProcessHeaders: function( headerArray ) { * var myHeaderColumns = []; * var thisCol; * headerArray.forEach( function( value, index ) { * thisCol = mySpecialLookupFunction( value ); * myHeaderColumns.push( thisCol.name ); * }); * * return myHeaderCols; * }) * </pre> * @param {Grid} grid the grid we're importing into * @param {array} headerArray an array of the text from the first row of the csv file, * which you need to match to column.names * @returns {array} array of matching column names, in the same order as the headerArray * */ gridOptions.importerProcessHeaders = gridOptions.importerProcessHeaders || service.processHeaders; /** * @ngdoc method * @name importerHeaderFilter * @methodOf ui.grid.importer.api:GridOptions * @description A callback function that will filter (usually translate) a single * header. Used when you want to match the passed in column names to the column * displayName after the header filter. * * Your callback routine needs to return the filtered header value. * <pre> * gridOptions.importerHeaderFilter: function( displayName ) { * return $translate.instant( displayName ); * }) * </pre> * * or: * <pre> * gridOptions.importerHeaderFilter: $translate.instant * </pre> * @param {string} displayName the displayName that we'd like to translate * @returns {string} the translated name * */ gridOptions.importerHeaderFilter = gridOptions.importerHeaderFilter || function( displayName ) { return displayName; }; /** * @ngdoc method * @name importerErrorCallback * @methodOf ui.grid.importer.api:GridOptions * @description A callback function that provides custom error handling, rather * than the standard grid behaviour of an alert box and a console message. You * might use this to internationalise the console log messages, or to write to a * custom logging routine that returned errors to the server. * * <pre> * gridOptions.importerErrorCallback: function( grid, errorKey, consoleMessage, context ) { * myUserDisplayRoutine( errorKey ); * myLoggingRoutine( consoleMessage, context ); * }) * </pre> * @param {Grid} grid the grid we're importing into, may be useful if you're positioning messages * in some way * @param {string} errorKey one of the i18n keys the importer can return - importer.noHeaders, * importer.noObjects, importer.invalidCsv, importer.invalidJson, importer.jsonNotArray * @param {string} consoleMessage the English console message that importer would have written * @param {object} context the context data that importer would have appended to that console message, * often the file content itself or the element that is in error * */ if ( !gridOptions.importerErrorCallback || typeof(gridOptions.importerErrorCallback) !== 'function' ){ delete gridOptions.importerErrorCallback; } /** * @ngdoc method * @name importerDataAddCallback * @methodOf ui.grid.importer.api:GridOptions * @description A mandatory callback function that adds data to the source data array. The grid * generally doesn't add rows to the source data array, it is tidier to handle this through a user * callback. * * <pre> * gridOptions.importerDataAddCallback: function( grid, newObjects ) { * $scope.myData = $scope.myData.concat( newObjects ); * }) * </pre> * @param {Grid} grid the grid we're importing into, may be useful in some way * @param {array} newObjects an array of new objects that you should add to your data * */ if ( gridOptions.enableImporter === true && !gridOptions.importerDataAddCallback ) { gridUtil.logError("You have not set an importerDataAddCallback, importer is disabled"); gridOptions.enableImporter = false; } /** * @ngdoc object * @name importerNewObject * @propertyOf ui.grid.importer.api:GridOptions * @description An object on which we call `new` to create each new row before inserting it into * the data array. Typically this would be a $resource entity, which means that if you're using * the rowEdit feature, you can directly call save on this entity when the save event is triggered. * * Defaults to a vanilla javascript object * * @example * <pre> * gridOptions.importerNewObject = MyRes; * </pre> * */ /** * @ngdoc property * @propertyOf ui.grid.importer.api:GridOptions * @name importerShowMenu * @description Whether or not to show an item in the grid menu. Defaults to true. * */ gridOptions.importerShowMenu = gridOptions.importerShowMenu !== false; /** * @ngdoc method * @methodOf ui.grid.importer.api:GridOptions * @name importerObjectCallback * @description A callback that massages the data for each object. For example, * you might have data stored as a code value, but display the decode. This callback * can be used to change the decoded value back into a code. Defaults to doing nothing. * @param {Grid} grid in case you need it * @param {object} newObject the new object as importer has created it, modify it * then return the modified version * @returns {object} the modified object * @example * <pre> * gridOptions.importerObjectCallback = function ( grid, newObject ) { * switch newObject.status { * case 'Active': * newObject.status = 1; * break; * case 'Inactive': * newObject.status = 2; * break; * } * return newObject; * }; * </pre> */ gridOptions.importerObjectCallback = gridOptions.importerObjectCallback || function( grid, newObject ) { return newObject; }; }, /** * @ngdoc function * @name addToMenu * @methodOf ui.grid.importer.service:uiGridImporterService * @description Adds import menu item to the grid menu, * allowing the user to request import of a file * @param {Grid} grid the grid into which data should be imported */ addToMenu: function ( grid ) { grid.api.core.addToGridMenu( grid, [ { title: i18nService.getSafeText('gridMenu.importerTitle'), order: 150 }, { templateUrl: 'ui-grid/importerMenuItemContainer', action: function ($event) { this.grid.api.importer.importAFile( grid ); }, order: 151 } ]); }, /** * @ngdoc function * @name importThisFile * @methodOf ui.grid.importer.service:uiGridImporterService * @description Imports the provided file into the grid using the file object * provided. Bypasses the grid menu * @param {Grid} grid the grid we're importing into * @param {File} fileObject the file we want to import, as returned from the File * javascript object */ importThisFile: function ( grid, fileObject ) { if (!fileObject){ gridUtil.logError( 'No file object provided to importThisFile, should be impossible, aborting'); return; } var reader = new FileReader(); switch ( fileObject.type ){ case 'application/json': reader.onload = service.importJsonClosure( grid ); break; default: reader.onload = service.importCsvClosure( grid ); break; } reader.readAsText( fileObject ); }, /** * @ngdoc function * @name importJson * @methodOf ui.grid.importer.service:uiGridImporterService * @description Creates a function that imports a json file into the grid. * The json data is imported into new objects of type `gridOptions.importerNewObject`, * and if the rowEdit feature is enabled the rows are marked as dirty * @param {Grid} grid the grid we want to import into * @param {FileObject} importFile the file that we want to import, as * a FileObject */ importJsonClosure: function( grid ) { return function( importFile ){ var newObjects = []; var newObject; var importArray = service.parseJson( grid, importFile ); if (importArray === null){ return; } importArray.forEach( function( value, index ) { newObject = service.newObject( grid ); angular.extend( newObject, value ); newObject = grid.options.importerObjectCallback( grid, newObject ); newObjects.push( newObject ); }); service.addObjects( grid, newObjects ); }; }, /** * @ngdoc function * @name parseJson * @methodOf ui.grid.importer.service:uiGridImporterService * @description Parses a json file, returns the parsed data. * Displays an error if file doesn't parse * @param {Grid} grid the grid that we want to import into * @param {FileObject} importFile the file that we want to import, as * a FileObject * @returns {array} array of objects from the imported json */ parseJson: function( grid, importFile ){ var loadedObjects; try { loadedObjects = JSON.parse( importFile.target.result ); } catch (e) { service.alertError( grid, 'importer.invalidJson', 'File could not be processed, is it valid json? Content was: ', importFile.target.result ); return; } if ( !Array.isArray( loadedObjects ) ){ service.alertError( grid, 'importer.jsonNotarray', 'Import failed, file is not an array, file was: ', importFile.target.result ); return []; } else { return loadedObjects; } }, /** * @ngdoc function * @name importCsvClosure * @methodOf ui.grid.importer.service:uiGridImporterService * @description Creates a function that imports a csv file into the grid * (allowing it to be used in the reader.onload event) * @param {Grid} grid the grid that we want to import into * @param {FileObject} importFile the file that we want to import, as * a file object */ importCsvClosure: function( grid ) { return function( importFile ){ var importArray = service.parseCsv( importFile ); if ( !importArray || importArray.length < 1 ){ service.alertError( grid, 'importer.invalidCsv', 'File could not be processed, is it valid csv? Content was: ', importFile.target.result ); return; } var newObjects = service.createCsvObjects( grid, importArray ); if ( !newObjects || newObjects.length === 0 ){ service.alertError( grid, 'importer.noObjects', 'Objects were not able to be derived, content was: ', importFile.target.result ); return; } service.addObjects( grid, newObjects ); }; }, /** * @ngdoc function * @name parseCsv * @methodOf ui.grid.importer.service:uiGridImporterService * @description Parses a csv file into an array of arrays, with the first * array being the headers, and the remaining arrays being the data. * The logic for this comes from https://github.com/thetalecrafter/excel.js/blob/master/src/csv.js, * which is noted as being under the MIT license. The code is modified to pass the jscs yoda condition * checker * @param {FileObject} importFile the file that we want to import, as a * file object */ parseCsv: function( importFile ) { var csv = importFile.target.result; // use the CSV-JS library to parse return CSV.parse(csv); }, /** * @ngdoc function * @name createCsvObjects * @methodOf ui.grid.importer.service:uiGridImporterService * @description Converts an array of arrays (representing the csv file) * into a set of objects. Uses the provided `gridOptions.importerNewObject` * to create the objects, and maps the header row into the individual columns * using either `gridOptions.importerProcessHeaders`, or by using a native method * of matching to either the displayName, column name or column field of * the columns in the column defs. The resulting objects will have attributes * that are named based on the column.field or column.name, in that order. * @param {Grid} grid the grid that we want to import into * @param {Array} importArray the data that we want to import, as an array */ createCsvObjects: function( grid, importArray ){ // pull off header row and turn into headers var headerMapping = grid.options.importerProcessHeaders( grid, importArray.shift() ); if ( !headerMapping || headerMapping.length === 0 ){ service.alertError( grid, 'importer.noHeaders', 'Column names could not be derived, content was: ', importArray ); return []; } var newObjects = []; var newObject; importArray.forEach( function( row, index ) { newObject = service.newObject( grid ); if ( row !== null ){ row.forEach( function( field, index ){ if ( headerMapping[index] !== null ){ newObject[ headerMapping[index] ] = field; } }); } newObject = grid.options.importerObjectCallback( grid, newObject ); newObjects.push( newObject ); }); return newObjects; }, /** * @ngdoc function * @name processHeaders * @methodOf ui.grid.importer.service:uiGridImporterService * @description Determines the columns that the header row from * a csv (or other) file represents. * @param {Grid} grid the grid we're importing into * @param {array} headerRow the header row that we wish to match against * the column definitions * @returns {array} an array of the attribute names that should be used * for that column, based on matching the headers or creating the headers * */ processHeaders: function( grid, headerRow ) { var headers = []; if ( !grid.options.columnDefs || grid.options.columnDefs.length === 0 ){ // we are going to create new columnDefs for all these columns, so just remove // spaces from the names to create fields headerRow.forEach( function( value, index ) { headers.push( value.replace( /[^0-9a-zA-Z\-_]/g, '_' ) ); }); return headers; } else { var lookupHash = service.flattenColumnDefs( grid, grid.options.columnDefs ); headerRow.forEach( function( value, index ) { if ( lookupHash[value] ) { headers.push( lookupHash[value] ); } else if ( lookupHash[ value.toLowerCase() ] ) { headers.push( lookupHash[ value.toLowerCase() ] ); } else { headers.push( null ); } }); return headers; } }, /** * @name flattenColumnDefs * @methodOf ui.grid.importer.service:uiGridImporterService * @description Runs through the column defs and creates a hash of * the displayName, name and field, and of each of those values forced to lower case, * with each pointing to the field or name * (whichever is present). Used to lookup column headers and decide what * attribute name to give to the resulting field. * @param {Grid} grid the grid we're importing into * @param {array} columnDefs the columnDefs that we should flatten * @returns {hash} the flattened version of the column def information, allowing * us to look up a value by `flattenedHash[ headerValue ]` */ flattenColumnDefs: function( grid, columnDefs ){ var flattenedHash = {}; columnDefs.forEach( function( columnDef, index) { if ( columnDef.name ){ flattenedHash[ columnDef.name ] = columnDef.field || columnDef.name; flattenedHash[ columnDef.name.toLowerCase() ] = columnDef.field || columnDef.name; } if ( columnDef.field ){ flattenedHash[ columnDef.field ] = columnDef.field || columnDef.name; flattenedHash[ columnDef.field.toLowerCase() ] = columnDef.field || columnDef.name; } if ( columnDef.displayName ){ flattenedHash[ columnDef.displayName ] = columnDef.field || columnDef.name; flattenedHash[ columnDef.displayName.toLowerCase() ] = columnDef.field || columnDef.name; } if ( columnDef.displayName && grid.options.importerHeaderFilter ){ flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName) ] = columnDef.field || columnDef.name; flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName).toLowerCase() ] = columnDef.field || columnDef.name; } }); return flattenedHash; }, /** * @ngdoc function * @name addObjects * @methodOf ui.grid.importer.service:uiGridImporterService * @description Inserts our new objects into the grid data, and * sets the rows to dirty if the rowEdit feature is being used * * Does this by registering a watch on dataChanges, which essentially * is waiting on the result of the grid data watch, and downstream processing. * * When the callback is called, it deregisters itself - we don't want to run * again next time data is added. * * If we never get called, we deregister on destroy. * * @param {Grid} grid the grid we're importing into * @param {array} newObjects the objects we want to insert into the grid data * @returns {object} the new object */ addObjects: function( grid, newObjects, $scope ){ if ( grid.api.rowEdit ){ var dataChangeDereg = grid.registerDataChangeCallback( function() { grid.api.rowEdit.setRowsDirty( newObjects ); dataChangeDereg(); }, [uiGridConstants.dataChange.ROW] ); grid.importer.$scope.$on( '$destroy', dataChangeDereg ); } grid.importer.$scope.$apply( grid.options.importerDataAddCallback( grid, newObjects ) ); }, /** * @ngdoc function * @name newObject * @methodOf ui.grid.importer.service:uiGridImporterService * @description Makes a new object based on `gridOptions.importerNewObject`, * or based on an empty object if not present * @param {Grid} grid the grid we're importing into * @returns {object} the new object */ newObject: function( grid ){ if ( typeof(grid.options) !== "undefined" && typeof(grid.options.importerNewObject) !== "undefined" ){ return new grid.options.importerNewObject(); } else { return {}; } }, /** * @ngdoc function * @name alertError * @methodOf ui.grid.importer.service:uiGridImporterService * @description Provides an internationalised user alert for the failure, * and logs a console message including diagnostic content. * Optionally, if the the `gridOptions.importerErrorCallback` routine * is defined, then calls that instead, allowing user specified error routines * @param {Grid} grid the grid we're importing into * @param {array} headerRow the header row that we wish to match against * the column definitions */ alertError: function( grid, alertI18nToken, consoleMessage, context ){ if ( grid.options.importerErrorCallback ){ grid.options.importerErrorCallback( grid, alertI18nToken, consoleMessage, context ); } else { $window.alert(i18nService.getSafeText( alertI18nToken )); gridUtil.logError(consoleMessage + context ); } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.importer.directive:uiGridImporter * @element div * @restrict A * * @description Adds importer features to grid * */ module.directive('uiGridImporter', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile', function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridImporterService.initializeGrid($scope, uiGridCtrl.grid); } }; } ]); /** * @ngdoc directive * @name ui.grid.importer.directive:uiGridImporterMenuItem * @element div * @restrict A * * @description Handles the processing from the importer menu item - once a file is * selected * */ module.directive('uiGridImporterMenuItem', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile', function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, templateUrl: 'ui-grid/importerMenuItem', link: function ($scope, $elm, $attrs, uiGridCtrl) { var handleFileSelect = function( event ){ var target = event.srcElement || event.target; if (target && target.files && target.files.length === 1) { var fileObject = target.files[0]; uiGridImporterService.importThisFile( grid, fileObject ); target.form.reset(); } }; var fileChooser = $elm[0].querySelectorAll('.ui-grid-importer-file-chooser'); var grid = uiGridCtrl.grid; if ( fileChooser.length !== 1 ){ gridUtil.logError('Found > 1 or < 1 file choosers within the menu item, error, cannot continue'); } else { fileChooser[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google } } }; } ]); })(); (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.infiniteScroll * * @description * * #ui.grid.infiniteScroll * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides infinite scroll functionality to ui-grid * */ var module = angular.module('ui.grid.infiniteScroll', ['ui.grid']); /** * @ngdoc service * @name ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * * @description Service for infinite scroll features */ module.service('uiGridInfiniteScrollService', ['gridUtil', '$compile', '$timeout', 'uiGridConstants', 'ScrollEvent', '$q', function (gridUtil, $compile, $timeout, uiGridConstants, ScrollEvent, $q) { var service = { /** * @ngdoc function * @name initializeGrid * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description This method register events and methods into grid public API */ initializeGrid: function(grid, $scope) { service.defaultGridOptions(grid.options); if (!grid.options.enableInfiniteScroll){ return; } grid.infiniteScroll = { dataLoading: false }; service.setScrollDirections( grid, grid.options.infiniteScrollUp, grid.options.infiniteScrollDown ); grid.api.core.on.scrollEnd($scope, service.handleScroll); /** * @ngdoc object * @name ui.grid.infiniteScroll.api:PublicAPI * * @description Public API for infinite scroll feature */ var publicApi = { events: { infiniteScroll: { /** * @ngdoc event * @name needLoadMoreData * @eventOf ui.grid.infiniteScroll.api:PublicAPI * @description This event fires when scroll reaches bottom percentage of grid * and needs to load data */ needLoadMoreData: function ($scope, fn) { }, /** * @ngdoc event * @name needLoadMoreDataTop * @eventOf ui.grid.infiniteScroll.api:PublicAPI * @description This event fires when scroll reaches top percentage of grid * and needs to load data */ needLoadMoreDataTop: function ($scope, fn) { } } }, methods: { infiniteScroll: { /** * @ngdoc function * @name dataLoaded * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Call this function when you have loaded the additional data * requested. You should set scrollUp and scrollDown to indicate * whether there are still more pages in each direction. * * If you call dataLoaded without first calling `saveScrollPercentage` then we will * scroll the user to the start of the newly loaded data, which usually gives a smooth scroll * experience, but can give a jumpy experience with large `infiniteScrollRowsFromEnd` values, and * on variable speed internet connections. Using `saveScrollPercentage` as demonstrated in the tutorial * should give a smoother scrolling experience for users. * * See infinite_scroll tutorial for example of usage * @param {boolean} scrollUp if set to false flags that there are no more pages upwards, so don't fire * any more infinite scroll events upward * @param {boolean} scrollDown if set to false flags that there are no more pages downwards, so don't * fire any more infinite scroll events downward * @returns {promise} a promise that is resolved when the grid scrolling is fully adjusted. If you're * planning to remove pages, you should wait on this promise first, or you'll break the scroll positioning */ dataLoaded: function( scrollUp, scrollDown ) { service.setScrollDirections(grid, scrollUp, scrollDown); var promise = service.adjustScroll(grid).then(function() { grid.infiniteScroll.dataLoading = false; }); return promise; }, /** * @ngdoc function * @name resetScroll * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Call this function when you have taken some action that makes the current * scroll position invalid. For example, if you're using external sorting and you've resorted * then you might reset the scroll, or if you've otherwise substantially changed the data, perhaps * you've reused an existing grid for a new data set * * You must tell us whether there is data upwards or downwards after the reset * * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward * @returns {promise} promise that is resolved when the scroll reset is complete */ resetScroll: function( scrollUp, scrollDown ) { service.setScrollDirections( grid, scrollUp, scrollDown); return service.adjustInfiniteScrollPosition(grid, 0); }, /** * @ngdoc function * @name saveScrollPercentage * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Saves the scroll percentage and number of visible rows before you adjust the data, * used if you're subsequently going to call `dataRemovedTop` or `dataRemovedBottom` */ saveScrollPercentage: function() { grid.infiniteScroll.prevScrolltopPercentage = grid.renderContainers.body.prevScrolltopPercentage; grid.infiniteScroll.previousVisibleRows = grid.renderContainers.body.visibleRowCache.length; }, /** * @ngdoc function * @name dataRemovedTop * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the top * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward */ dataRemovedTop: function( scrollUp, scrollDown ) { service.dataRemovedTop( grid, scrollUp, scrollDown ); }, /** * @ngdoc function * @name dataRemovedBottom * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the bottom * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward */ dataRemovedBottom: function( scrollUp, scrollDown ) { service.dataRemovedBottom( grid, scrollUp, scrollDown ); }, /** * @ngdoc function * @name setScrollDirections * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined, * and also sets the grid.suppressParentScroll * @param {boolean} scrollUp whether there are pages available up - defaults to false * @param {boolean} scrollDown whether there are pages available down - defaults to true */ setScrollDirections: function ( scrollUp, scrollDown ) { service.setScrollDirections( grid, scrollUp, scrollDown ); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.infiniteScroll.api:GridOptions * * @description GridOptions for infinite scroll feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableInfiniteScroll * @propertyOf ui.grid.infiniteScroll.api:GridOptions * @description Enable infinite scrolling for this grid * <br/>Defaults to true */ gridOptions.enableInfiniteScroll = gridOptions.enableInfiniteScroll !== false; /** * @ngdoc property * @name infiniteScrollRowsFromEnd * @propertyOf ui.grid.class:GridOptions * @description This setting controls how close to the end of the dataset a user gets before * more data is requested by the infinite scroll, whether scrolling up or down. This allows you to * 'prefetch' rows before the user actually runs out of scrolling. * * Note that if you set this value too high it may give jumpy scrolling behaviour, if you're getting * this behaviour you could use the `saveScrollPercentageMethod` right before loading your data, and we'll * preserve that scroll position * * <br> Defaults to 20 */ gridOptions.infiniteScrollRowsFromEnd = gridOptions.infiniteScrollRowsFromEnd || 20; /** * @ngdoc property * @name infiniteScrollUp * @propertyOf ui.grid.class:GridOptions * @description Whether you allow infinite scroll up, implying that the first page of data * you have displayed is in the middle of your data set. If set to true then we trigger the * needMoreDataTop event when the user hits the top of the scrollbar. * <br> Defaults to false */ gridOptions.infiniteScrollUp = gridOptions.infiniteScrollUp === true; /** * @ngdoc property * @name infiniteScrollDown * @propertyOf ui.grid.class:GridOptions * @description Whether you allow infinite scroll down, implying that the first page of data * you have displayed is in the middle of your data set. If set to true then we trigger the * needMoreData event when the user hits the bottom of the scrollbar. * <br> Defaults to true */ gridOptions.infiniteScrollDown = gridOptions.infiniteScrollDown !== false; }, /** * @ngdoc function * @name setScrollDirections * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined, * and also sets the grid.suppressParentScroll * @param {grid} grid the grid we're operating on * @param {boolean} scrollUp whether there are pages available up - defaults to false * @param {boolean} scrollDown whether there are pages available down - defaults to true */ setScrollDirections: function ( grid, scrollUp, scrollDown ) { grid.infiniteScroll.scrollUp = ( scrollUp === true ); grid.suppressParentScrollUp = ( scrollUp === true ); grid.infiniteScroll.scrollDown = ( scrollDown !== false); grid.suppressParentScrollDown = ( scrollDown !== false); }, /** * @ngdoc function * @name handleScroll * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Called whenever the grid scrolls, determines whether the scroll should * trigger an infinite scroll request for more data * @param {object} args the args from the event */ handleScroll: function (args) { // don't request data if already waiting for data, or if source is coming from ui.grid.adjustInfiniteScrollPosition() function if ( args.grid.infiniteScroll && args.grid.infiniteScroll.dataLoading || args.source === 'ui.grid.adjustInfiniteScrollPosition' ){ return; } if (args.y) { var percentage; var targetPercentage = args.grid.options.infiniteScrollRowsFromEnd / args.grid.renderContainers.body.visibleRowCache.length; if (args.grid.scrollDirection === uiGridConstants.scrollDirection.UP ) { percentage = args.y.percentage; if (percentage <= targetPercentage){ service.loadData(args.grid); } } else if (args.grid.scrollDirection === uiGridConstants.scrollDirection.DOWN) { percentage = 1 - args.y.percentage; if (percentage <= targetPercentage){ service.loadData(args.grid); } } } }, /** * @ngdoc function * @name loadData * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection * and whether there are more pages upwards or downwards. It also stores the number of rows that we had previously, * and clears out any saved scroll position so that we know whether or not the user calls `saveScrollPercentage` * @param {Grid} grid the grid we're working on */ loadData: function (grid) { // save number of currently visible rows to calculate new scroll position later - we know that we want // to be at approximately the row we're currently at grid.infiniteScroll.previousVisibleRows = grid.renderContainers.body.visibleRowCache.length; grid.infiniteScroll.direction = grid.scrollDirection; delete grid.infiniteScroll.prevScrolltopPercentage; if (grid.scrollDirection === uiGridConstants.scrollDirection.UP && grid.infiniteScroll.scrollUp ) { grid.infiniteScroll.dataLoading = true; grid.api.infiniteScroll.raise.needLoadMoreDataTop(); } else if (grid.scrollDirection === uiGridConstants.scrollDirection.DOWN && grid.infiniteScroll.scrollDown ) { grid.infiniteScroll.dataLoading = true; grid.api.infiniteScroll.raise.needLoadMoreData(); } }, /** * @ngdoc function * @name adjustScroll * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description Once we are informed that data has been loaded, adjust the scroll position to account for that * addition and to make things look clean. * * If we're scrolling up we scroll to the first row of the old data set - * so we're assuming that you would have gotten to the top of the grid (from the 20% need more data trigger) by * the time the data comes back. If we're scrolling down we scoll to the last row of the old data set - so we're * assuming that you would have gotten to the bottom of the grid (from the 80% need more data trigger) by the time * the data comes back. * * Neither of these are good assumptions, but making this a smoother experience really requires * that trigger to not be a percentage, and to be much closer to the end of the data (say, 5 rows off the end). Even then * it'd be better still to actually run into the end. But if the data takes a while to come back, they may have scrolled * somewhere else in the mean-time, in which case they'll get a jump back to the new data. Anyway, this will do for * now, until someone wants to do better. * @param {Grid} grid the grid we're working on * @returns {promise} a promise that is resolved when scrolling has finished */ adjustScroll: function(grid){ var promise = $q.defer(); $timeout(function () { var newPercentage; if ( grid.infiniteScroll.direction === undefined ){ // called from initialize, tweak our scroll up a little service.adjustInfiniteScrollPosition(grid, 0); } var newVisibleRows = grid.renderContainers.body.visibleRowCache.length; var oldPercentage, oldTopRow; var halfViewport = grid.getViewportHeight() / grid.options.rowHeight / 2; if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.UP ){ oldPercentage = grid.infiniteScroll.prevScrolltopPercentage || 0; oldTopRow = oldPercentage * grid.infiniteScroll.previousVisibleRows; newPercentage = ( newVisibleRows - grid.infiniteScroll.previousVisibleRows + oldTopRow + halfViewport ) / newVisibleRows; service.adjustInfiniteScrollPosition(grid, newPercentage); $timeout( function() { promise.resolve(); }); } if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.DOWN ){ oldPercentage = grid.infiniteScroll.prevScrolltopPercentage || 1; oldTopRow = oldPercentage * grid.infiniteScroll.previousVisibleRows; newPercentage = ( oldTopRow - halfViewport ) / newVisibleRows; service.adjustInfiniteScrollPosition(grid, newPercentage); $timeout( function() { promise.resolve(); }); } }, 0); return promise.promise; }, /** * @ngdoc function * @name adjustInfiniteScrollPosition * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection * @param {Grid} grid the grid we're working on * @param {number} percentage the percentage through the grid that we want to scroll to * @returns {promise} a promise that is resolved when the scrolling finishes */ adjustInfiniteScrollPosition: function (grid, percentage) { var scrollEvent = new ScrollEvent(grid, null, null, 'ui.grid.adjustInfiniteScrollPosition'); //for infinite scroll, if there are pages upwards then never allow it to be at the zero position so the up button can be active if ( percentage === 0 && grid.infiniteScroll.scrollUp ) { scrollEvent.y = {pixels: 1}; } else { scrollEvent.y = {percentage: percentage}; } grid.scrollContainers('', scrollEvent); }, /** * @ngdoc function * @name dataRemovedTop * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the top. You should * have called `saveScrollPercentage` before you remove the data, and if you're doing this in * response to a `needMoreData` you should wait until the promise from `loadData` has resolved * before you start removing data * @param {Grid} grid the grid we're working on * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward * @returns {promise} a promise that is resolved when the scrolling finishes */ dataRemovedTop: function( grid, scrollUp, scrollDown ) { service.setScrollDirections( grid, scrollUp, scrollDown ); var newVisibleRows = grid.renderContainers.body.visibleRowCache.length; var oldScrollRow = grid.infiniteScroll.prevScrolltopPercentage * grid.infiniteScroll.previousVisibleRows; // since we removed from the top, our new scroll row will be the old scroll row less the number // of rows removed var newScrollRow = oldScrollRow - ( grid.infiniteScroll.previousVisibleRows - newVisibleRows ); var newScrollPercent = newScrollRow / newVisibleRows; return service.adjustInfiniteScrollPosition( grid, newScrollPercent ); }, /** * @ngdoc function * @name dataRemovedBottom * @methodOf ui.grid.infiniteScroll.api:PublicAPI * @description Adjusts the scroll position after you've removed data at the bottom. You should * have called `saveScrollPercentage` before you remove the data, and if you're doing this in * response to a `needMoreData` you should wait until the promise from `loadData` has resolved * before you start removing data * @param {Grid} grid the grid we're working on * @param {boolean} scrollUp flag that there are pages upwards, fire * infinite scroll events upward * @param {boolean} scrollDown flag that there are pages downwards, so * fire infinite scroll events downward */ dataRemovedBottom: function( grid, scrollUp, scrollDown ) { service.setScrollDirections( grid, scrollUp, scrollDown ); var newVisibleRows = grid.renderContainers.body.visibleRowCache.length; var oldScrollRow = grid.infiniteScroll.prevScrolltopPercentage * grid.infiniteScroll.previousVisibleRows; // since we removed from the bottom, our new scroll row will be same as the old scroll row var newScrollPercent = oldScrollRow / newVisibleRows; return service.adjustInfiniteScrollPosition( grid, newScrollPercent ); } }; return service; }]); /** * @ngdoc directive * @name ui.grid.infiniteScroll.directive:uiGridInfiniteScroll * @element div * @restrict A * * @description Adds infinite scroll features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.infiniteScroll']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Alex', car: 'Toyota' }, { name: 'Sam', car: 'Lexus' } ]; $scope.columnDefs = [ {name: 'name'}, {name: 'car'} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-infinite-scroll="20"></div> </div> </file> </example> */ module.directive('uiGridInfiniteScroll', ['uiGridInfiniteScrollService', function (uiGridInfiniteScrollService) { return { priority: -200, scope: false, require: '^uiGrid', compile: function($scope, $elm, $attr){ return { pre: function($scope, $elm, $attr, uiGridCtrl) { uiGridInfiniteScrollService.initializeGrid(uiGridCtrl.grid, $scope); }, post: function($scope, $elm, $attr) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.moveColumns * @description * * # ui.grid.moveColumns * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides column moving capability to ui.grid. It enables to change the position of columns. * <div doc-module-components="ui.grid.moveColumns"></div> */ var module = angular.module('ui.grid.moveColumns', ['ui.grid']); /** * @ngdoc service * @name ui.grid.moveColumns.service:uiGridMoveColumnService * @description Service for column moving feature. */ module.service('uiGridMoveColumnService', ['$q', '$timeout', '$log', 'ScrollEvent', 'uiGridConstants', 'gridUtil', function ($q, $timeout, $log, ScrollEvent, uiGridConstants, gridUtil) { var service = { initializeGrid: function (grid) { var self = this; this.registerPublicApi(grid); this.defaultGridOptions(grid.options); grid.registerColumnBuilder(self.movableColumnBuilder); }, registerPublicApi: function (grid) { var self = this; /** * @ngdoc object * @name ui.grid.moveColumns.api:PublicApi * @description Public Api for column moving feature. */ var publicApi = { events: { /** * @ngdoc event * @name columnPositionChanged * @eventOf ui.grid.moveColumns.api:PublicApi * @description raised when column is moved * <pre> * gridApi.colMovable.on.columnPositionChanged(scope,function(colDef, originalPosition, newPosition){}) * </pre> * @param {object} colDef the column that was moved * @param {integer} originalPosition of the column * @param {integer} finalPosition of the column */ colMovable: { columnPositionChanged: function (colDef, originalPosition, newPosition) { } } }, methods: { /** * @ngdoc method * @name moveColumn * @methodOf ui.grid.moveColumns.api:PublicApi * @description Method can be used to change column position. * <pre> * gridApi.colMovable.moveColumn(oldPosition, newPosition) * </pre> * @param {integer} originalPosition of the column * @param {integer} finalPosition of the column */ colMovable: { moveColumn: function (originalPosition, finalPosition) { var columns = grid.columns; if (!angular.isNumber(originalPosition) || !angular.isNumber(finalPosition)) { gridUtil.logError('MoveColumn: Please provide valid values for originalPosition and finalPosition'); return; } var nonMovableColumns = 0; for (var i = 0; i < columns.length; i++) { if ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true) { nonMovableColumns++; } } if (originalPosition >= (columns.length - nonMovableColumns) || finalPosition >= (columns.length - nonMovableColumns)) { gridUtil.logError('MoveColumn: Invalid values for originalPosition, finalPosition'); return; } var findPositionForRenderIndex = function (index) { var position = index; for (var i = 0; i <= position; i++) { if (angular.isDefined(columns[i]) && ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true)) { position++; } } return position; }; self.redrawColumnAtPosition(grid, findPositionForRenderIndex(originalPosition), findPositionForRenderIndex(finalPosition)); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.moveColumns.api:GridOptions * * @description Options for configuring the move column feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableColumnMoving * @propertyOf ui.grid.moveColumns.api:GridOptions * @description If defined, sets the default value for the colMovable flag on each individual colDefs * if their individual enableColumnMoving configuration is not defined. Defaults to true. */ gridOptions.enableColumnMoving = gridOptions.enableColumnMoving !== false; }, movableColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.moveColumns.api:ColumnDef * * @description Column Definition for move column feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableColumnMoving * @propertyOf ui.grid.moveColumns.api:ColumnDef * @description Enable column moving for the column. */ colDef.enableColumnMoving = colDef.enableColumnMoving === undefined ? gridOptions.enableColumnMoving : colDef.enableColumnMoving; return $q.all(promises); }, redrawColumnAtPosition: function (grid, originalPosition, newPosition) { var columns = grid.columns; var originalColumn = columns[originalPosition]; if (originalColumn.colDef.enableColumnMoving) { if (originalPosition > newPosition) { for (var i1 = originalPosition; i1 > newPosition; i1--) { columns[i1] = columns[i1 - 1]; } } else if (newPosition > originalPosition) { for (var i2 = originalPosition; i2 < newPosition; i2++) { columns[i2] = columns[i2 + 1]; } } columns[newPosition] = originalColumn; grid.queueGridRefresh(); $timeout(function () { grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN ); grid.api.colMovable.raise.columnPositionChanged(originalColumn.colDef, originalPosition, newPosition); }); } } }; return service; }]); /** * @ngdoc directive * @name ui.grid.moveColumns.directive:uiGridMoveColumns * @element div * @restrict A * @description Adds column moving features to the ui-grid directive. * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.moveColumns']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO', age: 45 }, { name: 'Frank', title: 'Lowly Developer', age: 25 }, { name: 'Jenny', title: 'Highly Developer', age: 35 } ]; $scope.columnDefs = [ {name: 'name'}, {name: 'title'}, {name: 'age'} ]; }]); </file> <file name="main.css"> .grid { width: 100%; height: 150px; } </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div class="grid" ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-move-columns></div> </div> </file> </example> */ module.directive('uiGridMoveColumns', ['uiGridMoveColumnService', function (uiGridMoveColumnService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridMoveColumnService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.moveColumns.directive:uiGridHeaderCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridHeaderCell to provide capability to be able to move it to reposition column. * * On receiving mouseDown event headerCell is cloned, now as the mouse moves the cloned header cell also moved in the grid. * In case the moving cloned header cell reaches the left or right extreme of grid, grid scrolling is triggered (if horizontal scroll exists). * On mouseUp event column is repositioned at position where mouse is released and cloned header cell is removed. * * Events that invoke cloning of header cell: * - mousedown * * Events that invoke movement of cloned header cell: * - mousemove * * Events that invoke repositioning of column: * - mouseup */ module.directive('uiGridHeaderCell', ['$q', 'gridUtil', 'uiGridMoveColumnService', '$document', '$log', 'uiGridConstants', 'ScrollEvent', function ($q, gridUtil, uiGridMoveColumnService, $document, $log, uiGridConstants, ScrollEvent) { return { priority: -10, require: '^uiGrid', compile: function () { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { if ($scope.col.colDef.enableColumnMoving) { /* * Our general approach to column move is that we listen to a touchstart or mousedown * event over the column header. When we hear one, then we wait for a move of the same type * - if we are a touchstart then we listen for a touchmove, if we are a mousedown we listen for * a mousemove (i.e. a drag) before we decide that there's a move underway. If there's never a move, * and we instead get a mouseup or a touchend, then we just drop out again and do nothing. * */ var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') ); var gridLeft; var previousMouseX; var totalMouseMovement; var rightMoveLimit; var elmCloned = false; var movingElm; var reducedWidth; var moveOccurred = false; var downFn = function( event ){ //Setting some variables required for calculations. gridLeft = $scope.grid.element[0].getBoundingClientRect().left; if ( $scope.grid.hasLeftContainer() ){ gridLeft += $scope.grid.renderContainers.left.header[0].getBoundingClientRect().width; } previousMouseX = event.pageX; totalMouseMovement = 0; rightMoveLimit = gridLeft + $scope.grid.getViewportWidth(); if ( event.type === 'mousedown' ){ $document.on('mousemove', moveFn); $document.on('mouseup', upFn); } else if ( event.type === 'touchstart' ){ $document.on('touchmove', moveFn); $document.on('touchend', upFn); } }; var moveFn = function( event ) { var changeValue = event.pageX - previousMouseX; if ( changeValue === 0 ){ return; } //Disable text selection in Chrome during column move document.onselectstart = function() { return false; }; moveOccurred = true; if (!elmCloned) { cloneElement(); } else if (elmCloned) { moveElement(changeValue); previousMouseX = event.pageX; } }; var upFn = function( event ){ //Re-enable text selection after column move document.onselectstart = null; //Remove the cloned element on mouse up. if (movingElm) { movingElm.remove(); elmCloned = false; } offAllEvents(); onDownEvents(); if (!moveOccurred){ return; } var columns = $scope.grid.columns; var columnIndex = 0; for (var i = 0; i < columns.length; i++) { if (columns[i].colDef.name !== $scope.col.colDef.name) { columnIndex++; } else { break; } } //Case where column should be moved to a position on its left if (totalMouseMovement < 0) { var totalColumnsLeftWidth = 0; for (var il = columnIndex - 1; il >= 0; il--) { if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) { totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width; if (totalColumnsLeftWidth > Math.abs(totalMouseMovement)) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, il + 1); break; } } } //Case where column should be moved to beginning of the grid. if (totalColumnsLeftWidth < Math.abs(totalMouseMovement)) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, 0); } } //Case where column should be moved to a position on its right else if (totalMouseMovement > 0) { var totalColumnsRightWidth = 0; for (var ir = columnIndex + 1; ir < columns.length; ir++) { if (angular.isUndefined(columns[ir].colDef.visible) || columns[ir].colDef.visible === true) { totalColumnsRightWidth += columns[ir].drawnWidth || columns[ir].width || columns[ir].colDef.width; if (totalColumnsRightWidth > totalMouseMovement) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, ir - 1); break; } } } //Case where column should be moved to end of the grid. if (totalColumnsRightWidth < totalMouseMovement) { uiGridMoveColumnService.redrawColumnAtPosition ($scope.grid, columnIndex, columns.length - 1); } } }; var onDownEvents = function(){ $contentsElm.on('touchstart', downFn); $contentsElm.on('mousedown', downFn); }; var offAllEvents = function() { $contentsElm.off('touchstart', downFn); $contentsElm.off('mousedown', downFn); $document.off('mousemove', moveFn); $document.off('touchmove', moveFn); $document.off('mouseup', upFn); $document.off('touchend', upFn); }; onDownEvents(); var cloneElement = function () { elmCloned = true; //Cloning header cell and appending to current header cell. movingElm = $elm.clone(); $elm.parent().append(movingElm); //Left of cloned element should be aligned to original header cell. movingElm.addClass('movingColumn'); var movingElementStyles = {}; var elmLeft; if (gridUtil.detectBrowser() === 'safari') { //Correction for Safari getBoundingClientRect, //which does not correctly compute when there is an horizontal scroll elmLeft = $elm[0].offsetLeft + $elm[0].offsetWidth - $elm[0].getBoundingClientRect().width; } else { elmLeft = $elm[0].getBoundingClientRect().left; } movingElementStyles.left = (elmLeft - gridLeft) + 'px'; var gridRight = $scope.grid.element[0].getBoundingClientRect().right; var elmRight = $elm[0].getBoundingClientRect().right; if (elmRight > gridRight) { reducedWidth = $scope.col.drawnWidth + (gridRight - elmRight); movingElementStyles.width = reducedWidth + 'px'; } movingElm.css(movingElementStyles); }; var moveElement = function (changeValue) { //Calculate total column width var columns = $scope.grid.columns; var totalColumnWidth = 0; for (var i = 0; i < columns.length; i++) { if (angular.isUndefined(columns[i].colDef.visible) || columns[i].colDef.visible === true) { totalColumnWidth += columns[i].drawnWidth || columns[i].width || columns[i].colDef.width; } } //Calculate new position of left of column var currentElmLeft = movingElm[0].getBoundingClientRect().left - 1; var currentElmRight = movingElm[0].getBoundingClientRect().right; var newElementLeft; newElementLeft = currentElmLeft - gridLeft + changeValue; newElementLeft = newElementLeft < rightMoveLimit ? newElementLeft : rightMoveLimit; //Update css of moving column to adjust to new left value or fire scroll in case column has reached edge of grid if ((currentElmLeft >= gridLeft || changeValue > 0) && (currentElmRight <= rightMoveLimit || changeValue < 0)) { movingElm.css({visibility: 'visible', 'left': newElementLeft + 'px'}); } else if (totalColumnWidth > Math.ceil(uiGridCtrl.grid.gridWidth)) { changeValue *= 8; var scrollEvent = new ScrollEvent($scope.col.grid, null, null, 'uiGridHeaderCell.moveElement'); scrollEvent.x = {pixels: changeValue}; scrollEvent.grid.scrollContainers('',scrollEvent); } //Calculate total width of columns on the left of the moving column and the mouse movement var totalColumnsLeftWidth = 0; for (var il = 0; il < columns.length; il++) { if (angular.isUndefined(columns[il].colDef.visible) || columns[il].colDef.visible === true) { if (columns[il].colDef.name !== $scope.col.colDef.name) { totalColumnsLeftWidth += columns[il].drawnWidth || columns[il].width || columns[il].colDef.width; } else { break; } } } if ($scope.newScrollLeft === undefined) { totalMouseMovement += changeValue; } else { totalMouseMovement = $scope.newScrollLeft + newElementLeft - totalColumnsLeftWidth; } //Increase width of moving column, in case the rightmost column was moved and its width was //decreased because of overflow if (reducedWidth < $scope.col.drawnWidth) { reducedWidth += Math.abs(changeValue); movingElm.css({'width': reducedWidth + 'px'}); } }; } } }; } }; }]); })(); (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.pagination * * @description * * # ui.grid.pagination * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides pagination support to ui-grid */ var module = angular.module('ui.grid.pagination', ['ng', 'ui.grid']); /** * @ngdoc service * @name ui.grid.pagination.service:uiGridPaginationService * * @description Service for the pagination feature */ module.service('uiGridPaginationService', ['gridUtil', function (gridUtil) { var service = { /** * @ngdoc method * @name initializeGrid * @methodOf ui.grid.pagination.service:uiGridPaginationService * @description Attaches the service to a certain grid * @param {Grid} grid The grid we want to work with */ initializeGrid: function (grid) { service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.pagination.api:PublicAPI * * @description Public API for the pagination feature */ var publicApi = { events: { pagination: { /** * @ngdoc event * @name paginationChanged * @eventOf ui.grid.pagination.api:PublicAPI * @description This event fires when the pageSize or currentPage changes * @param {int} currentPage requested page number * @param {int} pageSize requested page size */ paginationChanged: function (currentPage, pageSize) { } } }, methods: { pagination: { /** * @ngdoc method * @name getPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the number of the current page */ getPage: function () { return grid.options.enablePagination ? grid.options.paginationCurrentPage : null; }, /** * @ngdoc method * @name getTotalPages * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the total number of pages */ getTotalPages: function () { if (!grid.options.enablePagination) { return null; } return (grid.options.totalItems === 0) ? 1 : Math.ceil(grid.options.totalItems / grid.options.paginationPageSize); }, /** * @ngdoc method * @name nextPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the next page, if possible */ nextPage: function () { if (!grid.options.enablePagination) { return; } if (grid.options.totalItems > 0) { grid.options.paginationCurrentPage = Math.min( grid.options.paginationCurrentPage + 1, publicApi.methods.pagination.getTotalPages() ); } else { grid.options.paginationCurrentPage++; } }, /** * @ngdoc method * @name previousPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the previous page, if we're not on the first page */ previousPage: function () { if (!grid.options.enablePagination) { return; } grid.options.paginationCurrentPage = Math.max(grid.options.paginationCurrentPage - 1, 1); }, /** * @ngdoc method * @name seek * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the requested page * @param {int} page The number of the page that should be displayed */ seek: function (page) { if (!grid.options.enablePagination) { return; } if (!angular.isNumber(page) || page < 1) { throw 'Invalid page number: ' + page; } grid.options.paginationCurrentPage = Math.min(page, publicApi.methods.pagination.getTotalPages()); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); var processPagination = function( renderableRows ){ if (grid.options.useExternalPagination || !grid.options.enablePagination) { return renderableRows; } //client side pagination var pageSize = parseInt(grid.options.paginationPageSize, 10); var currentPage = parseInt(grid.options.paginationCurrentPage, 10); var visibleRows = renderableRows.filter(function (row) { return row.visible; }); grid.options.totalItems = visibleRows.length; var firstRow = (currentPage - 1) * pageSize; if (firstRow > visibleRows.length) { currentPage = grid.options.paginationCurrentPage = 1; firstRow = (currentPage - 1) * pageSize; } return visibleRows.slice(firstRow, firstRow + pageSize); }; grid.registerRowsProcessor(processPagination, 900 ); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.pagination.api:GridOptions * * @description GridOptions for the pagination feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc property * @name enablePagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Enables pagination, defaults to true */ gridOptions.enablePagination = gridOptions.enablePagination !== false; /** * @ngdoc property * @name enablePaginationControls * @propertyOf ui.grid.pagination.api:GridOptions * @description Enables the paginator at the bottom of the grid. Turn this off, if you want to implement your * own controls outside the grid. */ gridOptions.enablePaginationControls = gridOptions.enablePaginationControls !== false; /** * @ngdoc property * @name useExternalPagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Disables client side pagination. When true, handle the paginationChanged event and set data * and totalItems, defaults to `false` */ gridOptions.useExternalPagination = gridOptions.useExternalPagination === true; /** * @ngdoc property * @name totalItems * @propertyOf ui.grid.pagination.api:GridOptions * @description Total number of items, set automatically when client side pagination, needs set by user * for server side pagination */ if (gridUtil.isNullOrUndefined(gridOptions.totalItems)) { gridOptions.totalItems = 0; } /** * @ngdoc property * @name paginationPageSizes * @propertyOf ui.grid.pagination.api:GridOptions * @description Array of page sizes, defaults to `[250, 500, 1000]` */ if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSizes)) { gridOptions.paginationPageSizes = [250, 500, 1000]; } /** * @ngdoc property * @name paginationPageSize * @propertyOf ui.grid.pagination.api:GridOptions * @description Page size, defaults to the first item in paginationPageSizes, or 0 if paginationPageSizes is empty */ if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSize)) { if (gridOptions.paginationPageSizes.length > 0) { gridOptions.paginationPageSize = gridOptions.paginationPageSizes[0]; } else { gridOptions.paginationPageSize = 0; } } /** * @ngdoc property * @name paginationCurrentPage * @propertyOf ui.grid.pagination.api:GridOptions * @description Current page number, defaults to 1 */ if (gridUtil.isNullOrUndefined(gridOptions.paginationCurrentPage)) { gridOptions.paginationCurrentPage = 1; } /** * @ngdoc property * @name paginationTemplate * @propertyOf ui.grid.pagination.api:GridOptions * @description A custom template for the pager, defaults to `ui-grid/pagination` */ if (gridUtil.isNullOrUndefined(gridOptions.paginationTemplate)) { gridOptions.paginationTemplate = 'ui-grid/pagination'; } }, /** * @ngdoc method * @methodOf ui.grid.pagination.service:uiGridPaginationService * @name uiGridPaginationService * @description Raises paginationChanged and calls refresh for client side pagination * @param {Grid} grid the grid for which the pagination changed * @param {int} currentPage requested page number * @param {int} pageSize requested page size */ onPaginationChanged: function (grid, currentPage, pageSize) { grid.api.pagination.raise.paginationChanged(currentPage, pageSize); if (!grid.options.useExternalPagination) { grid.queueGridRefresh(); //client side pagination } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.pagination.directive:uiGridPagination * @element div * @restrict A * * @description Adds pagination features to grid * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.pagination']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Alex', car: 'Toyota' }, { name: 'Sam', car: 'Lexus' }, { name: 'Joe', car: 'Dodge' }, { name: 'Bob', car: 'Buick' }, { name: 'Cindy', car: 'Ford' }, { name: 'Brian', car: 'Audi' }, { name: 'Malcom', car: 'Mercedes Benz' }, { name: 'Dave', car: 'Ford' }, { name: 'Stacey', car: 'Audi' }, { name: 'Amy', car: 'Acura' }, { name: 'Scott', car: 'Toyota' }, { name: 'Ryan', car: 'BMW' }, ]; $scope.gridOptions = { data: 'data', paginationPageSizes: [5, 10, 25], paginationPageSize: 5, columnDefs: [ {name: 'name'}, {name: 'car'} ] } }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-pagination></div> </div> </file> </example> */ module.directive('uiGridPagination', ['gridUtil', 'uiGridPaginationService', function (gridUtil, uiGridPaginationService) { return { priority: -200, scope: false, require: 'uiGrid', link: { pre: function ($scope, $elm, $attr, uiGridCtrl) { uiGridPaginationService.initializeGrid(uiGridCtrl.grid); gridUtil.getTemplate(uiGridCtrl.grid.options.paginationTemplate) .then(function (contents) { var template = angular.element(contents); $elm.append(template); uiGridCtrl.innerCompile(template); }); } } }; } ]); /** * @ngdoc directive * @name ui.grid.pagination.directive:uiGridPager * @element div * * @description Panel for handling pagination */ module.directive('uiGridPager', ['uiGridPaginationService', 'uiGridConstants', 'gridUtil', 'i18nService', function (uiGridPaginationService, uiGridConstants, gridUtil, i18nService) { return { priority: -200, scope: true, require: '^uiGrid', link: function ($scope, $elm, $attr, uiGridCtrl) { $scope.paginationApi = uiGridCtrl.grid.api.pagination; $scope.sizesLabel = i18nService.getSafeText('pagination.sizes'); $scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems'); $scope.paginationOf = i18nService.getSafeText('pagination.of'); var options = uiGridCtrl.grid.options; uiGridCtrl.grid.renderContainers.body.registerViewportAdjuster(function (adjustment) { adjustment.height = adjustment.height - gridUtil.elementHeight($elm); return adjustment; }); var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback(function (grid) { if (!grid.options.useExternalPagination) { grid.options.totalItems = grid.rows.length; } }, [uiGridConstants.dataChange.ROW]); $scope.$on('$destroy', dataChangeDereg); var setShowing = function () { $scope.showingLow = ((options.paginationCurrentPage - 1) * options.paginationPageSize) + 1; $scope.showingHigh = Math.min(options.paginationCurrentPage * options.paginationPageSize, options.totalItems); }; var deregT = $scope.$watch('grid.options.totalItems + grid.options.paginationPageSize', setShowing); var deregP = $scope.$watch('grid.options.paginationCurrentPage + grid.options.paginationPageSize', function (newValues, oldValues) { if (newValues === oldValues) { return; } if (!angular.isNumber(options.paginationCurrentPage) || options.paginationCurrentPage < 1) { options.paginationCurrentPage = 1; return; } if (options.totalItems > 0 && options.paginationCurrentPage > $scope.paginationApi.getTotalPages()) { options.paginationCurrentPage = $scope.paginationApi.getTotalPages(); return; } setShowing(); uiGridPaginationService.onPaginationChanged($scope.grid, options.paginationCurrentPage, options.paginationPageSize); } ); $scope.$on('$destroy', function() { deregT(); deregP(); }); $scope.cantPageForward = function () { if (options.totalItems > 0) { return options.paginationCurrentPage >= $scope.paginationApi.getTotalPages(); } else { return options.data.length < 1; } }; $scope.cantPageToLast = function () { if (options.totalItems > 0) { return $scope.cantPageForward(); } else { return true; } }; $scope.cantPageBackward = function () { return options.paginationCurrentPage <= 1; }; } }; } ]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.pinning * @description * * # ui.grid.pinning * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides column pinning to the end user via menu options in the column header * * <div doc-module-components="ui.grid.pinning"></div> */ var module = angular.module('ui.grid.pinning', ['ui.grid']); module.constant('uiGridPinningConstants', { container: { LEFT: 'left', RIGHT: 'right', NONE: '' } }); module.service('uiGridPinningService', ['gridUtil', 'GridRenderContainer', 'i18nService', 'uiGridPinningConstants', function (gridUtil, GridRenderContainer, i18nService, uiGridPinningConstants) { var service = { initializeGrid: function (grid) { service.defaultGridOptions(grid.options); // Register a column builder to add new menu items for pinning left and right grid.registerColumnBuilder(service.pinningColumnBuilder); /** * @ngdoc object * @name ui.grid.pinning.api:PublicApi * * @description Public Api for pinning feature */ var publicApi = { events: { pinning: { /** * @ngdoc event * @name columnPin * @eventOf ui.grid.pinning.api:PublicApi * @description raised when column pin state has changed * <pre> * gridApi.pinning.on.columnPinned(scope, function(colDef){}) * </pre> * @param {object} colDef the column that was changed * @param {string} container the render container the column is in ('left', 'right', '') */ columnPinned: function(colDef, container) { } } }, methods: { pinning: { /** * @ngdoc function * @name pinColumn * @methodOf ui.grid.pinning.api:PublicApi * @description pin column left, right, or none * <pre> * gridApi.pinning.pinColumn(col, uiGridPinningConstants.container.LEFT) * </pre> * @param {gridColumn} col the column being pinned * @param {string} container one of the recognised types * from uiGridPinningConstants */ pinColumn: function(col, container) { service.pinColumn(grid, col, container); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.pinning.api:GridOptions * * @description GridOptions for pinning feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enablePinning * @propertyOf ui.grid.pinning.api:GridOptions * @description Enable pinning for the entire grid. * <br/>Defaults to true */ gridOptions.enablePinning = gridOptions.enablePinning !== false; }, pinningColumnBuilder: function (colDef, col, gridOptions) { //default to true unless gridOptions or colDef is explicitly false /** * @ngdoc object * @name ui.grid.pinning.api:ColumnDef * * @description ColumnDef for pinning feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enablePinning * @propertyOf ui.grid.pinning.api:ColumnDef * @description Enable pinning for the individual column. * <br/>Defaults to true */ colDef.enablePinning = colDef.enablePinning === undefined ? gridOptions.enablePinning : colDef.enablePinning; /** * @ngdoc object * @name pinnedLeft * @propertyOf ui.grid.pinning.api:ColumnDef * @description Column is pinned left when grid is rendered * <br/>Defaults to false */ /** * @ngdoc object * @name pinnedRight * @propertyOf ui.grid.pinning.api:ColumnDef * @description Column is pinned right when grid is rendered * <br/>Defaults to false */ if (colDef.pinnedLeft) { col.renderContainer = 'left'; col.grid.createLeftContainer(); } else if (colDef.pinnedRight) { col.renderContainer = 'right'; col.grid.createRightContainer(); } if (!colDef.enablePinning) { return; } var pinColumnLeftAction = { name: 'ui.grid.pinning.pinLeft', title: i18nService.get().pinning.pinLeft, icon: 'ui-grid-icon-left-open', shown: function () { return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'left'; }, action: function () { service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.LEFT); } }; var pinColumnRightAction = { name: 'ui.grid.pinning.pinRight', title: i18nService.get().pinning.pinRight, icon: 'ui-grid-icon-right-open', shown: function () { return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'right'; }, action: function () { service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.RIGHT); } }; var removePinAction = { name: 'ui.grid.pinning.unpin', title: i18nService.get().pinning.unpin, icon: 'ui-grid-icon-cancel', shown: function () { return typeof(this.context.col.renderContainer) !== 'undefined' && this.context.col.renderContainer !== null && this.context.col.renderContainer !== 'body'; }, action: function () { service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.UNPIN); } }; if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinLeft')) { col.menuItems.push(pinColumnLeftAction); } if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinRight')) { col.menuItems.push(pinColumnRightAction); } if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.unpin')) { col.menuItems.push(removePinAction); } }, pinColumn: function(grid, col, container) { if (container === uiGridPinningConstants.container.NONE) { col.renderContainer = null; } else { col.renderContainer = container; if (container === uiGridPinningConstants.container.LEFT) { grid.createLeftContainer(); } else if (container === uiGridPinningConstants.container.RIGHT) { grid.createRightContainer(); } } grid.refresh() .then(function() { grid.api.pinning.raise.columnPinned( col.colDef, container ); }); } }; return service; }]); module.directive('uiGridPinning', ['gridUtil', 'uiGridPinningService', function (gridUtil, uiGridPinningService) { return { require: 'uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridPinningService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); })(); (function(){ 'use strict'; /** * @ngdoc overview * @name ui.grid.resizeColumns * @description * * # ui.grid.resizeColumns * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module allows columns to be resized. */ var module = angular.module('ui.grid.resizeColumns', ['ui.grid']); module.service('uiGridResizeColumnsService', ['gridUtil', '$q', '$timeout', function (gridUtil, $q, $timeout) { var service = { defaultGridOptions: function(gridOptions){ //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.resizeColumns.api:GridOptions * * @description GridOptions for resizeColumns feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableColumnResizing * @propertyOf ui.grid.resizeColumns.api:GridOptions * @description Enable column resizing on the entire grid * <br/>Defaults to true */ gridOptions.enableColumnResizing = gridOptions.enableColumnResizing !== false; //legacy support //use old name if it is explicitly false if (gridOptions.enableColumnResize === false){ gridOptions.enableColumnResizing = false; } }, colResizerColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.resizeColumns.api:ColumnDef * * @description ColumnDef for resizeColumns feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableColumnResizing * @propertyOf ui.grid.resizeColumns.api:ColumnDef * @description Enable column resizing on an individual column * <br/>Defaults to GridOptions.enableColumnResizing */ //default to true unless gridOptions or colDef is explicitly false colDef.enableColumnResizing = colDef.enableColumnResizing === undefined ? gridOptions.enableColumnResizing : colDef.enableColumnResizing; //legacy support of old option name if (colDef.enableColumnResize === false){ colDef.enableColumnResizing = false; } return $q.all(promises); }, registerPublicApi: function (grid) { /** * @ngdoc object * @name ui.grid.resizeColumns.api:PublicApi * @description Public Api for column resize feature. */ var publicApi = { events: { /** * @ngdoc event * @name columnSizeChanged * @eventOf ui.grid.resizeColumns.api:PublicApi * @description raised when column is resized * <pre> * gridApi.colResizable.on.columnSizeChanged(scope,function(colDef, deltaChange){}) * </pre> * @param {object} colDef the column that was resized * @param {integer} delta of the column size change */ colResizable: { columnSizeChanged: function (colDef, deltaChange) { } } } }; grid.api.registerEventsFromObject(publicApi.events); }, fireColumnSizeChanged: function (grid, colDef, deltaChange) { $timeout(function () { if ( grid.api.colResizable ){ grid.api.colResizable.raise.columnSizeChanged(colDef, deltaChange); } else { gridUtil.logError("The resizeable api is not registered, this may indicate that you've included the module but not added the 'ui-grid-resize-columns' directive to your grid definition. Cannot raise any events."); } }); }, // get either this column, or the column next to this column, to resize, // returns the column we're going to resize findTargetCol: function(col, position, rtlMultiplier){ var renderContainer = col.getRenderContainer(); if (position === 'left') { // Get the column to the left of this one var colIndex = renderContainer.visibleColumnCache.indexOf(col); return renderContainer.visibleColumnCache[colIndex - 1 * rtlMultiplier]; } else { return col; } } }; return service; }]); /** * @ngdoc directive * @name ui.grid.resizeColumns.directive:uiGridResizeColumns * @element div * @restrict A * @description * Enables resizing for all columns on the grid. If, for some reason, you want to use the ui-grid-resize-columns directive, but not allow column resizing, you can explicitly set the * option to false. This prevents resizing for the entire grid, regardless of individual columnDef options. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.gridOpts = { data: [ { "name": "Ethel Price", "gender": "female", "company": "Enersol" }, { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" }, { "name": "Beryl Rice", "gender": "female", "company": "Velity" }, { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" } ] }; }]); </script> <div ng-controller="MainCtrl"> <div class="testGrid" ui-grid="gridOpts" ui-grid-resize-columns ></div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ module.directive('uiGridResizeColumns', ['gridUtil', 'uiGridResizeColumnsService', function (gridUtil, uiGridResizeColumnsService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridResizeColumnsService.defaultGridOptions(uiGridCtrl.grid.options); uiGridCtrl.grid.registerColumnBuilder( uiGridResizeColumnsService.colResizerColumnBuilder); uiGridResizeColumnsService.registerPublicApi(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); // Extend the uiGridHeaderCell directive module.directive('uiGridHeaderCell', ['gridUtil', '$templateCache', '$compile', '$q', 'uiGridResizeColumnsService', 'uiGridConstants', '$timeout', function (gridUtil, $templateCache, $compile, $q, uiGridResizeColumnsService, uiGridConstants, $timeout) { return { // Run after the original uiGridHeaderCell priority: -10, require: '^uiGrid', // scope: false, compile: function() { return { post: function ($scope, $elm, $attrs, uiGridCtrl) { var grid = uiGridCtrl.grid; if (grid.options.enableColumnResizing) { var columnResizerElm = $templateCache.get('ui-grid/columnResizer'); var rtlMultiplier = 1; //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left if (grid.isRTL()) { $scope.position = 'left'; rtlMultiplier = -1; } var displayResizers = function(){ // remove any existing resizers. var resizers = $elm[0].getElementsByClassName('ui-grid-column-resizer'); for ( var i = 0; i < resizers.length; i++ ){ angular.element(resizers[i]).remove(); } // get the target column for the left resizer var otherCol = uiGridResizeColumnsService.findTargetCol($scope.col, 'left', rtlMultiplier); var renderContainer = $scope.col.getRenderContainer(); // Don't append the left resizer if this is the first column or the column to the left of this one has resizing disabled if (otherCol && renderContainer.visibleColumnCache.indexOf($scope.col) !== 0 && otherCol.colDef.enableColumnResizing !== false) { var resizerLeft = angular.element(columnResizerElm).clone(); resizerLeft.attr('position', 'left'); $elm.prepend(resizerLeft); $compile(resizerLeft)($scope); } // Don't append the right resizer if this column has resizing disabled if ($scope.col.colDef.enableColumnResizing !== false) { var resizerRight = angular.element(columnResizerElm).clone(); resizerRight.attr('position', 'right'); $elm.append(resizerRight); $compile(resizerRight)($scope); } }; displayResizers(); var waitDisplay = function(){ $timeout(displayResizers); }; var dataChangeDereg = grid.registerDataChangeCallback( waitDisplay, [uiGridConstants.dataChange.COLUMN] ); $scope.$on( '$destroy', dataChangeDereg ); } } }; } }; }]); /** * @ngdoc directive * @name ui.grid.resizeColumns.directive:uiGridColumnResizer * @element div * @restrict A * * @description * Draggable handle that controls column resizing. * * @example <doc:example module="app"> <doc:source> <script> var app = angular.module('app', ['ui.grid', 'ui.grid.resizeColumns']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.gridOpts = { enableColumnResizing: true, data: [ { "name": "Ethel Price", "gender": "female", "company": "Enersol" }, { "name": "Claudine Neal", "gender": "female", "company": "Sealoud" }, { "name": "Beryl Rice", "gender": "female", "company": "Velity" }, { "name": "Wilder Gonzales", "gender": "male", "company": "Geekko" } ] }; }]); </script> <div ng-controller="MainCtrl"> <div class="testGrid" ui-grid="gridOpts"></div> </div> </doc:source> <doc:scenario> // TODO: e2e specs? // TODO: post-resize a horizontal scroll event should be fired </doc:scenario> </doc:example> */ module.directive('uiGridColumnResizer', ['$document', 'gridUtil', 'uiGridConstants', 'uiGridResizeColumnsService', function ($document, gridUtil, uiGridConstants, uiGridResizeColumnsService) { var resizeOverlay = angular.element('<div class="ui-grid-resize-overlay"></div>'); var resizer = { priority: 0, scope: { col: '=', position: '@', renderIndex: '=' }, require: '?^uiGrid', link: function ($scope, $elm, $attrs, uiGridCtrl) { var startX = 0, x = 0, gridLeft = 0, rtlMultiplier = 1; //when in RTL mode reverse the direction using the rtlMultiplier and change the position to left if (uiGridCtrl.grid.isRTL()) { $scope.position = 'left'; rtlMultiplier = -1; } if ($scope.position === 'left') { $elm.addClass('left'); } else if ($scope.position === 'right') { $elm.addClass('right'); } // Refresh the grid canvas // takes an argument representing the diff along the X-axis that the resize had function refreshCanvas(xDiff) { // Then refresh the grid canvas, rebuilding the styles so that the scrollbar updates its size uiGridCtrl.grid.refreshCanvas(true).then( function() { uiGridCtrl.grid.queueGridRefresh(); }); } // Check that the requested width isn't wider than the maxWidth, or narrower than the minWidth // Returns the new recommended with, after constraints applied function constrainWidth(col, width){ var newWidth = width; // If the new width would be less than the column's allowably minimum width, don't allow it if (col.minWidth && newWidth < col.minWidth) { newWidth = col.minWidth; } else if (col.maxWidth && newWidth > col.maxWidth) { newWidth = col.maxWidth; } return newWidth; } /* * Our approach to event handling aims to deal with both touch devices and mouse devices * We register down handlers on both touch and mouse. When a touchstart or mousedown event * occurs, we register the corresponding touchmove/touchend, or mousemove/mouseend events. * * This way we can listen for both without worrying about the fact many touch devices also emulate * mouse events - basically whichever one we hear first is what we'll go with. */ function moveFunction(event, args) { if (event.originalEvent) { event = event.originalEvent; } event.preventDefault(); x = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft; if (x < 0) { x = 0; } else if (x > uiGridCtrl.grid.gridWidth) { x = uiGridCtrl.grid.gridWidth; } var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier); // Don't resize if it's disabled on this column if (col.colDef.enableColumnResizing === false) { return; } if (!uiGridCtrl.grid.element.hasClass('column-resizing')) { uiGridCtrl.grid.element.addClass('column-resizing'); } // Get the diff along the X axis var xDiff = x - startX; // Get the width that this mouse would give the column var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10); // check we're not outside the allowable bounds for this column x = x + ( constrainWidth(col, newWidth) - newWidth ) * rtlMultiplier; resizeOverlay.css({ left: x + 'px' }); uiGridCtrl.fireEvent(uiGridConstants.events.ITEM_DRAGGING); } function upFunction(event, args) { if (event.originalEvent) { event = event.originalEvent; } event.preventDefault(); uiGridCtrl.grid.element.removeClass('column-resizing'); resizeOverlay.remove(); // Resize the column x = (event.changedTouches ? event.changedTouches[0] : event).clientX - gridLeft; var xDiff = x - startX; if (xDiff === 0) { // no movement, so just reset event handlers, including turning back on both // down events - we turned one off when this event started offAllEvents(); onDownEvents(); return; } var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier); // Don't resize if it's disabled on this column if (col.colDef.enableColumnResizing === false) { return; } // Get the new width var newWidth = parseInt(col.drawnWidth + xDiff * rtlMultiplier, 10); // check we're not outside the allowable bounds for this column col.width = constrainWidth(col, newWidth); refreshCanvas(xDiff); uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff); // stop listening of up and move events - wait for next down // reset the down events - we will have turned one off when this event started offAllEvents(); onDownEvents(); } var downFunction = function(event, args) { if (event.originalEvent) { event = event.originalEvent; } event.stopPropagation(); // Get the left offset of the grid // gridLeft = uiGridCtrl.grid.element[0].offsetLeft; gridLeft = uiGridCtrl.grid.element[0].getBoundingClientRect().left; // Get the starting X position, which is the X coordinate of the click minus the grid's offset startX = (event.targetTouches ? event.targetTouches[0] : event).clientX - gridLeft; // Append the resizer overlay uiGridCtrl.grid.element.append(resizeOverlay); // Place the resizer overlay at the start position resizeOverlay.css({ left: startX }); // Add handlers for move and up events - if we were mousedown then we listen for mousemove and mouseup, if // we were touchdown then we listen for touchmove and touchup. Also remove the handler for the equivalent // down event - so if we're touchdown, then remove the mousedown handler until this event is over, if we're // mousedown then remove the touchdown handler until this event is over, this avoids processing duplicate events if ( event.type === 'touchstart' ){ $document.on('touchend', upFunction); $document.on('touchmove', moveFunction); $elm.off('mousedown', downFunction); } else { $document.on('mouseup', upFunction); $document.on('mousemove', moveFunction); $elm.off('touchstart', downFunction); } }; var onDownEvents = function() { $elm.on('mousedown', downFunction); $elm.on('touchstart', downFunction); }; var offAllEvents = function() { $document.off('mouseup', upFunction); $document.off('touchend', upFunction); $document.off('mousemove', moveFunction); $document.off('touchmove', moveFunction); $elm.off('mousedown', downFunction); $elm.off('touchstart', downFunction); }; onDownEvents(); // On doubleclick, resize to fit all rendered cells var dblClickFn = function(event, args){ event.stopPropagation(); var col = uiGridResizeColumnsService.findTargetCol($scope.col, $scope.position, rtlMultiplier); // Don't resize if it's disabled on this column if (col.colDef.enableColumnResizing === false) { return; } // Go through the rendered rows and find out the max size for the data in this column var maxWidth = 0; var xDiff = 0; // Get the parent render container element var renderContainerElm = gridUtil.closestElm($elm, '.ui-grid-render-container'); // Get the cell contents so we measure correctly. For the header cell we have to account for the sort icon and the menu buttons, if present var cells = renderContainerElm.querySelectorAll('.' + uiGridConstants.COL_CLASS_PREFIX + col.uid + ' .ui-grid-cell-contents'); Array.prototype.forEach.call(cells, function (cell) { // Get the cell width // gridUtil.logDebug('width', gridUtil.elementWidth(cell)); // Account for the menu button if it exists var menuButton; if (angular.element(cell).parent().hasClass('ui-grid-header-cell')) { menuButton = angular.element(cell).parent()[0].querySelectorAll('.ui-grid-column-menu-button'); } gridUtil.fakeElement(cell, {}, function(newElm) { // Make the element float since it's a div and can expand to fill its container var e = angular.element(newElm); e.attr('style', 'float: left'); var width = gridUtil.elementWidth(e); if (menuButton) { var menuButtonWidth = gridUtil.elementWidth(menuButton); width = width + menuButtonWidth; } if (width > maxWidth) { maxWidth = width; xDiff = maxWidth - width; } }); }); // check we're not outside the allowable bounds for this column col.width = constrainWidth(col, maxWidth); refreshCanvas(xDiff); uiGridResizeColumnsService.fireColumnSizeChanged(uiGridCtrl.grid, col.colDef, xDiff); }; $elm.on('dblclick', dblClickFn); $elm.on('$destroy', function() { $elm.off('dblclick', dblClickFn); offAllEvents(); }); } }; return resizer; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.rowEdit * @description * * # ui.grid.rowEdit * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module extends the edit feature to provide tracking and saving of rows * of data. The tutorial provides more information on how this feature is best * used {@link tutorial/205_row_editable here}. * <br/> * This feature depends on usage of the ui-grid-edit feature, and also benefits * from use of ui-grid-cellNav to provide the full spreadsheet-like editing * experience * */ var module = angular.module('ui.grid.rowEdit', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav']); /** * @ngdoc object * @name ui.grid.rowEdit.constant:uiGridRowEditConstants * * @description constants available in row edit module */ module.constant('uiGridRowEditConstants', { }); /** * @ngdoc service * @name ui.grid.rowEdit.service:uiGridRowEditService * * @description Services for row editing features */ module.service('uiGridRowEditService', ['$interval', '$q', 'uiGridConstants', 'uiGridRowEditConstants', 'gridUtil', function ($interval, $q, uiGridConstants, uiGridRowEditConstants, gridUtil) { var service = { initializeGrid: function (scope, grid) { /** * @ngdoc object * @name ui.grid.rowEdit.api:PublicApi * * @description Public Api for rowEdit feature */ grid.rowEdit = {}; var publicApi = { events: { rowEdit: { /** * @ngdoc event * @eventOf ui.grid.rowEdit.api:PublicApi * @name saveRow * @description raised when a row is ready for saving. Once your * row has saved you may need to use angular.extend to update the * data entity with any changed data from your save (for example, * lock version information if you're using optimistic locking, * or last update time/user information). * * Your method should call setSavePromise somewhere in the body before * returning control. The feature will then wait, with the gridRow greyed out * whilst this promise is being resolved. * * <pre> * gridApi.rowEdit.on.saveRow(scope,function(rowEntity){}) * </pre> * and somewhere within the event handler: * <pre> * gridApi.rowEdit.setSavePromise( rowEntity, savePromise) * </pre> * @param {object} rowEntity the options.data element that was edited * @returns {promise} Your saveRow method should return a promise, the * promise should either be resolved (implying successful save), or * rejected (implying an error). */ saveRow: function (rowEntity) { } } }, methods: { rowEdit: { /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name setSavePromise * @description Sets the promise associated with the row save, mandatory that * the saveRow event handler calls this method somewhere before returning. * <pre> * gridApi.rowEdit.setSavePromise(rowEntity, savePromise) * </pre> * @param {object} rowEntity a data row from the grid for which a save has * been initiated * @param {promise} savePromise the promise that will be resolved when the * save is successful, or rejected if the save fails * */ setSavePromise: function ( rowEntity, savePromise) { service.setSavePromise(grid, rowEntity, savePromise); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name getDirtyRows * @description Returns all currently dirty rows * <pre> * gridApi.rowEdit.getDirtyRows(grid) * </pre> * @returns {array} An array of gridRows that are currently dirty * */ getDirtyRows: function () { return grid.rowEdit.dirtyRows ? grid.rowEdit.dirtyRows : []; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name getErrorRows * @description Returns all currently errored rows * <pre> * gridApi.rowEdit.getErrorRows(grid) * </pre> * @returns {array} An array of gridRows that are currently in error * */ getErrorRows: function () { return grid.rowEdit.errorRows ? grid.rowEdit.errorRows : []; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name flushDirtyRows * @description Triggers a save event for all currently dirty rows, could * be used where user presses a save button or navigates away from the page * <pre> * gridApi.rowEdit.flushDirtyRows(grid) * </pre> * @returns {promise} a promise that represents the aggregate of all * of the individual save promises - i.e. it will be resolved when all * the individual save promises have been resolved. * */ flushDirtyRows: function () { return service.flushDirtyRows(grid); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name setRowsDirty * @description Sets each of the rows passed in dataRows * to be dirty. note that if you have only just inserted the * rows into your data you will need to wait for a $digest cycle * before the gridRows are present - so often you would wrap this * call in a $interval or $timeout * <pre> * $interval( function() { * gridApi.rowEdit.setRowsDirty(myDataRows); * }, 0, 1); * </pre> * @param {array} dataRows the data entities for which the gridRows * should be set dirty. * */ setRowsDirty: function ( dataRows) { service.setRowsDirty(grid, dataRows); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.api:PublicApi * @name setRowsClean * @description Sets each of the rows passed in dataRows * to be clean, removing them from the dirty cache and the error cache, * and clearing the error flag and the dirty flag * <pre> * var gridRows = $scope.gridApi.rowEdit.getDirtyRows(); * var dataRows = gridRows.map( function( gridRow ) { return gridRow.entity; }); * $scope.gridApi.rowEdit.setRowsClean( dataRows ); * </pre> * @param {array} dataRows the data entities for which the gridRows * should be set clean. * */ setRowsClean: function ( dataRows) { service.setRowsClean(grid, dataRows); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); grid.api.core.on.renderingComplete( scope, function ( gridApi ) { grid.api.edit.on.afterCellEdit( scope, service.endEditCell ); grid.api.edit.on.beginCellEdit( scope, service.beginEditCell ); grid.api.edit.on.cancelCellEdit( scope, service.cancelEditCell ); if ( grid.api.cellNav ) { grid.api.cellNav.on.navigate( scope, service.navigate ); } }); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.rowEdit.api:GridOptions * * @description Options for configuring the rowEdit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name saveRow * @description Returns a function that saves the specified row from the grid, * and returns a promise * @param {object} grid the grid for which dirty rows should be flushed * @param {GridRow} gridRow the row that should be saved * @returns {function} the saveRow function returns a function. That function * in turn, when called, returns a promise relating to the save callback */ saveRow: function ( grid, gridRow ) { var self = this; return function() { gridRow.isSaving = true; if ( gridRow.rowEditSavePromise ){ // don't save the row again if it's already saving - that causes stale object exceptions return gridRow.rowEditSavePromise; } var promise = grid.api.rowEdit.raise.saveRow( gridRow.entity ); if ( gridRow.rowEditSavePromise ){ gridRow.rowEditSavePromise.then( self.processSuccessPromise( grid, gridRow ), self.processErrorPromise( grid, gridRow )); } else { gridUtil.logError( 'A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise' ); } return promise; }; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name setSavePromise * @description Sets the promise associated with the row save, mandatory that * the saveRow event handler calls this method somewhere before returning. * <pre> * gridApi.rowEdit.setSavePromise(grid, rowEntity) * </pre> * @param {object} grid the grid for which dirty rows should be returned * @param {object} rowEntity a data row from the grid for which a save has * been initiated * @param {promise} savePromise the promise that will be resolved when the * save is successful, or rejected if the save fails * */ setSavePromise: function (grid, rowEntity, savePromise) { var gridRow = grid.getRow( rowEntity ); gridRow.rowEditSavePromise = savePromise; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name processSuccessPromise * @description Returns a function that processes the successful * resolution of a save promise * @param {object} grid the grid for which the promise should be processed * @param {GridRow} gridRow the row that has been saved * @returns {function} the success handling function */ processSuccessPromise: function ( grid, gridRow ) { var self = this; return function() { delete gridRow.isSaving; delete gridRow.isDirty; delete gridRow.isError; delete gridRow.rowEditSaveTimer; delete gridRow.rowEditSavePromise; self.removeRow( grid.rowEdit.errorRows, gridRow ); self.removeRow( grid.rowEdit.dirtyRows, gridRow ); }; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name processErrorPromise * @description Returns a function that processes the failed * resolution of a save promise * @param {object} grid the grid for which the promise should be processed * @param {GridRow} gridRow the row that is now in error * @returns {function} the error handling function */ processErrorPromise: function ( grid, gridRow ) { return function() { delete gridRow.isSaving; delete gridRow.rowEditSaveTimer; delete gridRow.rowEditSavePromise; gridRow.isError = true; if (!grid.rowEdit.errorRows){ grid.rowEdit.errorRows = []; } if (!service.isRowPresent( grid.rowEdit.errorRows, gridRow ) ){ grid.rowEdit.errorRows.push( gridRow ); } }; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name removeRow * @description Removes a row from a cache of rows - either * grid.rowEdit.errorRows or grid.rowEdit.dirtyRows. If the row * is not present silently does nothing. * @param {array} rowArray the array from which to remove the row * @param {GridRow} gridRow the row that should be removed */ removeRow: function( rowArray, removeGridRow ){ if (typeof(rowArray) === 'undefined' || rowArray === null){ return; } rowArray.forEach( function( gridRow, index ){ if ( gridRow.uid === removeGridRow.uid ){ rowArray.splice( index, 1); } }); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name isRowPresent * @description Checks whether a row is already present * in the given array * @param {array} rowArray the array in which to look for the row * @param {GridRow} gridRow the row that should be looked for */ isRowPresent: function( rowArray, removeGridRow ){ var present = false; rowArray.forEach( function( gridRow, index ){ if ( gridRow.uid === removeGridRow.uid ){ present = true; } }); return present; }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name flushDirtyRows * @description Triggers a save event for all currently dirty rows, could * be used where user presses a save button or navigates away from the page * <pre> * gridApi.rowEdit.flushDirtyRows(grid) * </pre> * @param {object} grid the grid for which dirty rows should be flushed * @returns {promise} a promise that represents the aggregate of all * of the individual save promises - i.e. it will be resolved when all * the individual save promises have been resolved. * */ flushDirtyRows: function(grid){ var promises = []; grid.rowEdit.dirtyRows.forEach( function( gridRow ){ service.saveRow( grid, gridRow )(); promises.push( gridRow.rowEditSavePromise ); }); return $q.all( promises ); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name endEditCell * @description Receives an afterCellEdit event from the edit function, * and sets flags as appropriate. Only the rowEntity parameter * is processed, although other params are available. Grid * is automatically provided by the gridApi. * @param {object} rowEntity the data entity for which the cell * was edited */ endEditCell: function( rowEntity, colDef, newValue, previousValue ){ var grid = this.grid; var gridRow = grid.getRow( rowEntity ); if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, dirty flag cannot be set' ); return; } if ( newValue !== previousValue || gridRow.isDirty ){ if ( !grid.rowEdit.dirtyRows ){ grid.rowEdit.dirtyRows = []; } if ( !gridRow.isDirty ){ gridRow.isDirty = true; grid.rowEdit.dirtyRows.push( gridRow ); } delete gridRow.isError; service.considerSetTimer( grid, gridRow ); } }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name beginEditCell * @description Receives a beginCellEdit event from the edit function, * and cancels any rowEditSaveTimers if present, as the user is still editing * this row. Only the rowEntity parameter * is processed, although other params are available. Grid * is automatically provided by the gridApi. * @param {object} rowEntity the data entity for which the cell * editing has commenced */ beginEditCell: function( rowEntity, colDef ){ var grid = this.grid; var gridRow = grid.getRow( rowEntity ); if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be cancelled' ); return; } service.cancelTimer( grid, gridRow ); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name cancelEditCell * @description Receives a cancelCellEdit event from the edit function, * and if the row was already dirty, restarts the save timer. If the row * was not already dirty, then it's not dirty now either and does nothing. * * Only the rowEntity parameter * is processed, although other params are available. Grid * is automatically provided by the gridApi. * * @param {object} rowEntity the data entity for which the cell * editing was cancelled */ cancelEditCell: function( rowEntity, colDef ){ var grid = this.grid; var gridRow = grid.getRow( rowEntity ); if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be set' ); return; } service.considerSetTimer( grid, gridRow ); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name navigate * @description cellNav tells us that the selected cell has changed. If * the new row had a timer running, then stop it similar to in a beginCellEdit * call. If the old row is dirty and not the same as the new row, then * start a timer on it. * @param {object} newRowCol the row and column that were selected * @param {object} oldRowCol the row and column that was left * */ navigate: function( newRowCol, oldRowCol ){ var grid = this.grid; if ( newRowCol.row.rowEditSaveTimer ){ service.cancelTimer( grid, newRowCol.row ); } if ( oldRowCol && oldRowCol.row && oldRowCol.row !== newRowCol.row ){ service.considerSetTimer( grid, oldRowCol.row ); } }, /** * @ngdoc property * @propertyOf ui.grid.rowEdit.api:GridOptions * @name rowEditWaitInterval * @description How long the grid should wait for another change on this row * before triggering a save (in milliseconds). If set to -1, then saves are * never triggered by timer (implying that the user will call flushDirtyRows() * manually) * * @example * Setting the wait interval to 4 seconds * <pre> * $scope.gridOptions = { rowEditWaitInterval: 4000 } * </pre> * */ /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name considerSetTimer * @description Consider setting a timer on this row (if it is dirty). if there is a timer running * on the row and the row isn't currently saving, cancel it, using cancelTimer, then if the row is * dirty and not currently saving then set a new timer * @param {object} grid the grid for which we are processing * @param {GridRow} gridRow the row for which the timer should be adjusted * */ considerSetTimer: function( grid, gridRow ){ service.cancelTimer( grid, gridRow ); if ( gridRow.isDirty && !gridRow.isSaving ){ if ( grid.options.rowEditWaitInterval !== -1 ){ var waitTime = grid.options.rowEditWaitInterval ? grid.options.rowEditWaitInterval : 2000; gridRow.rowEditSaveTimer = $interval( service.saveRow( grid, gridRow ), waitTime, 1); } } }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name cancelTimer * @description cancel the $interval for any timer running on this row * then delete the timer itself * @param {object} grid the grid for which we are processing * @param {GridRow} gridRow the row for which the timer should be adjusted * */ cancelTimer: function( grid, gridRow ){ if ( gridRow.rowEditSaveTimer && !gridRow.isSaving ){ $interval.cancel(gridRow.rowEditSaveTimer); delete gridRow.rowEditSaveTimer; } }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name setRowsDirty * @description Sets each of the rows passed in dataRows * to be dirty. note that if you have only just inserted the * rows into your data you will need to wait for a $digest cycle * before the gridRows are present - so often you would wrap this * call in a $interval or $timeout * <pre> * $interval( function() { * gridApi.rowEdit.setRowsDirty( myDataRows); * }, 0, 1); * </pre> * @param {object} grid the grid for which rows should be set dirty * @param {array} dataRows the data entities for which the gridRows * should be set dirty. * */ setRowsDirty: function( grid, myDataRows ) { var gridRow; myDataRows.forEach( function( value, index ){ gridRow = grid.getRow( value ); if ( gridRow ){ if ( !grid.rowEdit.dirtyRows ){ grid.rowEdit.dirtyRows = []; } if ( !gridRow.isDirty ){ gridRow.isDirty = true; grid.rowEdit.dirtyRows.push( gridRow ); } delete gridRow.isError; service.considerSetTimer( grid, gridRow ); } else { gridUtil.logError( "requested row not found in rowEdit.setRowsDirty, row was: " + value ); } }); }, /** * @ngdoc method * @methodOf ui.grid.rowEdit.service:uiGridRowEditService * @name setRowsClean * @description Sets each of the rows passed in dataRows * to be clean, clearing the dirty flag and the error flag, and removing * the rows from the dirty and error caches. * @param {object} grid the grid for which rows should be set clean * @param {array} dataRows the data entities for which the gridRows * should be set clean. * */ setRowsClean: function( grid, myDataRows ) { var gridRow; myDataRows.forEach( function( value, index ){ gridRow = grid.getRow( value ); if ( gridRow ){ delete gridRow.isDirty; service.removeRow( grid.rowEdit.dirtyRows, gridRow ); service.cancelTimer( grid, gridRow ); delete gridRow.isError; service.removeRow( grid.rowEdit.errorRows, gridRow ); } else { gridUtil.logError( "requested row not found in rowEdit.setRowsClean, row was: " + value ); } }); } }; return service; }]); /** * @ngdoc directive * @name ui.grid.rowEdit.directive:uiGridEdit * @element div * @restrict A * * @description Adds row editing features to the ui-grid-edit directive. * */ module.directive('uiGridRowEdit', ['gridUtil', 'uiGridRowEditService', 'uiGridEditConstants', function (gridUtil, uiGridRowEditService, uiGridEditConstants) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridRowEditService.initializeGrid($scope, uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.rowEdit.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used * for the grid row to allow coloring of saving and error rows */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse', function ($compile, uiGridConstants, gridUtil, $parse) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}"; } else { newNgClass = "{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.saveState * @description * * # ui.grid.saveState * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides the ability to save the grid state, and restore * it when the user returns to the page. * * No UI is provided, the caller should provide their own UI/buttons * as appropriate. Usually the navigate events would be used to save * the grid state and restore it. * * <br/> * <br/> * * <div doc-module-components="ui.grid.save-state"></div> */ var module = angular.module('ui.grid.saveState', ['ui.grid', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.grouping', 'ui.grid.pinning', 'ui.grid.treeView']); /** * @ngdoc object * @name ui.grid.saveState.constant:uiGridSaveStateConstants * * @description constants available in save state module */ module.constant('uiGridSaveStateConstants', { featureName: 'saveState' }); /** * @ngdoc service * @name ui.grid.saveState.service:uiGridSaveStateService * * @description Services for saveState feature */ module.service('uiGridSaveStateService', ['$q', 'uiGridSaveStateConstants', 'gridUtil', '$compile', '$interval', 'uiGridConstants', function ($q, uiGridSaveStateConstants, gridUtil, $compile, $interval, uiGridConstants ) { var service = { initializeGrid: function (grid) { //add feature namespace and any properties to grid for needed state grid.saveState = {}; this.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.saveState.api:PublicApi * * @description Public Api for saveState feature */ var publicApi = { events: { saveState: { } }, methods: { saveState: { /** * @ngdoc function * @name save * @methodOf ui.grid.saveState.api:PublicApi * @description Packages the current state of the grid into * an object, and provides it to the user for saving * @returns {object} the state as a javascript object that can be saved */ save: function () { return service.save(grid); }, /** * @ngdoc function * @name restore * @methodOf ui.grid.saveState.api:PublicApi * @description Restores the provided state into the grid * @param {scope} $scope a scope that we can broadcast on * @param {object} state the state that should be restored into the grid */ restore: function ( $scope, state) { service.restore(grid, $scope, state); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.saveState.api:GridOptions * * @description GridOptions for saveState feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name saveWidths * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current column widths. Note that unless * you've provided the user with some way to resize their columns (say * the resize columns feature), then this makes little sense. * <br/>Defaults to true */ gridOptions.saveWidths = gridOptions.saveWidths !== false; /** * @ngdoc object * @name saveOrder * @propertyOf ui.grid.saveState.api:GridOptions * @description Restore the current column order. Note that unless * you've provided the user with some way to reorder their columns (for * example the move columns feature), this makes little sense. * <br/>Defaults to true */ gridOptions.saveOrder = gridOptions.saveOrder !== false; /** * @ngdoc object * @name saveScroll * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current scroll position. Note that this * is saved as the percentage of the grid scrolled - so if your * user returns to a grid with a significantly different number of * rows (perhaps some data has been deleted) then the scroll won't * actually show the same rows as before. If you want to scroll to * a specific row then you should instead use the saveFocus option, which * is the default. * * Note that this element will only be saved if the cellNav feature is * enabled * <br/>Defaults to false */ gridOptions.saveScroll = gridOptions.saveScroll === true; /** * @ngdoc object * @name saveFocus * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current focused cell. On returning * to this focused cell we'll also scroll. This option is * preferred to the saveScroll option, so is set to true by * default. If saveScroll is set to true then this option will * be disabled. * * By default this option saves the current row number and column * number, and returns to that row and column. However, if you define * a saveRowIdentity function, then it will return you to the currently * selected column within that row (in a business sense - so if some * rows have been deleted, it will still find the same data, presuming it * still exists in the list. If it isn't in the list then it will instead * return to the same row number - i.e. scroll percentage) * * Note that this option will do nothing if the cellNav * feature is not enabled. * * <br/>Defaults to true (unless saveScroll is true) */ gridOptions.saveFocus = gridOptions.saveScroll !== true && gridOptions.saveFocus !== false; /** * @ngdoc object * @name saveRowIdentity * @propertyOf ui.grid.saveState.api:GridOptions * @description A function that can be called, passing in a rowEntity, * and that will return a unique id for that row. This might simply * return the `id` field from that row (if you have one), or it might * concatenate some fields within the row to make a unique value. * * This value will be used to find the same row again and set the focus * to it, if it exists when we return. * * <br/>Defaults to undefined */ /** * @ngdoc object * @name saveVisible * @propertyOf ui.grid.saveState.api:GridOptions * @description Save whether or not columns are visible. * * <br/>Defaults to true */ gridOptions.saveVisible = gridOptions.saveVisible !== false; /** * @ngdoc object * @name saveSort * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current sort state for each column * * <br/>Defaults to true */ gridOptions.saveSort = gridOptions.saveSort !== false; /** * @ngdoc object * @name saveFilter * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the current filter state for each column * * <br/>Defaults to true */ gridOptions.saveFilter = gridOptions.saveFilter !== false; /** * @ngdoc object * @name saveSelection * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the currently selected rows. If the `saveRowIdentity` callback * is defined, then it will save the id of the row and select that. If not, then * it will attempt to select the rows by row number, which will give the wrong results * if the data set has changed in the mean-time. * * Note that this option only does anything * if the selection feature is enabled. * * <br/>Defaults to true */ gridOptions.saveSelection = gridOptions.saveSelection !== false; /** * @ngdoc object * @name saveGrouping * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the grouping configuration. If set to true and the * grouping feature is not enabled then does nothing. * * <br/>Defaults to true */ gridOptions.saveGrouping = gridOptions.saveGrouping !== false; /** * @ngdoc object * @name saveGroupingExpandedStates * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the grouping row expanded states. If set to true and the * grouping feature is not enabled then does nothing. * * This can be quite a bit of data, in many cases you wouldn't want to save this * information. * * <br/>Defaults to false */ gridOptions.saveGroupingExpandedStates = gridOptions.saveGroupingExpandedStates === true; /** * @ngdoc object * @name savePinning * @propertyOf ui.grid.saveState.api:GridOptions * @description Save pinning state for columns. * * <br/>Defaults to true */ gridOptions.savePinning = gridOptions.savePinning !== false; /** * @ngdoc object * @name saveTreeView * @propertyOf ui.grid.saveState.api:GridOptions * @description Save the treeView configuration. If set to true and the * treeView feature is not enabled then does nothing. * * <br/>Defaults to true */ gridOptions.saveTreeView = gridOptions.saveTreeView !== false; }, /** * @ngdoc function * @name save * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the current grid state into an object, and * passes that object back to the caller * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the state ready to be saved */ save: function (grid) { var savedState = {}; savedState.columns = service.saveColumns( grid ); savedState.scrollFocus = service.saveScrollFocus( grid ); savedState.selection = service.saveSelection( grid ); savedState.grouping = service.saveGrouping( grid ); savedState.treeView = service.saveTreeView( grid ); return savedState; }, /** * @ngdoc function * @name restore * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Applies the provided state to the grid * * @param {Grid} grid the grid whose state we'd like to restore * @param {scope} $scope a scope that we can broadcast on * @param {object} state the state we'd like to restore */ restore: function( grid, $scope, state ){ if ( state.columns ) { service.restoreColumns( grid, state.columns ); } if ( state.scrollFocus ){ service.restoreScrollFocus( grid, $scope, state.scrollFocus ); } if ( state.selection ){ service.restoreSelection( grid, state.selection ); } if ( state.grouping ){ service.restoreGrouping( grid, state.grouping ); } if ( state.treeView ){ service.restoreTreeView( grid, state.treeView ); } grid.refresh(); }, /** * @ngdoc function * @name saveColumns * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the column setup, including sort, filters, ordering, * pinning and column widths. * * Works through the current columns, storing them in order. Stores the * column name, then the visible flag, width, sort and filters for each column. * * @param {Grid} grid the grid whose state we'd like to save * @returns {array} the columns state ready to be saved */ saveColumns: function( grid ) { var columns = []; grid.getOnlyDataColumns().forEach( function( column ) { var savedColumn = {}; savedColumn.name = column.name; if ( grid.options.saveVisible ){ savedColumn.visible = column.visible; } if ( grid.options.saveWidths ){ savedColumn.width = column.width; } // these two must be copied, not just pointed too - otherwise our saved state is pointing to the same object as current state if ( grid.options.saveSort ){ savedColumn.sort = angular.copy( column.sort ); } if ( grid.options.saveFilter ){ savedColumn.filters = []; column.filters.forEach( function( filter ){ var copiedFilter = {}; angular.forEach( filter, function( value, key) { if ( key !== 'condition' && key !== '$$hashKey' && key !== 'placeholder'){ copiedFilter[key] = value; } }); savedColumn.filters.push(copiedFilter); }); } if ( !!grid.api.pinning && grid.options.savePinning ){ savedColumn.pinned = column.renderContainer ? column.renderContainer : ''; } columns.push( savedColumn ); }); return columns; }, /** * @ngdoc function * @name saveScrollFocus * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the currently scroll or focus. * * If cellNav isn't present then does nothing - we can't return * to the scroll position without cellNav anyway. * * If the cellNav module is present, and saveFocus is true, then * it saves the currently focused cell. If rowIdentity is present * then saves using rowIdentity, otherwise saves visibleRowNum. * * If the cellNav module is not present, and saveScroll is true, then * it approximates the current scroll row and column, and saves that. * * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the selection state ready to be saved */ saveScrollFocus: function( grid ){ if ( !grid.api.cellNav ){ return {}; } var scrollFocus = {}; if ( grid.options.saveFocus ){ scrollFocus.focus = true; var rowCol = grid.api.cellNav.getFocusedCell(); if ( rowCol !== null ) { if ( rowCol.col !== null ){ scrollFocus.colName = rowCol.col.colDef.name; } if ( rowCol.row !== null ){ scrollFocus.rowVal = service.getRowVal( grid, rowCol.row ); } } } if ( grid.options.saveScroll || grid.options.saveFocus && !scrollFocus.colName && !scrollFocus.rowVal ) { scrollFocus.focus = false; if ( grid.renderContainers.body.prevRowScrollIndex ){ scrollFocus.rowVal = service.getRowVal( grid, grid.renderContainers.body.visibleRowCache[ grid.renderContainers.body.prevRowScrollIndex ]); } if ( grid.renderContainers.body.prevColScrollIndex ){ scrollFocus.colName = grid.renderContainers.body.visibleColumnCache[ grid.renderContainers.body.prevColScrollIndex ].name; } } return scrollFocus; }, /** * @ngdoc function * @name saveSelection * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the currently selected rows, if the selection feature is enabled * @param {Grid} grid the grid whose state we'd like to save * @returns {array} the selection state ready to be saved */ saveSelection: function( grid ){ if ( !grid.api.selection || !grid.options.saveSelection ){ return []; } var selection = grid.api.selection.getSelectedGridRows().map( function( gridRow ) { return service.getRowVal( grid, gridRow ); }); return selection; }, /** * @ngdoc function * @name saveGrouping * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the grouping state, if the grouping feature is enabled * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the grouping state ready to be saved */ saveGrouping: function( grid ){ if ( !grid.api.grouping || !grid.options.saveGrouping ){ return {}; } return grid.api.grouping.getGrouping( grid.options.saveGroupingExpandedStates ); }, /** * @ngdoc function * @name saveTreeView * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Saves the tree view state, if the tree feature is enabled * @param {Grid} grid the grid whose state we'd like to save * @returns {object} the tree view state ready to be saved */ saveTreeView: function( grid ){ if ( !grid.api.treeView || !grid.options.saveTreeView ){ return {}; } return grid.api.treeView.getTreeView(); }, /** * @ngdoc function * @name getRowVal * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Helper function that gets either the rowNum or * the saveRowIdentity, given a gridRow * @param {Grid} grid the grid the row is in * @param {GridRow} gridRow the row we want the rowNum for * @returns {object} an object containing { identity: true/false, row: rowNumber/rowIdentity } * */ getRowVal: function( grid, gridRow ){ if ( !gridRow ) { return null; } var rowVal = {}; if ( grid.options.saveRowIdentity ){ rowVal.identity = true; rowVal.row = grid.options.saveRowIdentity( gridRow.entity ); } else { rowVal.identity = false; rowVal.row = grid.renderContainers.body.visibleRowCache.indexOf( gridRow ); } return rowVal; }, /** * @ngdoc function * @name restoreColumns * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Restores the columns, including order, visible, width, * pinning, sort and filters. * * @param {Grid} grid the grid whose state we'd like to restore * @param {object} columnsState the list of columns we had before, with their state */ restoreColumns: function( grid, columnsState ){ var isSortChanged = false; columnsState.forEach( function( columnState, index ) { var currentCol = grid.getColumn( columnState.name ); if ( currentCol && !grid.isRowHeaderColumn(currentCol) ){ if ( grid.options.saveVisible && ( currentCol.visible !== columnState.visible || currentCol.colDef.visible !== columnState.visible ) ){ currentCol.visible = columnState.visible; currentCol.colDef.visible = columnState.visible; grid.api.core.raise.columnVisibilityChanged(currentCol); } if ( grid.options.saveWidths ){ currentCol.width = columnState.width; } if ( grid.options.saveSort && !angular.equals(currentCol.sort, columnState.sort) && !( currentCol.sort === undefined && angular.isEmpty(columnState.sort) ) ){ currentCol.sort = angular.copy( columnState.sort ); isSortChanged = true; } if ( grid.options.saveFilter && !angular.equals(currentCol.filters, columnState.filters ) ){ columnState.filters.forEach( function( filter, index ){ angular.extend( currentCol.filters[index], filter ); if ( typeof(filter.term) === 'undefined' || filter.term === null ){ delete currentCol.filters[index].term; } }); grid.api.core.raise.filterChanged(); } if ( !!grid.api.pinning && grid.options.savePinning && currentCol.renderContainer !== columnState.pinned ){ grid.api.pinning.pinColumn(currentCol, columnState.pinned); } var currentIndex = grid.getOnlyDataColumns().indexOf( currentCol ); if (currentIndex !== -1) { if (grid.options.saveOrder && currentIndex !== index) { var column = grid.columns.splice(currentIndex + grid.rowHeaderColumns.length, 1)[0]; grid.columns.splice(index + grid.rowHeaderColumns.length, 0, column); } } } }); if ( isSortChanged ) { grid.api.core.raise.sortChanged( grid, grid.getColumnSorting() ); } }, /** * @ngdoc function * @name restoreScrollFocus * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Scrolls to the position that was saved. If focus is true, then * sets focus to the specified row/col. If focus is false, then scrolls to the * specified row/col. * * @param {Grid} grid the grid whose state we'd like to restore * @param {scope} $scope a scope that we can broadcast on * @param {object} scrollFocusState the scroll/focus state ready to be restored */ restoreScrollFocus: function( grid, $scope, scrollFocusState ){ if ( !grid.api.cellNav ){ return; } var colDef, row; if ( scrollFocusState.colName ){ var colDefs = grid.options.columnDefs.filter( function( colDef ) { return colDef.name === scrollFocusState.colName; }); if ( colDefs.length > 0 ){ colDef = colDefs[0]; } } if ( scrollFocusState.rowVal && scrollFocusState.rowVal.row ){ if ( scrollFocusState.rowVal.identity ){ row = service.findRowByIdentity( grid, scrollFocusState.rowVal ); } else { row = grid.renderContainers.body.visibleRowCache[ scrollFocusState.rowVal.row ]; } } var entity = row && row.entity ? row.entity : null ; if ( colDef || entity ) { if (scrollFocusState.focus ){ grid.api.cellNav.scrollToFocus( entity, colDef ); } else { grid.scrollTo( entity, colDef ); } } }, /** * @ngdoc function * @name restoreSelection * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Selects the rows that are provided in the selection * state. If you are using `saveRowIdentity` and more than one row matches the identity * function then only the first is selected. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} selectionState the selection state ready to be restored */ restoreSelection: function( grid, selectionState ){ if ( !grid.api.selection ){ return; } grid.api.selection.clearSelectedRows(); selectionState.forEach( function( rowVal ) { if ( rowVal.identity ){ var foundRow = service.findRowByIdentity( grid, rowVal ); if ( foundRow ){ grid.api.selection.selectRow( foundRow.entity ); } } else { grid.api.selection.selectRowByVisibleIndex( rowVal.row ); } }); }, /** * @ngdoc function * @name restoreGrouping * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Restores the grouping configuration, if the grouping feature * is enabled. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} groupingState the grouping state ready to be restored */ restoreGrouping: function( grid, groupingState ){ if ( !grid.api.grouping || typeof(groupingState) === 'undefined' || groupingState === null || angular.equals(groupingState, {}) ){ return; } grid.api.grouping.setGrouping( groupingState ); }, /** * @ngdoc function * @name restoreTreeView * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Restores the tree view configuration, if the tree view feature * is enabled. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} treeViewState the tree view state ready to be restored */ restoreTreeView: function( grid, treeViewState ){ if ( !grid.api.treeView || typeof(treeViewState) === 'undefined' || treeViewState === null || angular.equals(treeViewState, {}) ){ return; } grid.api.treeView.setTreeView( treeViewState ); }, /** * @ngdoc function * @name findRowByIdentity * @methodOf ui.grid.saveState.service:uiGridSaveStateService * @description Finds a row given it's identity value, returns the first found row * if any are found, otherwise returns null if no rows are found. * @param {Grid} grid the grid whose state we'd like to restore * @param {object} rowVal the row we'd like to find * @returns {gridRow} the found row, or null if none found */ findRowByIdentity: function( grid, rowVal ){ if ( !grid.options.saveRowIdentity ){ return null; } var filteredRows = grid.rows.filter( function( gridRow ) { if ( grid.options.saveRowIdentity( gridRow.entity ) === rowVal.row ){ return true; } else { return false; } }); if ( filteredRows.length > 0 ){ return filteredRows[0]; } else { return null; } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.saveState.directive:uiGridSaveState * @element div * @restrict A * * @description Adds saveState features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.saveState']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.gridOptions = { columnDefs: [ {name: 'name'}, {name: 'title', enableCellEdit: true} ], data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-save-state></div> </div> </file> </example> */ module.directive('uiGridSaveState', ['uiGridSaveStateConstants', 'uiGridSaveStateService', 'gridUtil', '$compile', function (uiGridSaveStateConstants, uiGridSaveStateService, gridUtil, $compile) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridSaveStateService.initializeGrid(uiGridCtrl.grid); } }; } ]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.selection * @description * * # ui.grid.selection * This module provides row selection * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * <div doc-module-components="ui.grid.selection"></div> */ var module = angular.module('ui.grid.selection', ['ui.grid']); /** * @ngdoc object * @name ui.grid.selection.constant:uiGridSelectionConstants * * @description constants available in selection module */ module.constant('uiGridSelectionConstants', { featureName: "selection", selectionRowHeaderColName: 'selectionRowHeaderCol' }); //add methods to GridRow angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('GridRow', ['$delegate', function($delegate) { /** * @ngdoc object * @name ui.grid.selection.api:GridRow * * @description GridRow prototype functions added for selection */ /** * @ngdoc object * @name enableSelection * @propertyOf ui.grid.selection.api:GridRow * @description Enable row selection for this row, only settable by internal code. * * The grouping feature, for example, might set group header rows to not be selectable. * <br/>Defaults to true */ /** * @ngdoc object * @name isSelected * @propertyOf ui.grid.selection.api:GridRow * @description Selected state of row. Should be readonly. Make any changes to selected state using setSelected(). * <br/>Defaults to false */ /** * @ngdoc function * @name setSelected * @methodOf ui.grid.selection.api:GridRow * @description Sets the isSelected property and updates the selectedCount * Changes to isSelected state should only be made via this function * @param {bool} selected value to set */ $delegate.prototype.setSelected = function(selected) { this.isSelected = selected; if (selected) { this.grid.selection.selectedCount++; } else { this.grid.selection.selectedCount--; } }; return $delegate; }]); }]); /** * @ngdoc service * @name ui.grid.selection.service:uiGridSelectionService * * @description Services for selection features */ module.service('uiGridSelectionService', ['$q', '$templateCache', 'uiGridSelectionConstants', 'gridUtil', function ($q, $templateCache, uiGridSelectionConstants, gridUtil) { var service = { initializeGrid: function (grid) { //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.selection.grid:selection * * @description Grid properties and functions added for selection */ grid.selection = {}; grid.selection.lastSelectedRow = null; grid.selection.selectAll = false; /** * @ngdoc object * @name selectedCount * @propertyOf ui.grid.selection.grid:selection * @description Current count of selected rows * @example * var count = grid.selection.selectedCount */ grid.selection.selectedCount = 0; service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.selection.api:PublicApi * * @description Public Api for selection feature */ var publicApi = { events: { selection: { /** * @ngdoc event * @name rowSelectionChanged * @eventOf ui.grid.selection.api:PublicApi * @description is raised after the row.isSelected state is changed * @param {GridRow} row the row that was selected/deselected * @param {Event} event object if raised from an event */ rowSelectionChanged: function (scope, row, evt) { }, /** * @ngdoc event * @name rowSelectionChangedBatch * @eventOf ui.grid.selection.api:PublicApi * @description is raised after the row.isSelected state is changed * in bulk, if the `enableSelectionBatchEvent` option is set to true * (which it is by default). This allows more efficient processing * of bulk events. * @param {array} rows the rows that were selected/deselected * @param {Event} event object if raised from an event */ rowSelectionChangedBatch: function (scope, rows, evt) { } } }, methods: { selection: { /** * @ngdoc function * @name toggleRowSelection * @methodOf ui.grid.selection.api:PublicApi * @description Toggles data row as selected or unselected * @param {object} rowEntity gridOptions.data[] array instance * @param {Event} event object if raised from an event */ toggleRowSelection: function (rowEntity, evt) { var row = grid.getRow(rowEntity); if (row !== null) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name selectRow * @methodOf ui.grid.selection.api:PublicApi * @description Select the data row * @param {object} rowEntity gridOptions.data[] array instance * @param {Event} event object if raised from an event */ selectRow: function (rowEntity, evt) { var row = grid.getRow(rowEntity); if (row !== null && !row.isSelected) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name selectRowByVisibleIndex * @methodOf ui.grid.selection.api:PublicApi * @description Select the specified row by visible index (i.e. if you * specify row 0 you'll get the first visible row selected). In this context * visible means of those rows that are theoretically visible (i.e. not filtered), * rather than rows currently rendered on the screen. * @param {number} index index within the rowsVisible array * @param {Event} event object if raised from an event */ selectRowByVisibleIndex: function ( rowNum, evt ) { var row = grid.renderContainers.body.visibleRowCache[rowNum]; if (row !== null && typeof(row) !== 'undefined' && !row.isSelected) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name unSelectRow * @methodOf ui.grid.selection.api:PublicApi * @description UnSelect the data row * @param {object} rowEntity gridOptions.data[] array instance * @param {Event} event object if raised from an event */ unSelectRow: function (rowEntity, evt) { var row = grid.getRow(rowEntity); if (row !== null && row.isSelected) { service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect); } }, /** * @ngdoc function * @name selectAllRows * @methodOf ui.grid.selection.api:PublicApi * @description Selects all rows. Does nothing if multiSelect = false * @param {Event} event object if raised from an event */ selectAllRows: function (evt) { if (grid.options.multiSelect === false) { return; } var changedRows = []; grid.rows.forEach(function (row) { if ( !row.isSelected && row.enableSelection !== false ){ row.setSelected(true); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } }); service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); grid.selection.selectAll = true; }, /** * @ngdoc function * @name selectAllVisibleRows * @methodOf ui.grid.selection.api:PublicApi * @description Selects all visible rows. Does nothing if multiSelect = false * @param {Event} event object if raised from an event */ selectAllVisibleRows: function (evt) { if (grid.options.multiSelect === false) { return; } var changedRows = []; grid.rows.forEach(function (row) { if (row.visible) { if (!row.isSelected && row.enableSelection !== false){ row.setSelected(true); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } } else { if (row.isSelected){ row.setSelected(false); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } } }); service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); grid.selection.selectAll = true; }, /** * @ngdoc function * @name clearSelectedRows * @methodOf ui.grid.selection.api:PublicApi * @description Unselects all rows * @param {Event} event object if raised from an event */ clearSelectedRows: function (evt) { service.clearSelectedRows(grid, evt); }, /** * @ngdoc function * @name getSelectedRows * @methodOf ui.grid.selection.api:PublicApi * @description returns all selectedRow's entity references */ getSelectedRows: function () { return service.getSelectedRows(grid).map(function (gridRow) { return gridRow.entity; }); }, /** * @ngdoc function * @name getSelectedGridRows * @methodOf ui.grid.selection.api:PublicApi * @description returns all selectedRow's as gridRows */ getSelectedGridRows: function () { return service.getSelectedRows(grid); }, /** * @ngdoc function * @name setMultiSelect * @methodOf ui.grid.selection.api:PublicApi * @description Sets the current gridOption.multiSelect to true or false * @param {bool} multiSelect true to allow multiple rows */ setMultiSelect: function (multiSelect) { grid.options.multiSelect = multiSelect; }, /** * @ngdoc function * @name setModifierKeysToMultiSelect * @methodOf ui.grid.selection.api:PublicApi * @description Sets the current gridOption.modifierKeysToMultiSelect to true or false * @param {bool} modifierKeysToMultiSelect true to only allow multiple rows when using ctrlKey or shiftKey is used */ setModifierKeysToMultiSelect: function (modifierKeysToMultiSelect) { grid.options.modifierKeysToMultiSelect = modifierKeysToMultiSelect; }, /** * @ngdoc function * @name getSelectAllState * @methodOf ui.grid.selection.api:PublicApi * @description Returns whether or not the selectAll checkbox is currently ticked. The * grid doesn't automatically select rows when you add extra data - so when you add data * you need to explicitly check whether the selectAll is set, and then call setVisible rows * if it is */ getSelectAllState: function () { return grid.selection.selectAll; } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.selection.api:GridOptions * * @description GridOptions for selection feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableRowSelection * @propertyOf ui.grid.selection.api:GridOptions * @description Enable row selection for entire grid. * <br/>Defaults to true */ gridOptions.enableRowSelection = gridOptions.enableRowSelection !== false; /** * @ngdoc object * @name multiSelect * @propertyOf ui.grid.selection.api:GridOptions * @description Enable multiple row selection for entire grid * <br/>Defaults to true */ gridOptions.multiSelect = gridOptions.multiSelect !== false; /** * @ngdoc object * @name noUnselect * @propertyOf ui.grid.selection.api:GridOptions * @description Prevent a row from being unselected. Works in conjunction * with `multiselect = false` and `gridApi.selection.selectRow()` to allow * you to create a single selection only grid - a row is always selected, you * can only select different rows, you can't unselect the row. * <br/>Defaults to false */ gridOptions.noUnselect = gridOptions.noUnselect === true; /** * @ngdoc object * @name modifierKeysToMultiSelect * @propertyOf ui.grid.selection.api:GridOptions * @description Enable multiple row selection only when using the ctrlKey or shiftKey. Requires multiSelect to be true. * <br/>Defaults to false */ gridOptions.modifierKeysToMultiSelect = gridOptions.modifierKeysToMultiSelect === true; /** * @ngdoc object * @name enableRowHeaderSelection * @propertyOf ui.grid.selection.api:GridOptions * @description Enable a row header to be used for selection * <br/>Defaults to true */ gridOptions.enableRowHeaderSelection = gridOptions.enableRowHeaderSelection !== false; /** * @ngdoc object * @name enableFullRowSelection * @propertyOf ui.grid.selection.api:GridOptions * @description Enable selection by clicking anywhere on the row. Defaults to * false if `enableRowHeaderSelection` is true, otherwise defaults to false. */ if ( typeof(gridOptions.enableFullRowSelection) === 'undefined' ){ gridOptions.enableFullRowSelection = !gridOptions.enableRowHeaderSelection; } /** * @ngdoc object * @name enableSelectAll * @propertyOf ui.grid.selection.api:GridOptions * @description Enable the select all checkbox at the top of the selectionRowHeader * <br/>Defaults to true */ gridOptions.enableSelectAll = gridOptions.enableSelectAll !== false; /** * @ngdoc object * @name enableSelectionBatchEvent * @propertyOf ui.grid.selection.api:GridOptions * @description If selected rows are changed in bulk, either via the API or * via the selectAll checkbox, then a separate event is fired. Setting this * option to false will cause the rowSelectionChanged event to be called multiple times * instead * <br/>Defaults to true */ gridOptions.enableSelectionBatchEvent = gridOptions.enableSelectionBatchEvent !== false; /** * @ngdoc object * @name selectionRowHeaderWidth * @propertyOf ui.grid.selection.api:GridOptions * @description can be used to set a custom width for the row header selection column * <br/>Defaults to 30px */ gridOptions.selectionRowHeaderWidth = angular.isDefined(gridOptions.selectionRowHeaderWidth) ? gridOptions.selectionRowHeaderWidth : 30; /** * @ngdoc object * @name enableFooterTotalSelected * @propertyOf ui.grid.selection.api:GridOptions * @description Shows the total number of selected items in footer if true. * <br/>Defaults to true. * <br/>GridOptions.showGridFooter must also be set to true. */ gridOptions.enableFooterTotalSelected = gridOptions.enableFooterTotalSelected !== false; /** * @ngdoc object * @name isRowSelectable * @propertyOf ui.grid.selection.api:GridOptions * @description Makes it possible to specify a method that evaluates for each row and sets its "enableSelection" property. */ gridOptions.isRowSelectable = angular.isDefined(gridOptions.isRowSelectable) ? gridOptions.isRowSelectable : angular.noop; }, /** * @ngdoc function * @name toggleRowSelection * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Toggles row as selected or unselected * @param {Grid} grid grid object * @param {GridRow} row row to select or deselect * @param {Event} event object if resulting from event * @param {bool} multiSelect if false, only one row at time can be selected * @param {bool} noUnselect if true then rows cannot be unselected */ toggleRowSelection: function (grid, row, evt, multiSelect, noUnselect) { var selected = row.isSelected; if ( row.enableSelection === false && !selected ){ return; } if (!multiSelect && !selected) { service.clearSelectedRows(grid, evt); } else if (!multiSelect && selected) { var selectedRows = service.getSelectedRows(grid); if (selectedRows.length > 1) { selected = false; // Enable reselect of the row service.clearSelectedRows(grid, evt); } } if (selected && noUnselect){ // don't deselect the row } else { row.setSelected(!selected); if (row.isSelected === true) { grid.selection.lastSelectedRow = row; } else { grid.selection.selectAll = false; } grid.api.selection.raise.rowSelectionChanged(row, evt); } }, /** * @ngdoc function * @name shiftSelect * @methodOf ui.grid.selection.service:uiGridSelectionService * @description selects a group of rows from the last selected row using the shift key * @param {Grid} grid grid object * @param {GridRow} clicked row * @param {Event} event object if raised from an event * @param {bool} multiSelect if false, does nothing this is for multiSelect only */ shiftSelect: function (grid, row, evt, multiSelect) { if (!multiSelect) { return; } var selectedRows = service.getSelectedRows(grid); var fromRow = selectedRows.length > 0 ? grid.renderContainers.body.visibleRowCache.indexOf(grid.selection.lastSelectedRow) : 0; var toRow = grid.renderContainers.body.visibleRowCache.indexOf(row); //reverse select direction if (fromRow > toRow) { var tmp = fromRow; fromRow = toRow; toRow = tmp; } var changedRows = []; for (var i = fromRow; i <= toRow; i++) { var rowToSelect = grid.renderContainers.body.visibleRowCache[i]; if (rowToSelect) { if ( !rowToSelect.isSelected && rowToSelect.enableSelection !== false ){ rowToSelect.setSelected(true); grid.selection.lastSelectedRow = rowToSelect; service.decideRaiseSelectionEvent( grid, rowToSelect, changedRows, evt ); } } } service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); }, /** * @ngdoc function * @name getSelectedRows * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Returns all the selected rows * @param {Grid} grid grid object */ getSelectedRows: function (grid) { return grid.rows.filter(function (row) { return row.isSelected; }); }, /** * @ngdoc function * @name clearSelectedRows * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Clears all selected rows * @param {Grid} grid grid object * @param {Event} event object if raised from an event */ clearSelectedRows: function (grid, evt) { var changedRows = []; service.getSelectedRows(grid).forEach(function (row) { if ( row.isSelected ){ row.setSelected(false); service.decideRaiseSelectionEvent( grid, row, changedRows, evt ); } }); service.decideRaiseSelectionBatchEvent( grid, changedRows, evt ); grid.selection.selectAll = false; }, /** * @ngdoc function * @name decideRaiseSelectionEvent * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Decides whether to raise a single event or a batch event * @param {Grid} grid grid object * @param {GridRow} row row that has changed * @param {array} changedRows an array to which we can append the changed * @param {Event} event object if raised from an event * row if we're doing batch events */ decideRaiseSelectionEvent: function( grid, row, changedRows, evt ){ if ( !grid.options.enableSelectionBatchEvent ){ grid.api.selection.raise.rowSelectionChanged(row, evt); } else { changedRows.push(row); } }, /** * @ngdoc function * @name raiseSelectionEvent * @methodOf ui.grid.selection.service:uiGridSelectionService * @description Decides whether we need to raise a batch event, and * raises it if we do. * @param {Grid} grid grid object * @param {array} changedRows an array of changed rows, only populated * @param {Event} event object if raised from an event * if we're doing batch events */ decideRaiseSelectionBatchEvent: function( grid, changedRows, evt ){ if ( changedRows.length > 0 ){ grid.api.selection.raise.rowSelectionChangedBatch(changedRows, evt); } } }; return service; }]); /** * @ngdoc directive * @name ui.grid.selection.directive:uiGridSelection * @element div * @restrict A * * @description Adds selection features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.selection']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-selection></div> </div> </file> </example> */ module.directive('uiGridSelection', ['uiGridSelectionConstants', 'uiGridSelectionService', '$templateCache', 'uiGridConstants', function (uiGridSelectionConstants, uiGridSelectionService, $templateCache, uiGridConstants) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridSelectionService.initializeGrid(uiGridCtrl.grid); if (uiGridCtrl.grid.options.enableRowHeaderSelection) { var selectionRowHeaderDef = { name: uiGridSelectionConstants.selectionRowHeaderColName, displayName: '', width: uiGridCtrl.grid.options.selectionRowHeaderWidth, minWidth: 10, cellTemplate: 'ui-grid/selectionRowHeader', headerCellTemplate: 'ui-grid/selectionHeaderCell', enableColumnResizing: false, enableColumnMenu: false, exporterSuppressExport: true, allowCellFocus: true }; uiGridCtrl.grid.addRowHeaderColumn(selectionRowHeaderDef); } var processorSet = false; var processSelectableRows = function( rows ){ rows.forEach(function(row){ row.enableSelection = uiGridCtrl.grid.options.isRowSelectable(row); }); return rows; }; var updateOptions = function(){ if (uiGridCtrl.grid.options.isRowSelectable !== angular.noop && processorSet !== true) { uiGridCtrl.grid.registerRowsProcessor(processSelectableRows, 500); processorSet = true; } }; updateOptions(); var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback( updateOptions, [uiGridConstants.dataChange.OPTIONS] ); $scope.$on( '$destroy', dataChangeDereg); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); module.directive('uiGridSelectionRowHeaderButtons', ['$templateCache', 'uiGridSelectionService', 'gridUtil', function ($templateCache, uiGridSelectionService, gridUtil) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/selectionRowHeaderButtons'), scope: true, require: '^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { var self = uiGridCtrl.grid; $scope.selectButtonClick = selectButtonClick; // On IE, prevent mousedowns on the select button from starting a selection. // If this is not done and you shift+click on another row, the browser will select a big chunk of text if (gridUtil.detectBrowser() === 'ie') { $elm.on('mousedown', selectButtonMouseDown); } function selectButtonClick(row, evt) { evt.stopPropagation(); if (evt.shiftKey) { uiGridSelectionService.shiftSelect(self, row, evt, self.options.multiSelect); } else if (evt.ctrlKey || evt.metaKey) { uiGridSelectionService.toggleRowSelection(self, row, evt, self.options.multiSelect, self.options.noUnselect); } else { uiGridSelectionService.toggleRowSelection(self, row, evt, (self.options.multiSelect && !self.options.modifierKeysToMultiSelect), self.options.noUnselect); } } function selectButtonMouseDown(evt) { if (evt.ctrlKey || evt.shiftKey) { evt.target.onselectstart = function () { return false; }; window.setTimeout(function () { evt.target.onselectstart = null; }, 0); } } } }; }]); module.directive('uiGridSelectionSelectAllButtons', ['$templateCache', 'uiGridSelectionService', function ($templateCache, uiGridSelectionService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/selectionSelectAllButtons'), scope: false, link: function($scope, $elm, $attrs, uiGridCtrl) { var self = $scope.col.grid; $scope.headerButtonClick = function(row, evt) { if ( self.selection.selectAll ){ uiGridSelectionService.clearSelectedRows(self, evt); if ( self.options.noUnselect ){ self.api.selection.selectRowByVisibleIndex(0, evt); } self.selection.selectAll = false; } else { if ( self.options.multiSelect ){ self.api.selection.selectAllVisibleRows(evt); self.selection.selectAll = true; } } }; } }; }]); /** * @ngdoc directive * @name ui.grid.selection.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used * for the grid row */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService', function ($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-row-selected': row.isSelected}"; } else { newNgClass = "{'ui-grid-row-selected': row.isSelected}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.selection.directive:uiGridCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridCell to provide selection feature */ module.directive('uiGridCell', ['$compile', 'uiGridConstants', 'uiGridSelectionConstants', 'gridUtil', '$parse', 'uiGridSelectionService', '$timeout', function ($compile, uiGridConstants, uiGridSelectionConstants, gridUtil, $parse, uiGridSelectionService, $timeout) { return { priority: -200, // run after default uiGridCell directive restrict: 'A', require: '?^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var touchStartTime = 0; var touchTimeout = 300; // Bind to keydown events in the render container if (uiGridCtrl.grid.api.cellNav) { uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) { if (rowCol === null || rowCol.row !== $scope.row || rowCol.col !== $scope.col) { return; } if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); $scope.$apply(); } // uiGridCellNavService.scrollToIfNecessary(uiGridCtrl.grid, rowCol.row, rowCol.col); }); } //$elm.bind('keydown', function (evt) { // if (evt.keyCode === 32 && $scope.col.colDef.name === "selectionRowHeaderCol") { // uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); // $scope.$apply(); // } //}); var selectCells = function(evt){ // if we get a click, then stop listening for touchend $elm.off('touchend', touchEnd); if (evt.shiftKey) { uiGridSelectionService.shiftSelect($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect); } else if (evt.ctrlKey || evt.metaKey) { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, $scope.grid.options.multiSelect, $scope.grid.options.noUnselect); } else { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); } $scope.$apply(); // don't re-enable the touchend handler for a little while - some devices generate both, and it will // take a little while to move your hand from the mouse to the screen if you have both modes of input $timeout(function() { $elm.on('touchend', touchEnd); }, touchTimeout); }; var touchStart = function(evt){ touchStartTime = (new Date()).getTime(); // if we get a touch event, then stop listening for click $elm.off('click', selectCells); }; var touchEnd = function(evt) { var touchEndTime = (new Date()).getTime(); var touchTime = touchEndTime - touchStartTime; if (touchTime < touchTimeout ) { // short touch selectCells(evt); } // don't re-enable the click handler for a little while - some devices generate both, and it will // take a little while to move your hand from the screen to the mouse if you have both modes of input $timeout(function() { $elm.on('click', selectCells); }, touchTimeout); }; function registerRowSelectionEvents() { if ($scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection) { $elm.addClass('ui-grid-disable-selection'); $elm.on('touchstart', touchStart); $elm.on('touchend', touchEnd); $elm.on('click', selectCells); $scope.registered = true; } } function deregisterRowSelectionEvents() { if ($scope.registered){ $elm.removeClass('ui-grid-disable-selection'); $elm.off('touchstart', touchStart); $elm.off('touchend', touchEnd); $elm.off('click', selectCells); $scope.registered = false; } } registerRowSelectionEvents(); // register a dataChange callback so that we can change the selection configuration dynamically // if the user changes the options var dataChangeDereg = $scope.grid.registerDataChangeCallback( function() { if ( $scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection && !$scope.registered ){ registerRowSelectionEvents(); } else if ( ( !$scope.grid.options.enableRowSelection || !$scope.grid.options.enableFullRowSelection ) && $scope.registered ){ deregisterRowSelectionEvents(); } }, [uiGridConstants.dataChange.OPTIONS] ); $elm.on( '$destroy', dataChangeDereg); } }; }]); module.directive('uiGridGridFooter', ['$compile', 'uiGridConstants', 'gridUtil', function ($compile, uiGridConstants, gridUtil) { return { restrict: 'EA', replace: true, priority: -1000, require: '^uiGrid', scope: true, compile: function ($elm, $attrs) { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if (!uiGridCtrl.grid.options.showGridFooter) { return; } gridUtil.getTemplate('ui-grid/gridFooterSelectedItems') .then(function (contents) { var template = angular.element(contents); var newElm = $compile(template)($scope); angular.element($elm[0].getElementsByClassName('ui-grid-grid-footer')[0]).append(newElm); }); }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.treeBase * @description * * # ui.grid.treeBase * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides base tree handling functions that are shared by other features, notably grouping * and treeView. It provides a tree view of the data, with nodes in that * tree and leaves. * * Design information: * ------------------- * * The raw data that is provided must come with a $$treeLevel on any non-leaf node. Grouping will create * these on all the group header rows, treeView will expect these to be set in the raw data by the user. * TreeBase will run a rowsProcessor that: * - builds `treeBase.tree` out of the provided rows * - permits a recursive sort of the tree * - maintains the expand/collapse state of each node * - provides the expand/collapse all button and the expand/collapse buttons * - maintains the count of children for each node * * Each row is updated with a link to the tree node that represents it. Refer {@link ui.grid.treeBase.grid:treeBase.tree tree documentation} * for information. * * TreeBase adds information to the rows * - treeLevel: if present and > -1 tells us the level (level 0 is the top level) * - treeNode: pointer to the node in the grid.treeBase.tree that refers * to this row, allowing us to manipulate the state * * Since the logic is baked into the rowsProcessors, it should get triggered whenever * row order or filtering or anything like that is changed. We recall the expanded state * across invocations of the rowsProcessors by the reference to the treeNode on the individual * rows. We rebuild the tree itself quite frequently, when we do this we use the saved treeNodes to * get the state, but we overwrite the other data in that treeNode. * * By default rows are collapsed, which means all data rows have their visible property * set to false, and only level 0 group rows are set to visible. * * We rely on the rowsProcessors to do the actual expanding and collapsing, so we set the flags we want into * grid.treeBase.tree, then call refresh. This is because we can't easily change the visible * row cache without calling the processors, and once we've built the logic into the rowProcessors we may as * well use it all the time. * * Tree base provides sorting (on non-grouped columns). * * Sorting works in two passes. The standard sorting is performed for any columns that are important to building * the tree (for example, any grouped columns). Then after the tree is built, a recursive tree sort is performed * for the remaining sort columns (including the original sort) - these columns are sorted within each tree level * (so all the level 1 nodes are sorted, then all the level 2 nodes within each level 1 node etc). * * To achieve this we make use of the `ignoreSort` property on the sort configuration. The parent feature (treeView or grouping) * must provide a rowsProcessor that runs with very low priority (typically in the 60-65 range), and that sets * the `ignoreSort`on any sort that it wants to run on the tree. TreeBase will clear the ignoreSort on all sorts - so it * will turn on any sorts that haven't run. It will then call a recursive sort on the tree. * * Tree base provides treeAggregation. It checks the treeAggregation configuration on each column, and aggregates based on * the logic provided as it builds the tree. Footer aggregation from the uiGrid core should not be used with treeBase aggregation, * since it operates on all visible rows, as opposed to to leaf nodes only. Setting `showColumnFooter: true` will show the * treeAggregations in the column footer. Aggregation information will be collected in the format: * * ``` * { * type: 'count', * value: 4, * label: 'count: ', * rendered: 'count: 4' * } * ``` * * A callback is provided to format the value once it is finalised (aka a valueFilter). * * <br/> * <br/> * * <div doc-module-components="ui.grid.treeBase"></div> */ var module = angular.module('ui.grid.treeBase', ['ui.grid']); /** * @ngdoc object * @name ui.grid.treeBase.constant:uiGridTreeBaseConstants * * @description constants available in treeBase module. * * These constants are manually copied into grouping and treeView, * as I haven't found a way to simply include them, and it's not worth * investing time in for something that changes very infrequently. * */ module.constant('uiGridTreeBaseConstants', { featureName: "treeBase", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.treeBase.service:uiGridTreeBaseService * * @description Services for treeBase feature */ /** * @ngdoc object * @name ui.grid.treeBase.api:ColumnDef * * @description ColumnDef for tree feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter', function ($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) { var service = { initializeGrid: function (grid, $scope) { //add feature namespace and any properties to grid for needed /** * @ngdoc object * @name ui.grid.treeBase.grid:treeBase * * @description Grid properties and functions added for treeBase */ grid.treeBase = {}; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name numberLevels * * @description Total number of tree levels currently used, calculated by the rowsProcessor by * retaining the highest tree level it sees */ grid.treeBase.numberLevels = 0; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name expandAll * * @description Whether or not the expandAll box is selected */ grid.treeBase.expandAll = false; /** * @ngdoc property * @propertyOf ui.grid.treeBase.grid:treeBase * @name tree * * @description Tree represented as a nested array that holds the state of each node, along with a * pointer to the row. The array order is material - we will display the children in the order * they are stored in the array * * Each node stores: * * - the state of this node * - an array of children of this node * - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree) * - the number of children of this node * - aggregation information calculated from the nodes * * ``` * [{ * state: 'expanded', * row: <reference to row>, * parentRow: null, * aggregations: [{ * type: 'count', * col: <gridCol>, * value: 2, * label: 'count: ', * rendered: 'count: 2' * }], * children: [ * { * state: 'expanded', * row: <reference to row>, * parentRow: <reference to row>, * aggregations: [{ * type: 'count', * col: '<gridCol>, * value: 4, * label: 'count: ', * rendered: 'count: 4' * }], * children: [ * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }, * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> } * ] * }, * { * state: 'collapsed', * row: <reference to row>, * parentRow: <reference to row>, * aggregations: [{ * type: 'count', * col: <gridCol>, * value: 3, * label: 'count: ', * rendered: 'count: 3' * }], * children: [ * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> }, * { state: 'collapsed', row: <reference to row>, parentRow: <reference to row> }, * { state: 'expanded', row: <reference to row>, parentRow: <reference to row> } * ] * } * ] * }, {<another level 0 node maybe>} ] * ``` * Missing state values are false - meaning they aren't expanded. * * This is used because the rowProcessors run every time the grid is refreshed, so * we'd lose the expanded state every time the grid was refreshed. This instead gives * us a reliable lookup that persists across rowProcessors. * * This tree is rebuilt every time we run the rowsProcessors. Since each row holds a pointer * to it's tree node we can persist expand/collapse state across calls to rowsProcessor, we discard * all transient information on the tree (children, childCount) and recalculate it * */ grid.treeBase.tree = {}; service.defaultGridOptions(grid.options); grid.registerRowsProcessor(service.treeRows, 410); grid.registerColumnBuilder( service.treeBaseColumnBuilder ); service.createRowHeader( grid ); /** * @ngdoc object * @name ui.grid.treeBase.api:PublicApi * * @description Public Api for treeBase feature */ var publicApi = { events: { treeBase: { /** * @ngdoc event * @eventOf ui.grid.treeBase.api:PublicApi * @name rowExpanded * @description raised whenever a row is expanded. If you are dynamically * rendering your tree you can listen to this event, and then retrieve * the children of this row and load them into the grid data. * * When the data is loaded the grid will automatically refresh to show these new rows * * <pre> * gridApi.treeBase.on.rowExpanded(scope,function(row){}) * </pre> * @param {gridRow} row the row that was expanded. You can also * retrieve the grid from this row with row.grid */ rowExpanded: {}, /** * @ngdoc event * @eventOf ui.grid.treeBase.api:PublicApi * @name rowCollapsed * @description raised whenever a row is collapsed. Doesn't really have * a purpose at the moment, included for symmetry * * <pre> * gridApi.treeBase.on.rowCollapsed(scope,function(row){}) * </pre> * @param {gridRow} row the row that was collapsed. You can also * retrieve the grid from this row with row.grid */ rowCollapsed: {} } }, methods: { treeBase: { /** * @ngdoc function * @name expandAllRows * @methodOf ui.grid.treeBase.api:PublicApi * @description Expands all tree rows */ expandAllRows: function () { service.expandAllRows(grid); }, /** * @ngdoc function * @name collapseAllRows * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse all tree rows */ collapseAllRows: function () { service.collapseAllRows(grid); }, /** * @ngdoc function * @name toggleRowTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description call expand if the row is collapsed, collapse if it is expanded * @param {gridRow} row the row you wish to toggle */ toggleRowTreeState: function (row) { service.toggleRowTreeState(grid, row); }, /** * @ngdoc function * @name expandRow * @methodOf ui.grid.treeBase.api:PublicApi * @description expand the immediate children of the specified row * @param {gridRow} row the row you wish to expand */ expandRow: function (row) { service.expandRow(grid, row); }, /** * @ngdoc function * @name expandRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description expand all children of the specified row * @param {gridRow} row the row you wish to expand */ expandRowChildren: function (row) { service.expandRowChildren(grid, row); }, /** * @ngdoc function * @name collapseRow * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse the specified row. When * you expand the row again, all grandchildren will retain their state * @param {gridRow} row the row you wish to collapse */ collapseRow: function ( row ) { service.collapseRow(grid, row); }, /** * @ngdoc function * @name collapseRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description collapse all children of the specified row. When * you expand the row again, all grandchildren will be collapsed * @param {gridRow} row the row you wish to collapse children for */ collapseRowChildren: function ( row ) { service.collapseRowChildren(grid, row); }, /** * @ngdoc function * @name getTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description Get the tree state for this grid, * used by the saveState feature * Returned treeState as an object * `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }` * where expandedState is a hash of row uid and the current expanded state * * @returns {object} tree state * * TODO - this needs work - we need an identifier that persists across instantiations, * not uid. This really means we need a row identity defined, but that won't work for * grouping. Perhaps this needs to be moved up to treeView and grouping, rather than * being in base. */ getTreeExpandedState: function () { return { expandedState: service.getTreeState(grid) }; }, /** * @ngdoc function * @name setTreeState * @methodOf ui.grid.treeBase.api:PublicApi * @description Set the expanded states of the tree * @param {object} config the config you want to apply, in the format * provided by getTreeState */ setTreeState: function ( config ) { service.setTreeState( grid, config ); }, /** * @ngdoc function * @name getRowChildren * @methodOf ui.grid.treeBase.api:PublicApi * @description Get the children of the specified row * @param {GridRow} row the row you want the children of * @returns {Array} array of children of this row, the children * are all gridRows */ getRowChildren: function ( row ){ return row.treeNode.children.map( function( childNode ){ return childNode.row; }); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.treeBase.api:GridOptions * * @description GridOptions for treeBase feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name treeRowHeaderBaseWidth * @propertyOf ui.grid.treeBase.api:GridOptions * @description Base width of the tree header, provides for a single level of tree. This * is incremented by `treeIndent` for each extra level * <br/>Defaults to 30 */ gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 30; /** * @ngdoc object * @name treeIndent * @propertyOf ui.grid.treeBase.api:GridOptions * @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing, * but will make the tree row header wider * <br/>Defaults to 10 */ gridOptions.treeIndent = gridOptions.treeIndent || 10; /** * @ngdoc object * @name showTreeRowHeader * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to false, don't create the row header. Youll need to programatically control the expand * states * <br/>Defaults to true */ gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false; /** * @ngdoc object * @name showTreeExpandNoChildren * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to true, show the expand/collapse button even if there are no * children of a node. You'd use this if you're planning to dynamically load the children * * <br/>Defaults to true, grouping overrides to false */ gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false; /** * @ngdoc object * @name treeRowHeaderAlwaysVisible * @propertyOf ui.grid.treeBase.api:GridOptions * @description If set to true, row header even if there are no tree nodes * * <br/>Defaults to true */ gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false; /** * @ngdoc object * @name treeCustomAggregations * @propertyOf ui.grid.treeBase.api:GridOptions * @description Define custom aggregation functions. The properties of this object will be * aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu. * If a function defined here uses the same name as one of the native aggregations, this one will take precedence. * The object format is: * * <pre> * { * aggregationName: { * label: (optional) string, * aggregationFn: function( aggregation, fieldValue, numValue, row ){...}, * finalizerFn: (optional) function( aggregation ){...} * }, * mean: { * label: 'mean', * aggregationFn: function( aggregation, fieldValue, numValue ){ * aggregation.count = (aggregation.count || 1) + 1; * aggregation.sum = (aggregation.sum || 0) + numValue; * }, * finalizerFn: function( aggregation ){ * aggregation.value = aggregation.sum / aggregation.count * } * } * } * </pre> * * <br/>The `finalizerFn` may be used to manipulate the value before rendering, or to * apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be * rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate * the label and the value. * * <br/>Defaults to {} */ gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {}; }, /** * @ngdoc function * @name treeBaseColumnBuilder * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Sets the tree defaults based on the columnDefs * * @param {object} colDef columnDef we're basing on * @param {GridCol} col the column we're to update * @param {object} gridOptions the options we should use * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved */ treeBaseColumnBuilder: function (colDef, col, gridOptions) { /** * @ngdoc object * @name customTreeAggregationFn * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom function that aggregates rows into some form of * total. Aggregations run row-by-row, the function needs to be capable of * creating a running total. * * The function will be provided the aggregation item (in which you can store running * totals), the row value that is to be aggregated, and that same row value converted to * a number (most aggregations work on numbers) * @example * <pre> * customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){ * // calculates the average of the squares of the values * if ( typeof(aggregation.count) === 'undefined' ){ * aggregation.count = 0; * } * aggregation.count++; * * if ( !isNaN(numValue) ){ * if ( typeof(aggregation.total) === 'undefined' ){ * aggregation.total = 0; * } * aggregation.total = aggregation.total + numValue * numValue; * } * * aggregation.value = aggregation.total / aggregation.count; * } * </pre> * <br/>Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together. */ if ( typeof(colDef.customTreeAggregationFn) !== 'undefined' ){ col.treeAggregationFn = colDef.customTreeAggregationFn; } /** * @ngdoc object * @name treeAggregationType * @propertyOf ui.grid.treeBase.api:ColumnDef * @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column. * Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the * name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}. * * <pre> * treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM, * } * </pre> * * If you are using aggregations you should either: * * - also use grouping, in which case the aggregations are displayed in the group header, OR * - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and * treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false` * in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations * * <br/>Takes precendence over a treeAggregationFn, the two options should not be used together. * <br/>Defaults to undefined. */ if ( typeof(colDef.treeAggregationType) !== 'undefined' ){ col.treeAggregation = { type: colDef.treeAggregationType }; if ( typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined' ){ col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn; col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn; col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label; } else if ( typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined' ){ col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn; col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label; } } /** * @ngdoc object * @name treeAggregationLabel * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom label to use for this aggregation. If provided we don't use native i18n. */ if ( typeof(colDef.treeAggregationLabel) !== 'undefined' ){ if (typeof(col.treeAggregation) === 'undefined' ){ col.treeAggregation = {}; } col.treeAggregation.label = colDef.treeAggregationLabel; } /** * @ngdoc object * @name treeAggregationUpdateEntity * @propertyOf ui.grid.treeBase.api:ColumnDef * @description Store calculated aggregations into the entity, allowing them * to be displayed in the grid using a standard cellTemplate. This defaults to true, * if you are using grouping then you shouldn't set it to false, as then the aggregations won't * display. * * If you are using treeView in most cases you'll want to set this to true. This will result in * getCellValue returning the aggregation rather than whatever was stored in the cell attribute on * the entity. If you want to render the underlying entity value (and do something else with the aggregation) * then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue. * * <br/>Defaults to true * * @example * <pre> * gridOptions.columns = [{ * name: 'myCol', * treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM }, * treeAggregationUpdateEntity: true * cellTemplate: '<div>{{row.entity.myCol + " " + row.treeNode.aggregations[0].rendered}}</div>' * }]; * </pre> */ col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false; /** * @ngdoc object * @name customTreeAggregationFinalizerFn * @propertyOf ui.grid.treeBase.api:ColumnDef * @description A custom function that populates aggregation.rendered, this is called when * a particular aggregation has been fully calculated, and we want to render the value. * * With the native aggregation options we just concatenate `aggregation.label` and * `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label * or the value, you can do so with this function. This function will be called after the * the default `finalizerFn`. * * @example * <pre> * customTreeAggregationFinalizerFn = function ( aggregation ){ * aggregation.rendered = aggregation.label + aggregation.value / 100 + '%'; * } * </pre> * <br/>Defaults to undefined. */ if ( typeof(col.customTreeAggregationFinalizerFn) === 'undefined' ){ col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn; } }, /** * @ngdoc function * @name createRowHeader * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Create the rowHeader. If treeRowHeaderAlwaysVisible then * set it to visible, otherwise set it to invisible * * @param {Grid} grid grid object */ createRowHeader: function( grid ){ var rowHeaderColumnDef = { name: uiGridTreeBaseConstants.rowHeaderColName, displayName: '', width: grid.options.treeRowHeaderBaseWidth, minWidth: 10, cellTemplate: 'ui-grid/treeBaseRowHeader', headerCellTemplate: 'ui-grid/treeBaseHeaderCell', enableColumnResizing: false, enableColumnMenu: false, exporterSuppressExport: true, allowCellFocus: true }; rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible; grid.addRowHeaderColumn( rowHeaderColumnDef ); }, /** * @ngdoc function * @name expandAllRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands all nodes in the tree * * @param {Grid} grid grid object */ expandAllRows: function (grid) { grid.treeBase.tree.forEach( function( node ) { service.setAllNodes( grid, node, uiGridTreeBaseConstants.EXPANDED); }); grid.treeBase.expandAll = true; grid.queueGridRefresh(); }, /** * @ngdoc function * @name collapseAllRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses all nodes in the tree * * @param {Grid} grid grid object */ collapseAllRows: function (grid) { grid.treeBase.tree.forEach( function( node ) { service.setAllNodes( grid, node, uiGridTreeBaseConstants.COLLAPSED); }); grid.treeBase.expandAll = false; grid.queueGridRefresh(); }, /** * @ngdoc function * @name setAllNodes * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Works through a subset of grid.treeBase.rowExpandedStates, setting * all child nodes (and their descendents) of the provided node to the given state. * * Calls itself recursively on all nodes so as to achieve this. * * @param {Grid} grid the grid we're operating on (so we can raise events) * @param {object} treeNode a node in the tree that we want to update * @param {string} targetState the state we want to set it to */ setAllNodes: function (grid, treeNode, targetState) { if ( typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState ){ treeNode.state = targetState; if ( targetState === uiGridTreeBaseConstants.EXPANDED ){ grid.api.treeBase.raise.rowExpanded(treeNode.row); } else { grid.api.treeBase.raise.rowCollapsed(treeNode.row); } } // set all child nodes if ( treeNode.children ){ treeNode.children.forEach(function( childNode ){ service.setAllNodes(grid, childNode, targetState); }); } }, /** * @ngdoc function * @name toggleRowTreeState * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Toggles the expand or collapse state of this grouped row, if * it's a parent row * * @param {Grid} grid grid object * @param {GridRow} row the row we want to toggle */ toggleRowTreeState: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED){ service.collapseRow(grid, row); } else { service.expandRow(grid, row); } grid.queueGridRefresh(); }, /** * @ngdoc function * @name expandRow * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands this specific row, showing only immediate children. * * @param {Grid} grid grid object * @param {GridRow} row the row we want to expand */ expandRow: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if ( row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){ row.treeNode.state = uiGridTreeBaseConstants.EXPANDED; grid.api.treeBase.raise.rowExpanded(row); grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); } }, /** * @ngdoc function * @name expandRowChildren * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Expands this specific row, showing all children. * * @param {Grid} grid grid object * @param {GridRow} row the row we want to expand */ expandRowChildren: function ( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED); grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree); grid.queueGridRefresh(); }, /** * @ngdoc function * @name collapseRow * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses this specific row * * @param {Grid} grid grid object * @param {GridRow} row the row we want to collapse */ collapseRow: function( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } if ( row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED ){ row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED; grid.treeBase.expandAll = false; grid.api.treeBase.raise.rowCollapsed(row); grid.queueGridRefresh(); } }, /** * @ngdoc function * @name collapseRowChildren * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Collapses this specific row and all children * * @param {Grid} grid grid object * @param {GridRow} row the row we want to collapse */ collapseRowChildren: function( grid, row ){ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){ return; } service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED); grid.treeBase.expandAll = false; grid.queueGridRefresh(); }, /** * @ngdoc function * @name allExpanded * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Returns true if all rows are expanded, false * if they're not. Walks the tree to determine this. Used * to set the expandAll state. * * If the node has no children, then return true (it's immaterial * whether it is expanded). If the node has children, then return * false if this node is collapsed, or if any child node is not all expanded * * @param {object} tree the grid to check * @returns {boolean} whether or not the tree is all expanded */ allExpanded: function( tree ){ var allExpanded = true; tree.forEach( function( node ){ if ( !service.allExpandedInternal( node ) ){ allExpanded = false; } }); return allExpanded; }, allExpandedInternal: function( treeNode ){ if ( treeNode.children && treeNode.children.length > 0 ){ if ( treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){ return false; } var allExpanded = true; treeNode.children.forEach( function( node ){ if ( !service.allExpandedInternal( node ) ){ allExpanded = false; } }); return allExpanded; } else { return true; } }, /** * @ngdoc function * @name treeRows * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description The rowProcessor that adds the nodes to the tree, and sets the visible * state of each row based on it's parent state * * Assumes it is always called after the sorting processor, and the grouping processor if there is one. * Performs any tree sorts itself after having built the tree * * Processes all the rows in order, setting the group level based on the $$treeLevel in the associated * entity, and setting the visible state based on the parent's state. * * Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly * sized. * * Aggregates if necessary along the way. * * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor * @returns {array} the updated rows */ treeRows: function( renderableRows ) { if (renderableRows.length === 0){ return renderableRows; } var grid = this; var currentLevel = 0; var currentState = uiGridTreeBaseConstants.EXPANDED; var parents = []; grid.treeBase.tree = service.createTree( grid, renderableRows ); service.updateRowHeaderWidth( grid ); service.sortTree( grid ); service.fixFilter( grid ); return service.renderTree( grid.treeBase.tree ); }, /** * @ngdoc function * @name createOrUpdateRowHeaderWidth * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Calculates the rowHeader width. * * If rowHeader is always present, updates the width. * * If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there * should be one, then creates or removes it as appropriate, with the created rowHeader having the * right width. * * If there's never a rowHeader then never creates one: `showTreeRowHeader: false` * * @param {Grid} grid the grid we want to set the row header on */ updateRowHeaderWidth: function( grid ){ var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName); var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0); if ( rowHeader && newWidth !== rowHeader.width ){ rowHeader.width = newWidth; grid.queueRefresh(); } var newVisibility = true; if ( grid.options.showTreeRowHeader === false ){ newVisibility = false; } if ( grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0 ){ newVisibility = false; } if ( rowHeader.visible !== newVisibility ) { rowHeader.visible = newVisibility; rowHeader.colDef.visible = newVisibility; grid.queueGridRefresh(); } }, /** * @ngdoc function * @name renderTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates an array of rows based on the tree, exporting only * the visible nodes and leaves * * @param {array} nodeList the list of nodes - can be grid.treeBase.tree, or can be node.children when * we're calling recursively * @returns {array} renderable rows */ renderTree: function( nodeList ){ var renderableRows = []; nodeList.forEach( function ( node ){ if ( node.row.visible ){ renderableRows.push( node.row ); } if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){ renderableRows = renderableRows.concat( service.renderTree( node.children ) ); } }); return renderableRows; }, /** * @ngdoc function * @name createTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates a tree from the renderableRows * * @param {Grid} grid the grid * @param {array} renderableRows the rows we want to create a tree from * @returns {object} the tree we've build */ createTree: function( grid, renderableRows ) { var currentLevel = -1; var parents = []; var currentState; grid.treeBase.tree = []; grid.treeBase.numberLevels = 0; var aggregations = service.getAggregations( grid ); var createNode = function( row ){ if ( typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel ){ row.treeLevel = row.entity.$$treeLevel; } if ( row.treeLevel <= currentLevel ){ // pop any levels that aren't parents of this level, formatting the aggregation at the same time while ( row.treeLevel <= currentLevel ){ var lastParent = parents.pop(); service.finaliseAggregations( lastParent ); currentLevel--; } // reset our current state based on the new parent, set to expanded if this is a level 0 node if ( parents.length > 0 ){ currentState = service.setCurrentState(parents); } else { currentState = uiGridTreeBaseConstants.EXPANDED; } } // aggregate if this is a leaf node if ( ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ) && row.visible ){ service.aggregate( grid, row, parents ); } // add this node to the tree service.addOrUseNode(grid, row, parents, aggregations); if ( typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 ){ parents.push(row); currentLevel++; currentState = service.setCurrentState(parents); } // update the tree number of levels, so we can set header width if we need to if ( grid.treeBase.numberLevels < row.treeLevel + 1){ grid.treeBase.numberLevels = row.treeLevel + 1; } }; renderableRows.forEach( createNode ); // finalise remaining aggregations while ( parents.length > 0 ){ var lastParent = parents.pop(); service.finaliseAggregations( lastParent ); } return grid.treeBase.tree; }, /** * @ngdoc function * @name addOrUseNode * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Creates a tree node for this row. If this row already has a treeNode * recorded against it, preserves the state, but otherwise overwrites the data. * * @param {grid} grid the grid we're operating on * @param {gridRow} row the row we want to set * @param {array} parents an array of the parents this row should have * @param {array} aggregationBase empty aggregation information * @returns {undefined} updates the parents array, updates the row to have a treeNode, and updates the * grid.treeBase.tree */ addOrUseNode: function( grid, row, parents, aggregationBase ){ var newAggregations = []; aggregationBase.forEach( function(aggregation){ newAggregations.push(service.buildAggregationObject(aggregation.col)); }); var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] }; if ( row.treeNode ){ newNode.state = row.treeNode.state; } if ( parents.length > 0 ){ newNode.parentRow = parents[parents.length - 1]; } row.treeNode = newNode; if ( parents.length === 0 ){ grid.treeBase.tree.push( newNode ); } else { parents[parents.length - 1].treeNode.children.push( newNode ); } }, /** * @ngdoc function * @name setCurrentState * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Looks at the parents array to determine our current state. * If any node in the hierarchy is collapsed, then return collapsed, otherwise return * expanded. * * @param {array} parents an array of the parents this row should have * @returns {string} the state we should be setting to any nodes we see */ setCurrentState: function( parents ){ var currentState = uiGridTreeBaseConstants.EXPANDED; parents.forEach( function(parent){ if ( parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){ currentState = uiGridTreeBaseConstants.COLLAPSED; } }); return currentState; }, /** * @ngdoc function * @name sortTree * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Performs a recursive sort on the tree nodes, sorting the * children of each node and putting them back into the children array. * * Before doing this it turns back on all the sortIgnore - things that were previously * ignored we process now. Since we're sorting within the nodes, presumably anything * that was already sorted is how we derived the nodes, we can keep those sorts too. * * We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed * nodes * * @param {Grid} grid the grid to get the aggregation information from * @returns {array} the aggregation information */ sortTree: function( grid ){ grid.columns.forEach( function( column ) { if ( column.sort && column.sort.ignoreSort ){ delete column.sort.ignoreSort; } }); grid.treeBase.tree = service.sortInternal( grid, grid.treeBase.tree ); }, sortInternal: function( grid, treeList ){ var rows = treeList.map( function( node ){ return node.row; }); rows = rowSorter.sort( grid, rows, grid.columns ); var treeNodes = rows.map( function( row ){ return row.treeNode; }); treeNodes.forEach( function( node ){ if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){ node.children = service.sortInternal( grid, node.children ); } }); return treeNodes; }, /** * @ngdoc function * @name fixFilter * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description After filtering has run, we need to go back through the tree * and make sure the parent rows are always visible if any of the child rows * are visible (filtering may make a child visible, but the parent may not * match the filter criteria) * * This has a risk of being computationally expensive, we do it by walking * the tree and remembering whether there are any invisible nodes on the * way down. * * @param {Grid} grid the grid to fix filters on */ fixFilter: function( grid ){ var parentsVisible; grid.treeBase.tree.forEach( function( node ){ if ( node.children && node.children.length > 0 ){ parentsVisible = node.row.visible; service.fixFilterInternal( node.children, parentsVisible ); } }); }, fixFilterInternal: function( nodes, parentsVisible) { nodes.forEach( function( node ){ if ( node.row.visible && !parentsVisible ){ service.setParentsVisible( node ); parentsVisible = true; } if ( node.children && node.children.length > 0 ){ if ( service.fixFilterInternal( node.children, ( parentsVisible && node.row.visible ) ) ) { parentsVisible = true; } } }); return parentsVisible; }, setParentsVisible: function( node ){ while ( node.parentRow ){ node.parentRow.visible = true; node = node.parentRow.treeNode; } }, /** * @ngdoc function * @name buildAggregationObject * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Build the object which is stored on the column for holding meta-data about the aggregation. * This method should only be called with columns which have an aggregation. * * @param {Column} the column which this object relates to * @returns {object} {col: Column object, label: string, type: string (optional)} */ buildAggregationObject: function( column ){ var newAggregation = { col: column }; if ( column.treeAggregation && column.treeAggregation.type ){ newAggregation.type = column.treeAggregation.type; } if ( column.treeAggregation && column.treeAggregation.label ){ newAggregation.label = column.treeAggregation.label; } return newAggregation; }, /** * @ngdoc function * @name getAggregations * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Looks through the grid columns to find those with aggregations, * and collates the aggregation information into an array, returns that array * * @param {Grid} grid the grid to get the aggregation information from * @returns {array} the aggregation information */ getAggregations: function( grid ){ var aggregateArray = []; grid.columns.forEach( function(column){ if ( typeof(column.treeAggregationFn) !== 'undefined' ){ aggregateArray.push( service.buildAggregationObject(column) ); if ( grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation ){ // Add aggregation object for footer column.treeFooterAggregation = service.buildAggregationObject(column); column.aggregationType = service.treeFooterAggregationType; } } }); return aggregateArray; }, /** * @ngdoc function * @name aggregate * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Accumulate the data from this row onto the aggregations for each parent * * Iterate over the parents, then iterate over the aggregations for each of those parents, * and perform the aggregation for each individual aggregation * * @param {Grid} grid grid object * @param {GridRow} row the row we want to set grouping visibility on * @param {array} parents the parents that we would want to aggregate onto */ aggregate: function( grid, row, parents ){ if ( parents.length === 0 && row.treeNode && row.treeNode.aggregations ){ row.treeNode.aggregations.forEach(function(aggregation){ // Calculate aggregations for footer even if there are no grouped rows if ( typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ) { var fieldValue = grid.getCellValue(row, aggregation.col); var numValue = Number(fieldValue); aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row); } }); } parents.forEach( function( parent, index ){ if ( parent.treeNode.aggregations ){ parent.treeNode.aggregations.forEach( function( aggregation ){ var fieldValue = grid.getCellValue(row, aggregation.col); var numValue = Number(fieldValue); aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row); if ( index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ){ aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row); } }); } }); }, // Aggregation routines - no doco needed as self evident nativeAggregations: function() { var nativeAggregations = { count: { label: i18nService.get().aggregation.count, menuTitle: i18nService.get().grouping.aggregate_count, aggregationFn: function (aggregation, fieldValue, numValue) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = 1; } else { aggregation.value++; } } }, sum: { label: i18nService.get().aggregation.sum, menuTitle: i18nService.get().grouping.aggregate_sum, aggregationFn: function( aggregation, fieldValue, numValue ) { if (!isNaN(numValue)) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = numValue; } else { aggregation.value += numValue; } } } }, min: { label: i18nService.get().aggregation.min, menuTitle: i18nService.get().grouping.aggregate_min, aggregationFn: function( aggregation, fieldValue, numValue ) { if (typeof(aggregation.value) === 'undefined') { aggregation.value = fieldValue; } else { if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) { aggregation.value = fieldValue; } } } }, max: { label: i18nService.get().aggregation.max, menuTitle: i18nService.get().grouping.aggregate_max, aggregationFn: function( aggregation, fieldValue, numValue ){ if ( typeof(aggregation.value) === 'undefined' ){ aggregation.value = fieldValue; } else { if ( typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)){ aggregation.value = fieldValue; } } } }, avg: { label: i18nService.get().aggregation.avg, menuTitle: i18nService.get().grouping.aggregate_avg, aggregationFn: function( aggregation, fieldValue, numValue ){ if ( typeof(aggregation.count) === 'undefined' ){ aggregation.count = 1; } else { aggregation.count++; } if ( isNaN(numValue) ){ return; } if ( typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined' ){ aggregation.value = numValue; aggregation.sum = numValue; } else { aggregation.sum += numValue; aggregation.value = aggregation.sum / aggregation.count; } } } }; return nativeAggregations; }, /** * @ngdoc function * @name finaliseAggregation * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Helper function used to finalize aggregation nodes and footer cells * * @param {gridRow} row the parent we're finalising * @param {aggregation} the aggregation object manipulated by the aggregationFn */ finaliseAggregation: function(row, aggregation){ if ( aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity[ '$$' + aggregation.col.uid ]) !== 'undefined' ){ angular.extend( aggregation, row.entity[ '$$' + aggregation.col.uid ]); } if ( typeof(aggregation.col.treeAggregationFinalizerFn) === 'function' ){ aggregation.col.treeAggregationFinalizerFn( aggregation ); } if ( typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function' ){ aggregation.col.customTreeAggregationFinalizerFn( aggregation ); } if ( typeof(aggregation.rendered) === 'undefined' ){ aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value; } }, /** * @ngdoc function * @name finaliseAggregations * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Format the data from the aggregation into the rendered text * e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'. * * As part of this we call any formatting callback routines we've been provided. * * We write our aggregation out to the row.entity if treeAggregationUpdateEntity is * set on the column - we don't overwrite any information that's already there, we append * to it so that grouping can have set the groupVal beforehand without us overwriting it. * * We need to copy the data from the row.entity first before we finalise the aggregation, * we need that information for the finaliserFn * * @param {gridRow} row the parent we're finalising */ finaliseAggregations: function( row ){ if ( typeof(row.treeNode.aggregations) === 'undefined' ){ return; } row.treeNode.aggregations.forEach( function( aggregation ) { service.finaliseAggregation(row, aggregation); if ( aggregation.col.treeAggregationUpdateEntity ){ var aggregationCopy = {}; angular.forEach( aggregation, function( value, key ){ if ( aggregation.hasOwnProperty(key) && key !== 'col' ){ aggregationCopy[key] = value; } }); row.entity[ '$$' + aggregation.col.uid ] = aggregationCopy; } }); }, /** * @ngdoc function * @name treeFooterAggregationType * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Uses the tree aggregation functions and finalizers to set the * column footer aggregations. * * @param {rows} visible rows. not used, but accepted to match signature of GridColumn.aggregationType * @param {gridColumn} the column we are finalizing */ treeFooterAggregationType: function( rows, column ) { service.finaliseAggregation(undefined, column.treeFooterAggregation); if ( typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null ){ // The was apparently no aggregation performed (perhaps this is a grouped column return ''; } return column.treeFooterAggregation.rendered; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons * @element div * * @description Provides the expand/collapse button on rows */ module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService', function ($templateCache, uiGridTreeBaseService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'), scope: true, require: '^uiGrid', link: function($scope, $elm, $attrs, uiGridCtrl) { var self = uiGridCtrl.grid; $scope.treeButtonClick = function(row, evt) { uiGridTreeBaseService.toggleRowTreeState(self, row, evt); }; } }; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons * @element div * * @description Provides the expand/collapse all button */ module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService', function ($templateCache, uiGridTreeBaseService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'), scope: false, link: function($scope, $elm, $attrs, uiGridCtrl) { var self = $scope.col.grid; $scope.headerButtonClick = function(row, evt) { if ( self.treeBase.expandAll ){ uiGridTreeBaseService.collapseAllRows(self, evt); } else { uiGridTreeBaseService.expandAllRows(self, evt); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.treeBase.directive:uiGridViewport * @element div * * @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row */ module.directive('uiGridViewport', ['$compile', 'uiGridConstants', 'gridUtil', '$parse', function ($compile, uiGridConstants, gridUtil, $parse) { return { priority: -200, // run after default directive scope: false, compile: function ($elm, $attrs) { var rowRepeatDiv = angular.element($elm.children().children()[0]); var existingNgClass = rowRepeatDiv.attr("ng-class"); var newNgClass = ''; if ( existingNgClass ) { newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}"; } else { newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}"; } rowRepeatDiv.attr("ng-class", newNgClass); return { pre: function ($scope, $elm, $attrs, controllers) { }, post: function ($scope, $elm, $attrs, controllers) { } }; } }; }]); })(); (function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.treeView * @description * * # ui.grid.treeView * * <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div> * * This module provides a tree view of the data that it is provided, with nodes in that * tree and leaves. Unlike grouping, the tree is an inherent property of the data and must * be provided with your data array. * * Design information: * ------------------- * * TreeView uses treeBase for the underlying functionality, and is a very thin wrapper around * that logic. Most of the design information has now moved to treebase. * <br/> * <br/> * * <div doc-module-components="ui.grid.treeView"></div> */ var module = angular.module('ui.grid.treeView', ['ui.grid', 'ui.grid.treeBase']); /** * @ngdoc object * @name ui.grid.treeView.constant:uiGridTreeViewConstants * * @description constants available in treeView module, this includes * all the constants declared in the treeBase module (these are manually copied * as there isn't an easy way to include constants in another constants file, and * we don't want to make users include treeBase) * */ module.constant('uiGridTreeViewConstants', { featureName: "treeView", rowHeaderColName: 'treeBaseRowHeaderCol', EXPANDED: 'expanded', COLLAPSED: 'collapsed', aggregation: { COUNT: 'count', SUM: 'sum', MAX: 'max', MIN: 'min', AVG: 'avg' } }); /** * @ngdoc service * @name ui.grid.treeView.service:uiGridTreeViewService * * @description Services for treeView features */ module.service('uiGridTreeViewService', ['$q', 'uiGridTreeViewConstants', 'uiGridTreeBaseConstants', 'uiGridTreeBaseService', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', function ($q, uiGridTreeViewConstants, uiGridTreeBaseConstants, uiGridTreeBaseService, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants) { var service = { initializeGrid: function (grid, $scope) { uiGridTreeBaseService.initializeGrid( grid, $scope ); /** * @ngdoc object * @name ui.grid.treeView.grid:treeView * * @description Grid properties and functions added for treeView */ grid.treeView = {}; grid.registerRowsProcessor(service.adjustSorting, 60); /** * @ngdoc object * @name ui.grid.treeView.api:PublicApi * * @description Public Api for treeView feature */ var publicApi = { events: { treeView: { } }, methods: { treeView: { } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { //default option to true unless it was explicitly set to false /** * @ngdoc object * @name ui.grid.treeView.api:GridOptions * * @description GridOptions for treeView feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} * * Many tree options are set on treeBase, make sure to look at that feature in * conjunction with these options. */ /** * @ngdoc object * @name enableTreeView * @propertyOf ui.grid.treeView.api:GridOptions * @description Enable row tree view for entire grid. * <br/>Defaults to true */ gridOptions.enableTreeView = gridOptions.enableTreeView !== false; }, /** * @ngdoc function * @name adjustSorting * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService * @description Trees cannot be sorted the same as flat lists of rows - * trees are sorted recursively within each level - so the children of each * node are sorted, but not the full set of rows. * * To achieve this, we suppress the normal sorting by setting ignoreSort on * each of the sort columns. When the treeBase rowsProcessor runs it will then * unignore these, and will perform a recursive sort against the tree that it builds. * * @param {array} renderableRows the rows that we need to pass on through * @returns {array} renderableRows that we passed on through */ adjustSorting: function( renderableRows ) { var grid = this; grid.columns.forEach( function( column ){ if ( column.sort ){ column.sort.ignoreSort = true; } }); return renderableRows; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.treeView.directive:uiGridTreeView * @element div * @restrict A * * @description Adds treeView features to grid * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.treeView']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; $scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data }; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-tree-view></div> </div> </file> </example> */ module.directive('uiGridTreeView', ['uiGridTreeViewConstants', 'uiGridTreeViewService', '$templateCache', function (uiGridTreeViewConstants, uiGridTreeViewService, $templateCache) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { if (uiGridCtrl.grid.options.enableTreeView !== false){ uiGridTreeViewService.initializeGrid(uiGridCtrl.grid, $scope); } }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); })(); angular.module('ui.grid').run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('ui-grid/ui-grid-filter', "<div class=\"ui-grid-filter-container\" ng-repeat=\"colFilter in col.filters\" ng-class=\"{'ui-grid-filter-cancel-button-hidden' : colFilter.disableCancelFilterButton === true }\"><div ng-if=\"colFilter.type !== 'select'\"><input type=\"text\" class=\"ui-grid-filter-input\" ng-model=\"colFilter.term\" ng-attr-placeholder=\"{{colFilter.placeholder || ''}}\"><div class=\"ui-grid-filter-button\" ng-click=\"colFilter.term = null\" ng-if=\"!colFilter.disableCancelFilterButton\"><i class=\"ui-grid-icon-cancel\" ng-show=\"colFilter.term !== undefined && colFilter.term !== null && colFilter.term !== ''\">&nbsp;</i></div></div><div ng-if=\"colFilter.type === 'select'\"><select class=\"ui-grid-filter-select\" ng-model=\"colFilter.term\" ng-attr-placeholder=\"{{colFilter.placeholder || ''}}\" ng-options=\"option.value as option.label for option in colFilter.selectOptions\"><option value=\"\"></option></select><div class=\"ui-grid-filter-button-select\" ng-click=\"colFilter.term = null\" ng-if=\"!colFilter.disableCancelFilterButton\"><i class=\"ui-grid-icon-cancel\" ng-show=\"colFilter.term !== undefined && colFilter.term != null\">&nbsp;</i></div></div></div>" ); $templateCache.put('ui-grid/ui-grid-footer', "<div class=\"ui-grid-footer-panel ui-grid-footer-aggregates-row\"><div class=\"ui-grid-footer ui-grid-footer-viewport\"><div class=\"ui-grid-footer-canvas\"><div class=\"ui-grid-footer-cell-wrapper\" ng-style=\"colContainer.headerCellWrapperStyle()\"><div class=\"ui-grid-footer-cell-row\"><div ng-repeat=\"col in colContainer.renderedColumns track by col.uid\" ui-grid-footer-cell col=\"col\" render-index=\"$index\" class=\"ui-grid-footer-cell ui-grid-clearfix\"></div></div></div></div></div></div>" ); $templateCache.put('ui-grid/ui-grid-grid-footer', "<div class=\"ui-grid-footer-info ui-grid-grid-footer\"><span>{{'search.totalItems' | t}} {{grid.rows.length}}</span> <span ng-if=\"grid.renderContainers.body.visibleRowCache.length !== grid.rows.length\" class=\"ngLabel\">({{\"search.showingItems\" | t}} {{grid.renderContainers.body.visibleRowCache.length}})</span></div>" ); $templateCache.put('ui-grid/ui-grid-group-panel', "<div class=\"ui-grid-group-panel\"><div ui-t=\"groupPanel.description\" class=\"description\" ng-show=\"groupings.length == 0\"></div><ul ng-show=\"groupings.length > 0\" class=\"ngGroupList\"><li class=\"ngGroupItem\" ng-repeat=\"group in configGroups\"><span class=\"ngGroupElement\"><span class=\"ngGroupName\">{{group.displayName}} <span ng-click=\"removeGroup($index)\" class=\"ngRemoveGroup\">x</span></span> <span ng-hide=\"$last\" class=\"ngGroupArrow\"></span></span></li></ul></div>" ); $templateCache.put('ui-grid/ui-grid-header', "<div class=\"ui-grid-header\"><div class=\"ui-grid-top-panel\"><div class=\"ui-grid-header-viewport\"><div class=\"ui-grid-header-canvas\"><div class=\"ui-grid-header-cell-wrapper\" ng-style=\"colContainer.headerCellWrapperStyle()\"><div class=\"ui-grid-header-cell-row\"><div class=\"ui-grid-header-cell ui-grid-clearfix\" ng-repeat=\"col in colContainer.renderedColumns track by col.uid\" ui-grid-header-cell col=\"col\" render-index=\"$index\"></div></div></div></div></div></div></div>" ); $templateCache.put('ui-grid/ui-grid-menu-button', "<div class=\"ui-grid-menu-button\" ng-click=\"toggleMenu()\"><div class=\"ui-grid-icon-container\"><i class=\"ui-grid-icon-menu\">&nbsp;</i></div><div ui-grid-menu menu-items=\"menuItems\"></div></div>" ); $templateCache.put('ui-grid/ui-grid-no-header', "<div class=\"ui-grid-top-panel\"></div>" ); $templateCache.put('ui-grid/ui-grid-row', "<div ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" ui-grid-cell></div>" ); $templateCache.put('ui-grid/ui-grid', "<div ui-i18n=\"en\" class=\"ui-grid\"><!-- TODO (c0bra): add \"scoped\" attr here, eventually? --><style ui-grid-style>.grid{{ grid.id }} {\n" + " /* Styles for the grid */\n" + " }\n" + "\n" + " .grid{{ grid.id }} .ui-grid-row, .grid{{ grid.id }} .ui-grid-cell, .grid{{ grid.id }} .ui-grid-cell .ui-grid-vertical-bar {\n" + " height: {{ grid.options.rowHeight }}px;\n" + " }\n" + "\n" + " .grid{{ grid.id }} .ui-grid-row:last-child .ui-grid-cell {\n" + " border-bottom-width: {{ ((grid.getTotalRowHeight() < grid.getViewportHeight()) && '1') || '0' }}px;\n" + " }\n" + "\n" + " {{ grid.verticalScrollbarStyles }}\n" + " {{ grid.horizontalScrollbarStyles }}\n" + "\n" + " /*\n" + " .ui-grid[dir=rtl] .ui-grid-viewport {\n" + " padding-left: {{ grid.verticalScrollbarWidth }}px;\n" + " }\n" + " */\n" + "\n" + " {{ grid.customStyles }}</style><div class=\"ui-grid-contents-wrapper\"><div ui-grid-menu-button ng-if=\"grid.options.enableGridMenu\"></div><div ng-if=\"grid.hasLeftContainer()\" style=\"width: 0\" ui-grid-pinned-container=\"'left'\"></div><div ui-grid-render-container container-id=\"'body'\" col-container-name=\"'body'\" row-container-name=\"'body'\" bind-scroll-horizontal=\"true\" bind-scroll-vertical=\"true\" enable-horizontal-scrollbar=\"grid.options.enableHorizontalScrollbar\" enable-vertical-scrollbar=\"grid.options.enableVerticalScrollbar\"></div><div ng-if=\"grid.hasRightContainer()\" style=\"width: 0\" ui-grid-pinned-container=\"'right'\"></div><div ui-grid-grid-footer ng-if=\"grid.options.showGridFooter\"></div><div ui-grid-column-menu ng-if=\"grid.options.enableColumnMenus\"></div><div ng-transclude></div></div></div>" ); $templateCache.put('ui-grid/uiGridCell', "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\">{{COL_FIELD CUSTOM_FILTERS}}</div>" ); $templateCache.put('ui-grid/uiGridColumnMenu', "<div class=\"ui-grid-column-menu\"><div ui-grid-menu menu-items=\"menuItems\"><!-- <div class=\"ui-grid-column-menu\">\n" + " <div class=\"inner\" ng-show=\"menuShown\">\n" + " <ul>\n" + " <div ng-show=\"grid.options.enableSorting\">\n" + " <li ng-click=\"sortColumn($event, asc)\" ng-class=\"{ 'selected' : col.sort.direction == asc }\"><i class=\"ui-grid-icon-sort-alt-up\"></i> Sort Ascending</li>\n" + " <li ng-click=\"sortColumn($event, desc)\" ng-class=\"{ 'selected' : col.sort.direction == desc }\"><i class=\"ui-grid-icon-sort-alt-down\"></i> Sort Descending</li>\n" + " <li ng-show=\"col.sort.direction\" ng-click=\"unsortColumn()\"><i class=\"ui-grid-icon-cancel\"></i> Remove Sort</li>\n" + " </div>\n" + " </ul>\n" + " </div>\n" + " </div> --></div></div>" ); $templateCache.put('ui-grid/uiGridFooterCell', "<div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><div>{{ col.getAggregationText() + ( col.getAggregationValue() CUSTOM_FILTERS ) }}</div></div>" ); $templateCache.put('ui-grid/uiGridHeaderCell', "<div ng-class=\"{ 'sortable': sortable }\"><!-- <div class=\"ui-grid-vertical-bar\">&nbsp;</div> --><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\" title=\"TOOLTIP\"><span>{{ col.displayName CUSTOM_FILTERS }}</span> <span ui-grid-visible=\"col.sort.direction\" ng-class=\"{ 'ui-grid-icon-up-dir': col.sort.direction == asc, 'ui-grid-icon-down-dir': col.sort.direction == desc, 'ui-grid-icon-blank': !col.sort.direction }\">&nbsp;</span></div><div class=\"ui-grid-column-menu-button\" ng-if=\"grid.options.enableColumnMenus && !col.isRowHeader && col.colDef.enableColumnMenu !== false\" ng-click=\"toggleMenu($event)\" ng-class=\"{'ui-grid-column-menu-button-last-col': isLastCol}\"><i class=\"ui-grid-icon-angle-down\">&nbsp;</i></div><div ui-grid-filter></div></div>" ); $templateCache.put('ui-grid/uiGridMenu', "<div class=\"ui-grid-menu\" ng-if=\"shown\"><div class=\"ui-grid-menu-mid\" ng-show=\"shownMid\"><div class=\"ui-grid-menu-inner\"><ul class=\"ui-grid-menu-items\"><li ng-repeat=\"item in menuItems\" ui-grid-menu-item action=\"item.action\" name=\"item.title\" active=\"item.active\" icon=\"item.icon\" shown=\"item.shown\" context=\"item.context\" template-url=\"item.templateUrl\" leave-open=\"item.leaveOpen\"></li></ul></div></div></div>" ); $templateCache.put('ui-grid/uiGridMenuItem', "<li class=\"ui-grid-menu-item\" ng-click=\"itemAction($event, title)\" ng-show=\"itemShown()\" ng-class=\"{ 'ui-grid-menu-item-active' : active() }\"><i ng-class=\"icon\"></i> {{ name }}</li>" ); $templateCache.put('ui-grid/uiGridRenderContainer', "<div class=\"ui-grid-render-container\" ng-style=\"{ 'margin-left': colContainer.getMargin('left') + 'px', 'margin-right': colContainer.getMargin('right') + 'px' }\"><div ui-grid-header></div><div ui-grid-viewport></div><div ng-if=\"colContainer.needsHScrollbarPlaceholder()\" class=\"ui-grid-scrollbar-placeholder\" style=\"height:{{colContainer.grid.scrollbarHeight}}px\"></div><div ui-grid-footer ng-if=\"grid.options.showColumnFooter\"></div></div>" ); $templateCache.put('ui-grid/uiGridViewport', "<div class=\"ui-grid-viewport\" ng-style=\"colContainer.getViewportStyle()\"><div class=\"ui-grid-canvas\"><div ng-repeat=\"(rowRenderIndex, row) in rowContainer.renderedRows track by $index\" class=\"ui-grid-row\" ng-style=\"Viewport.rowStyle(rowRenderIndex)\"><div ui-grid-row=\"row\" row-render-index=\"rowRenderIndex\"></div></div></div></div>" ); $templateCache.put('ui-grid/cellEditor', "<div><form name=\"inputForm\"><input type=\"INPUT_TYPE\" ng-class=\"'colt' + col.uid\" ui-grid-editor ng-model=\"MODEL_COL_FIELD\"></form></div>" ); $templateCache.put('ui-grid/dropdownEditor', "<div><form name=\"inputForm\"><select ng-class=\"'colt' + col.uid\" ui-grid-edit-dropdown ng-model=\"MODEL_COL_FIELD\" ng-options=\"field[editDropdownIdLabel] as field[editDropdownValueLabel] CUSTOM_FILTERS for field in editDropdownOptionsArray\"></select></form></div>" ); $templateCache.put('ui-grid/fileChooserEditor', "<div><form name=\"inputForm\"><input ng-class=\"'colt' + col.uid\" ui-grid-edit-file-chooser type=\"file\" id=\"files\" name=\"files[]\" ng-model=\"MODEL_COL_FIELD\"></form></div>" ); $templateCache.put('ui-grid/expandableRow', "<div ui-grid-expandable-row ng-if=\"expandableRow.shouldRenderExpand()\" class=\"expandableRow\" style=\"float:left; margin-top: 1px; margin-bottom: 1px\" ng-style=\"{width: (grid.renderContainers.body.getCanvasWidth()) + 'px'\n" + " , height: grid.options.expandableRowHeight + 'px'}\"></div>" ); $templateCache.put('ui-grid/expandableRowHeader', "<div class=\"ui-grid-row-header-cell ui-grid-expandable-buttons-cell\"><div class=\"ui-grid-cell-contents\"><i ng-class=\"{ 'ui-grid-icon-plus-squared' : !row.isExpanded, 'ui-grid-icon-minus-squared' : row.isExpanded }\" ng-click=\"grid.api.expandable.toggleRowExpansion(row.entity)\"></i></div></div>" ); $templateCache.put('ui-grid/expandableScrollFiller', "<div ng-if=\"expandableRow.shouldRenderFiller()\" ng-class=\"{scrollFiller:true, scrollFillerClass:(colContainer.name === 'body')}\" ng-style=\"{ width: (grid.getViewportWidth()) + 'px',\n" + " height: grid.options.expandableRowHeight + 2 + 'px', 'margin-left': grid.options.rowHeader.rowHeaderWidth + 'px' }\"><i class=\"ui-grid-icon-spin5 ui-grid-animate-spin\" ng-style=\"{ 'margin-top': ( grid.options.expandableRowHeight/2 - 5) + 'px',\n" + " 'margin-left' : ((grid.getViewportWidth() - grid.options.rowHeader.rowHeaderWidth)/2 - 5) + 'px' }\"></i></div>" ); $templateCache.put('ui-grid/expandableTopRowHeader', "<div class=\"ui-grid-row-header-cell ui-grid-expandable-buttons-cell\"><div class=\"ui-grid-cell-contents\"><i ng-class=\"{ 'ui-grid-icon-plus-squared' : !grid.expandable.expandedAll, 'ui-grid-icon-minus-squared' : grid.expandable.expandedAll }\" ng-click=\"grid.api.expandable.toggleAllRows()\"></i></div></div>" ); $templateCache.put('ui-grid/csvLink', "<span class=\"ui-grid-exporter-csv-link-span\"><a href=\"data:text/csv;charset=UTF-8,CSV_CONTENT\" download=\"FILE_NAME\">LINK_LABEL</a></span>" ); $templateCache.put('ui-grid/importerMenuItem', "<li class=\"ui-grid-menu-item\"><form><input class=\"ui-grid-importer-file-chooser\" type=\"file\" id=\"files\" name=\"files[]\"></form></li>" ); $templateCache.put('ui-grid/importerMenuItemContainer', "<div ui-grid-importer-menu-item></div>" ); $templateCache.put('ui-grid/pagination', "<div class=\"ui-grid-pager-panel\" ui-grid-pager ng-show=\"grid.options.enablePaginationControls\"><div class=\"ui-grid-pager-container\"><div class=\"ui-grid-pager-control\"><button type=\"button\" ng-click=\"paginationApi.seek(1)\" ng-disabled=\"cantPageBackward()\"><div class=\"first-triangle\"><div class=\"first-bar\"></div></div></button> <button type=\"button\" ng-click=\"paginationApi.previousPage()\" ng-disabled=\"cantPageBackward()\"><div class=\"first-triangle prev-triangle\"></div></button> <input type=\"number\" ng-model=\"grid.options.paginationCurrentPage\" min=\"1\" max=\"{{ paginationApi.getTotalPages() }}\" required> <span class=\"ui-grid-pager-max-pages-number\" ng-show=\"paginationApi.getTotalPages() > 0\">/ {{ paginationApi.getTotalPages() }}</span> <button type=\"button\" ng-click=\"paginationApi.nextPage()\" ng-disabled=\"cantPageForward()\"><div class=\"last-triangle next-triangle\"></div></button> <button type=\"button\" ng-click=\"paginationApi.seek(paginationApi.getTotalPages())\" ng-disabled=\"cantPageToLast()\"><div class=\"last-triangle\"><div class=\"last-bar\"></div></div></button></div><div class=\"ui-grid-pager-row-count-picker\"><select ng-model=\"grid.options.paginationPageSize\" ng-options=\"o as o for o in grid.options.paginationPageSizes\"></select><span class=\"ui-grid-pager-row-count-label\">&nbsp;{{sizesLabel}}</span></div></div><div class=\"ui-grid-pager-count-container\"><div class=\"ui-grid-pager-count\"><span ng-show=\"grid.options.totalItems > 0\">{{showingLow}} - {{showingHigh}} {{paginationOf}} {{grid.options.totalItems}} {{totalItemsLabel}}</span></div></div></div>" ); $templateCache.put('ui-grid/columnResizer', "<div ui-grid-column-resizer ng-if=\"grid.options.enableColumnResizing\" class=\"ui-grid-column-resizer\" col=\"col\" position=\"right\" render-index=\"renderIndex\" unselectable=\"on\"></div>" ); $templateCache.put('ui-grid/gridFooterSelectedItems', "<span ng-if=\"grid.selection.selectedCount !== 0 && grid.options.enableFooterTotalSelected\">({{\"search.selectedItems\" | t}} {{grid.selection.selectedCount}})</span>" ); $templateCache.put('ui-grid/selectionHeaderCell', "<div><!-- <div class=\"ui-grid-vertical-bar\">&nbsp;</div> --><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><ui-grid-selection-select-all-buttons ng-if=\"grid.options.enableSelectAll\"></ui-grid-selection-select-all-buttons></div></div>" ); $templateCache.put('ui-grid/selectionRowHeader', "<div class=\"ui-grid-disable-selection\"><div class=\"ui-grid-cell-contents\"><ui-grid-selection-row-header-buttons></ui-grid-selection-row-header-buttons></div></div>" ); $templateCache.put('ui-grid/selectionRowHeaderButtons', "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" ng-click=\"selectButtonClick(row, $event)\">&nbsp;</div>" ); $templateCache.put('ui-grid/selectionSelectAllButtons', "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-click=\"headerButtonClick($event)\"></div>" ); $templateCache.put('ui-grid/treeBaseExpandAllButtons', "<div class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-icon-minus-squared': grid.treeBase.numberLevels > 0 && grid.treeBase.expandAll, 'ui-grid-icon-plus-squared': grid.treeBase.numberLevels > 0 && !grid.treeBase.expandAll}\" ng-click=\"headerButtonClick($event)\"></div>" ); $templateCache.put('ui-grid/treeBaseHeaderCell', "<div><div class=\"ui-grid-cell-contents\" col-index=\"renderIndex\"><ui-grid-tree-base-expand-all-buttons></ui-grid-tree-base-expand-all-buttons></div></div>" ); $templateCache.put('ui-grid/treeBaseRowHeader', "<div class=\"ui-grid-cell-contents\"><ui-grid-tree-base-row-header-buttons></ui-grid-tree-base-row-header-buttons></div>" ); $templateCache.put('ui-grid/treeBaseRowHeaderButtons', "<div class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-tree-base-header': row.treeLevel > -1 }\" ng-click=\"treeButtonClick(row, $event)\"><i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> &nbsp;</div>" ); }]);
js/jquery.js
MCavigli/BPAD_website
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.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||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(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 ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.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===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||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 fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.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},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.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=fb.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=fb.selectors={cacheLength:50,createPseudo:hb,match:X,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(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===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]||fb.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]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.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(cb,db).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("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).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 Z.test(a.nodeName)},input:function(a){return Y.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:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(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]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.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=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[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?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(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=[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(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(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 tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(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 vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(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?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(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 vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.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(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.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(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(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&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.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=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.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 m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.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=m._data(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=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(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},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.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]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(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=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.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+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(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+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{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":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.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=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,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||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.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 kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),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:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.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)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.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)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.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})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.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=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.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){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.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 Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(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}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.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?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
client/components/basic/MarkdownText.stories.js
iiet/iiet-chat
import React from 'react'; import MarkdownText from './MarkdownText'; export default { title: 'components/basic/MarkdownText', component: MarkdownText, }; export const Example = () => <MarkdownText content={` # h1 Heading ## h2 Heading ### h3 Heading #### h4 Heading ##### h5 Heading ###### h6 Heading ___ *This is bold text* _This is italic text_ ~Strikethrough~ + Lorem ipsum dolor sit amet + Consectetur adipiscing elit + Integer molestie lorem at massa 1. Lorem ipsum dolor sit amet 2. Consectetur adipiscing elit 3. Integer molestie lorem at massa \`rocket.chat();\` https://rocket.chat`} />;
src/docs/Example.js
xujihui1985/my-component
import React from 'react'; import PropTypes from 'prop-types'; import CodeExample from './CodeExample'; class Example extends React.Component { constructor(props) { super(props); this.state = { showCode: false }; } toggleCode = event => { event.preventDefault(); this.setState(prevState => { return { showCode: !prevState.showCode }; }); } render() { const { showCode } = this.state; const { code, description, name } = this.props.example; const ExampleComponent = require(`./examples/${this.props.componentName}/${name}`).default; return ( <div className="example"> {description && <h4>{description}</h4>} <ExampleComponent /> <p> <a href="#" onClick={this.toggleCode}> {showCode ? "Hide" : "Show"} Code </a> { showCode && (<CodeExample>{code}</CodeExample>) } </p> </div> ); } } Example.propTypes = { example: PropTypes.object.isRequired, componentName: PropTypes.string.isRequired, }; export default Example;
definitions/npm/expo-asset_v6.x.x/flow_v0.69.0-/test_expo-asset.js
splodingsocks/FlowTyped
// @flow import React from 'react'; import { it, describe } from 'flow-typed-test'; import { Asset } from 'expo-asset'; describe('static methods', () => { describe('loadAsync', () => { it('should passes when used properly', () => { Asset.loadAsync(1); Asset.loadAsync([1, 2]); }); it('should raise an error when call with invalid argument', () => { // $FlowExpectedError: first argument must be number or array if numbers Asset.loadAsync(''); Asset.loadAsync([ 1, // $FlowExpectedError: must be number '', ]); }); }); describe('fromURI', () => { it('should passes when used properly', () => { Asset.fromURI('uri').downloadAsync(); }); it('should raise an error when call with invalid argument', () => { // $FlowExpectedError: first argument must be a string Asset.fromURI(1); }); }); describe('fromModule', () => { it('should passes when used properly', () => { Asset.fromModule('uri').downloadAsync(); Asset.fromModule(1).downloadAsync(); }); it('should raise an error when call with invalid argument', () => { // $FlowExpectedError: first argument must be a string or a number Asset.fromModule(true); }); }); describe('fromMetadata', () => { it('should passes when used properly', () => { const requiredMeta = { hash: 'str', name: 'str', type: 'str', scales: [1, 2], httpServerLocation: 'str', }; Asset.fromMetadata(requiredMeta).downloadAsync(); Asset.fromMetadata({ width: 1, height: 1, uri: 'str', fileHashes: ['str'], fileUris: ['str'], ...requiredMeta, }).downloadAsync(); Asset.fromMetadata({ width: undefined, height: undefined, uri: undefined, fileHashes: undefined, fileUris: undefined, ...requiredMeta, }).downloadAsync(); }); it('should raise an error when call with invalid argument', () => { // $FlowExpectedError: first argument must be an object Asset.fromMetadata(true); // $FlowExpectedError: missing required props Asset.fromMetadata({}); }); }); }); describe('class properties', () => { const requiredAssetOptions = { name: 'str', type: 'str', uri: 'str', }; it('should passes when used properly', () => { const a = new Asset(requiredAssetOptions); const b = new Asset({ hash: 'string', width: 1, height: 1, ...requiredAssetOptions, }); const c = new Asset({ hash: null, width: null, height: null, ...requiredAssetOptions, }); }); });
src/js/components/error/UnexpectedError.js
choonchernlim/front-end-stack
// @flow import React from 'react'; import Typography from '@material-ui/core/Typography'; const UnexpectedError = () => ( <Typography variant="h3" gutterBottom> An unexpected error has occurred while trying to process the page. </Typography> ); export default UnexpectedError;
src/components/MuteButton.js
pixelcanvasio/pixelcanvas
/** * Created by arkeros on 31/5/17. * * @flow */ import React from 'react'; import { connect } from 'react-redux'; import FaVolumeUp from 'react-icons/lib/fa/volume-up'; import FaVolumeOff from 'react-icons/lib/fa/volume-off'; import FloatingActionButton from './FloatingActionButton'; import { toggleMute } from '../actions'; import type { State } from '../reducers'; const MutteButton = ({ onMute, mute }) => ( <FloatingActionButton onClick={onMute}> {mute ? <FaVolumeOff /> : <FaVolumeUp />} </FloatingActionButton> ); function mapStateToProps(state: State) { const { mute } = state.audio; return { mute }; } function mapDispatchToProps(dispatch) { return { onMute() { dispatch(toggleMute()); }, }; } export default connect(mapStateToProps, mapDispatchToProps)(MutteButton);
renderer/components/Onboarding/Steps/ConnectionDetails.js
LN-Zap/zap-desktop
import React from 'react' import PropTypes from 'prop-types' import { Box } from 'rebass/styled-components' import ConnectionDetailsManual from './ConnectionDetailsManual' import ConnectionDetailsString from './ConnectionDetailsString' import ConnectionDetailsContext from './ConnectionDetailsContext' import { FORM_TYPE_CONNECTION_STRING, FORM_TYPE_MANUAL } from './constants' class ConnectionDetails extends React.Component { state = { formType: null, } static propTypes = { clearStartLndError: PropTypes.func.isRequired, connectionCert: PropTypes.string, connectionHost: PropTypes.string, connectionMacaroon: PropTypes.string, connectionString: PropTypes.string, lndConnect: PropTypes.string, name: PropTypes.string, setConnectionCert: PropTypes.func.isRequired, setConnectionHost: PropTypes.func.isRequired, setConnectionMacaroon: PropTypes.func.isRequired, setConnectionString: PropTypes.func.isRequired, setLndconnect: PropTypes.func.isRequired, setName: PropTypes.func.isRequired, startLndCertError: PropTypes.string, startLndHostError: PropTypes.string, startLndMacaroonError: PropTypes.string, validateCert: PropTypes.func.isRequired, validateHost: PropTypes.func.isRequired, validateMacaroon: PropTypes.func.isRequired, wizardApi: PropTypes.object, wizardState: PropTypes.object, } componentDidMount() { const { connectionHost, connectionCert, connectionMacaroon } = this.props if (connectionHost || connectionCert || connectionMacaroon) { this.openModal(FORM_TYPE_MANUAL) } else { this.openModal(FORM_TYPE_CONNECTION_STRING) } } componentDidUpdate(prevProps, prevState) { const { lndConnect, setConnectionCert, setConnectionHost, setConnectionMacaroon, setConnectionString, setName, } = this.props const { formType } = this.state if (formType && formType !== prevState.formType && prevState.formType) { switch (formType) { case FORM_TYPE_CONNECTION_STRING: setConnectionCert(null) setConnectionHost(null) setConnectionMacaroon(null) setName(null) break case FORM_TYPE_MANUAL: setConnectionString(null) setName(null) break default: break } } if (lndConnect && lndConnect !== prevProps.lndConnect) { this.openModal(FORM_TYPE_CONNECTION_STRING) } } openModal = formType => { this.setState({ formType }) } render() { const { clearStartLndError, connectionCert, connectionHost, connectionMacaroon, connectionString, lndConnect, name, setConnectionCert, setConnectionHost, setConnectionMacaroon, setConnectionString, setLndconnect, setName, startLndCertError, startLndHostError, startLndMacaroonError, validateCert, validateHost, validateMacaroon, wizardApi, wizardState, } = this.props const { formType } = this.state if (!formType) { return null } return ( <Box css={` visibility: ${lndConnect ? 'hidden' : 'visible'}; `} width={1} > <ConnectionDetailsContext.Provider value={{ formType, openModal: this.openModal, }} > {formType === FORM_TYPE_CONNECTION_STRING ? ( <ConnectionDetailsString clearStartLndError={clearStartLndError} connectionString={connectionString} lndConnect={lndConnect} name={name} setConnectionString={setConnectionString} setLndconnect={setLndconnect} setName={setName} startLndCertError={startLndCertError} startLndHostError={startLndHostError} startLndMacaroonError={startLndMacaroonError} wizardApi={wizardApi} wizardState={wizardState} /> ) : ( <ConnectionDetailsManual clearStartLndError={clearStartLndError} connectionCert={connectionCert} connectionHost={connectionHost} connectionMacaroon={connectionMacaroon} connectionString={connectionString} lndConnect={lndConnect} name={name} setConnectionCert={setConnectionCert} setConnectionHost={setConnectionHost} setConnectionMacaroon={setConnectionMacaroon} setLndconnect={setLndconnect} setName={setName} startLndCertError={startLndCertError} startLndHostError={startLndHostError} startLndMacaroonError={startLndMacaroonError} validateCert={validateCert} validateHost={validateHost} validateMacaroon={validateMacaroon} wizardApi={wizardApi} wizardState={wizardState} /> )} </ConnectionDetailsContext.Provider> </Box> ) } } export default ConnectionDetails
app/components/Sites-list.js
L-A/Little-Jekyll
import React, { Component } from 'react'; import Site from './Site'; import Mousetrap from 'Mousetrap'; import EmptySitesList from './Empty-sites-list'; import Dispatcher from '../utils/front-end-dispatcher'; import Cycle from '../utils/cycle'; import { VelocityElement, VelocityTransitionGroup } from 'velocity-react'; var SitesList = React.createClass({ getInitialState: function() { Dispatcher.createCallback('updateSitesList', this.receiveSitesList); Dispatcher.createCallback('activityStarted', this.showActivity); Dispatcher.createCallback('activityStopped', this.stopActivity); return {sites: null, isActive: false, selectedSite: 0}; }, componentDidMount: function() { Dispatcher.send('getSitesList'); Mousetrap.bind('up', this.selectPrevious); Mousetrap.bind('down', this.selectNext); }, componentWillUnmount: function() { Mousetrap.unbind('up', this.selectNext); Mousetrap.unbind('down', this.selectPrevious); }, receiveSitesList: function( event, list ) { this.setState({sites: list}); }, showActivity: function() { this.setState({isActive:true}); }, stopActivity: function() { this.setState({isActive:false}) }, selectNext: function() { var nextIndex = Cycle(this.state.sites, this.state.selectedSite, 1); this.setSelection(nextIndex); }, selectPrevious: function() { var previousIndex = Cycle(this.state.sites, this.state.selectedSite, -1); this.setSelection(previousIndex); }, setSelection: function(index) { this.setState({selectedSite: index}); }, render: function () { if (this.state.sites != null && this.state.sites.length > 0) { var siteNodes = this.state.sites.map( function(data, mapIndex){ var selectMe = function (){this.setSelection(mapIndex)}; return ( <Site key={data.id} onClick={this.setSelection.bind(this, mapIndex)} selected={this.state.selectedSite == mapIndex} siteInfo={data}/> ); }, this) return( <VelocityTransitionGroup component="ul" className="sites-list" enter={{animation: "slideDown", stagger:25, duration: 300, easing: "easeInOutQuart"}} leave={{animation: "slideUp", easing: "easeInOutQuart", duration: 450, delay:175}}> {siteNodes} </VelocityTransitionGroup> ) } else { return ( <EmptySitesList isActive={this.state.isActive} sitesReceived={this.state.sites == null ? false : true} /> ); } } }) module.exports = SitesList;
ajax/libs/inferno-mobx/4.0.0-5/inferno-mobx.js
extend1994/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('mobx'), require('inferno'), require('inferno-create-class'), require('inferno-create-element'), require('hoist-non-inferno-statics')) : typeof define === 'function' && define.amd ? define(['exports', 'mobx', 'inferno', 'inferno-create-class', 'inferno-create-element', 'hoist-non-inferno-statics'], factory) : (factory((global.Inferno = global.Inferno || {}, global.Inferno.Mobx = global.Inferno.Mobx || {}),global.mobx,global.Inferno,global.Inferno,global.Inferno,global.hoistNonReactStatics)); }(this, (function (exports,mobx,inferno,infernoCreateClass,infernoCreateElement,hoistNonReactStatics) { 'use strict'; hoistNonReactStatics = hoistNonReactStatics && hoistNonReactStatics.hasOwnProperty('default') ? hoistNonReactStatics['default'] : hoistNonReactStatics; /** * @module Inferno-Shared */ /** TypeDoc Comment */ // This should be boolean and not reference to window.document var isBrowser$1 = !!(typeof window !== 'undefined' && window.document); // 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$1 = Array.isArray; function isStringOrNumber(o) { var type = typeof o; return type === 'string' || type === 'number'; } function isInvalid(o) { return isNull$1(o) || o === false || isTrue(o) || isUndefined$1(o); } function isNull$1(o) { return o === null; } function isTrue(o) { return o === true; } function isUndefined$1(o) { return o === void 0; } 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; } /** * @module Inferno-Clone-VNode */ /** TypeDoc Comment */ /* directClone is preferred over cloneVNode and used internally also. This function makes Inferno backwards compatible. And can be tree-shaked by modern bundlers Would be nice to combine this with directClone but could not do it without breaking change */ /** * Clones given virtual node by creating new instance of it * @param {VNode} vNodeToClone virtual node to be cloned * @param {Props=} props additional props for new virtual node * @param {...*} _children new children for new virtual node * @returns {VNode} new virtual node */ function cloneVNode(vNodeToClone, props) { var arguments$1 = arguments; var _children = [], len$2 = arguments.length - 2; while ( len$2-- > 0 ) { _children[ len$2 ] = arguments$1[ len$2 + 2 ]; } var children = _children; var childrenLen = _children.length; if (childrenLen > 0 && !isUndefined$1(_children[0])) { if (!props) { props = {}; } if (childrenLen === 1) { children = _children[0]; } if (!isUndefined$1(children)) { props.children = children; } } var newVNode; if (isArray$1(vNodeToClone)) { var tmpArray = []; for (var i = 0, len = vNodeToClone.length; i < len; i++) { tmpArray.push(inferno.directClone(vNodeToClone[i])); } newVNode = tmpArray; } else { var flags = vNodeToClone.flags; var className = vNodeToClone.className; var key = vNodeToClone.key; var ref = vNodeToClone.ref; if (props) { if (!isUndefined$1(props.className)) { className = props.className; } if (!isUndefined$1(props.ref)) { ref = props.ref; } if (!isUndefined$1(props.key)) { key = props.key; } } if (flags & 14 /* Component */) { newVNode = inferno.createComponentVNode(flags, vNodeToClone.type, !vNodeToClone.props && !props ? inferno.EMPTY_OBJ : combineFrom(vNodeToClone.props, props), key, ref); var newProps = newVNode.props; if (newProps) { var newChildren = newProps.children; // we need to also clone component children that are in props // as the children may also have been hoisted if (newChildren) { if (isArray$1(newChildren)) { var len$1 = newChildren.length; if (len$1 > 0) { var tmpArray$1 = []; for (var i$1 = 0; i$1 < len$1; i$1++) { var child = newChildren[i$1]; if (isStringOrNumber(child)) { tmpArray$1.push(child); } else if (!isInvalid(child) && child.flags) { tmpArray$1.push(inferno.directClone(child)); } } newProps.children = tmpArray$1; } } else if (newChildren.flags) { newProps.children = inferno.directClone(newChildren); } } } newVNode.children = null; } else if (flags & 993 /* Element */) { children = props && !isUndefined$1(props.children) ? props.children : vNodeToClone.children; newVNode = inferno.normalizeChildren(inferno.createVNode(flags, vNodeToClone.type, className, null, 1 /* HasInvalidChildren */, !vNodeToClone.props && !props ? inferno.EMPTY_OBJ : combineFrom(vNodeToClone.props, props), key, ref), children); } else if (flags & 16 /* Text */) { newVNode = inferno.createTextVNode(vNodeToClone.children); } } return inferno.normalizeProps(newVNode); } /** * @module Inferno-Shared */ /** TypeDoc Comment */ var NO_OP = '$NO_OP'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; // This should be boolean and not reference to window.document var isBrowser = !!(typeof window !== 'undefined' && window.document); // 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 isNullOrUndef(o) { return isUndefined(o) || isNull(o); } function isFunction(o) { return typeof o === 'function'; } function isString(o) { return typeof o === 'string'; } function isNull(o) { return o === null; } function isUndefined(o) { return o === void 0; } function isObject(o) { return typeof o === 'object'; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } /** * @module Inferno-Compat */ /** TypeDoc Comment */ function isValidElement(obj) { var isNotANullObject = isObject(obj) && isNull(obj) === false; if (isNotANullObject === false) { return false; } var flags = obj.flags; return (flags & (14 /* Component */ | 993 /* Element */)) > 0; } /** * @module Inferno-Compat */ /** * Inlined PropTypes, there is propType checking ATM. */ // tslint:disable-next-line:no-empty function proptype() { } proptype.isRequired = proptype; var getProptype = function () { return proptype; }; var PropTypes = { any: getProptype, array: proptype, arrayOf: getProptype, bool: proptype, checkPropTypes: function () { return null; }, element: getProptype, func: proptype, instanceOf: getProptype, node: getProptype, number: proptype, object: proptype, objectOf: getProptype, oneOf: getProptype, oneOfType: getProptype, shape: getProptype, string: proptype, symbol: proptype }; /** * This is a list of all SVG attributes that need special casing, * namespacing, or boolean value assignment. * * When adding attributes to this list, be sure to also add them to * the `possibleStandardNames` module to ensure casing and incorrect * name warnings. * * SVG Attributes List: * https://www.w3.org/TR/SVG/attindex.html * SMIL Spec: * https://www.w3.org/TR/smil */ var ATTRS = [ 'accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-constiant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'x-height', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xmlns:xlink', 'xml:lang', 'xml:space' ]; var SVGDOMPropertyConfig = {}; var CAMELIZE = /[\-\:]([a-z])/g; var capitalize = function (token) { return token[1].toUpperCase(); }; ATTRS.forEach(function (original) { var reactName = original.replace(CAMELIZE, capitalize); SVGDOMPropertyConfig[reactName] = original; }); /** * @module Inferno-Compat */ /** TypeDoc Comment */ var componentToDOMNodeMap = new Map(); inferno.options.findDOMNodeEnabled = true; function unmountComponentAtNode(container) { inferno.render(null, container); return true; } var ARR = []; var Children = { map: function map(children, fn, ctx) { if (isNullOrUndef(children)) { return children; } children = Children.toArray(children); if (ctx && ctx !== children) { fn = fn.bind(ctx); } return children.map(fn); }, forEach: function forEach(children, fn, ctx) { if (isNullOrUndef(children)) { return; } children = Children.toArray(children); if (ctx && ctx !== children) { fn = fn.bind(ctx); } for (var i = 0, len = children.length; i < len; i++) { fn(children[i], i, children); } }, count: function count(children) { children = Children.toArray(children); return children.length; }, only: function only(children) { children = Children.toArray(children); if (children.length !== 1) { throw new Error('Children.only() expects only one child.'); } return children[0]; }, toArray: function toArray$$1(children) { if (isNullOrUndef(children)) { return []; } return isArray(children) ? children : ARR.concat(children); } }; inferno.Component.prototype.isReactComponent = {}; var currentComponent = null; inferno.options.beforeRender = function (component) { currentComponent = component; }; inferno.options.afterRender = function () { currentComponent = null; }; var nextAfterMount = inferno.options.afterMount; inferno.options.afterMount = function (vNode) { if (inferno.options.findDOMNodeEnabled) { componentToDOMNodeMap.set(vNode.children, vNode.dom); } if (nextAfterMount) { nextAfterMount(vNode); } }; var nextAfterUpdate = inferno.options.afterUpdate; inferno.options.afterUpdate = function (vNode) { if (inferno.options.findDOMNodeEnabled) { componentToDOMNodeMap.set(vNode.children, vNode.dom); } if (nextAfterUpdate) { nextAfterUpdate(vNode); } }; var nextBeforeUnmount = inferno.options.beforeUnmount; inferno.options.beforeUnmount = function (vNode) { if (inferno.options.findDOMNodeEnabled) { componentToDOMNodeMap.delete(vNode.children); } if (nextBeforeUnmount) { nextBeforeUnmount(vNode); } }; var version = '15.4.2'; function normalizeProps$1(name, props) { if ((name === 'input' || name === 'textarea') && props.type !== 'radio' && props.onChange) { var type = props.type; var eventName; if (type === 'checkbox') { eventName = 'onclick'; } else if (type === 'file') { eventName = 'onchange'; } else { eventName = 'oninput'; } if (!props[eventName]) { props[eventName] = props.onChange; delete props.onChange; } } for (var prop in props) { if (prop === 'onDoubleClick') { props.onDblClick = props[prop]; delete props[prop]; } if (prop === 'htmlFor') { props.for = props[prop]; delete props[prop]; } var mappedProp = SVGDOMPropertyConfig[prop]; if (mappedProp && mappedProp !== prop) { props[mappedProp] = props[prop]; delete props[prop]; } } } // we need to add persist() to Event (as React has it for synthetic events) // this is a hack and we really shouldn't be modifying a global object this way, // but there isn't a performant way of doing this apart from trying to proxy // every prop event that starts with "on", i.e. onClick or onKeyPress // but in reality devs use onSomething for many things, not only for // input events if (typeof Event !== 'undefined' && !Event.prototype.persist) { // tslint:disable-next-line:no-empty Event.prototype.persist = function () { }; } function iterableToArray(iterable) { var iterStep; var tmpArr = []; do { iterStep = iterable.next(); if (iterStep.value) { tmpArr.push(iterStep.value); } } while (!iterStep.done); return tmpArr; } var hasSymbolSupport = typeof Symbol !== 'undefined'; var injectStringRefs = function (originalFunction) { return function (name, _props) { var arguments$1 = arguments; var children = [], len$1 = arguments.length - 2; while ( len$1-- > 0 ) { children[ len$1 ] = arguments$1[ len$1 + 2 ]; } var props = _props || {}; var ref = props.ref; if (typeof ref === 'string' && !isNull(currentComponent)) { currentComponent.refs = currentComponent.refs || {}; props.ref = function (val) { this.refs[ref] = val; }.bind(currentComponent); } if (typeof name === 'string') { normalizeProps$1(name, props); } // React supports iterable children, in addition to Array-like if (hasSymbolSupport) { for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; if (child && !isArray(child) && !isString(child) && isFunction(child[Symbol.iterator])) { children[i] = iterableToArray(child[Symbol.iterator]()); } } } var vnode = originalFunction.apply(void 0, [ name, props ].concat( children )); if (vnode.className) { vnode.props = vnode.props || {}; vnode.props.className = vnode.className; } return vnode; }; }; var createElement$1 = injectStringRefs(infernoCreateElement.createElement); var cloneElement = injectStringRefs(cloneVNode); var oldCreateVNode = inferno.options.createVNode; inferno.options.createVNode = function (vNode) { var children = vNode.children; var props = vNode.props; if (isNullOrUndef(props)) { props = vNode.props = {}; } if (!isNullOrUndef(children) && isNullOrUndef(props.children)) { props.children = children; } if (vNode.flags & 14 /* Component */) { if (isString(vNode.type)) { vNode.flags = inferno.getFlagsForElementVnode(vNode.type); if (props && props.children) { inferno.normalizeChildren(vNode, props.children); delete props.children; } } } if (oldCreateVNode) { oldCreateVNode(vNode); } }; // Credit: preact-compat - https://github.com/developit/preact-compat :) function shallowDiffers(a, b) { for (var i in a) { if (!(i in b)) { return true; } } for (var i$1 in b) { if (a[i$1] !== b[i$1]) { return true; } } return false; } function PureComponent(props, context) { inferno.Component.call(this, props, context); } PureComponent.prototype = new inferno.Component({}, {}); PureComponent.prototype.shouldComponentUpdate = function (props, state) { return shallowDiffers(this.props, props) || shallowDiffers(this.state, state); }; var WrapperComponent = (function (Component$$1) { function WrapperComponent () { Component$$1.apply(this, arguments); } if ( Component$$1 ) { WrapperComponent.__proto__ = Component$$1; } WrapperComponent.prototype = Object.create( Component$$1 && Component$$1.prototype ); WrapperComponent.prototype.constructor = WrapperComponent; WrapperComponent.prototype.getChildContext = function getChildContext () { // tslint:disable-next-line return this.props['context']; }; WrapperComponent.prototype.render = function render$$1 (props) { return props.children; }; return WrapperComponent; }(inferno.Component)); function unstable_renderSubtreeIntoContainer(parentComponent, vNode, container, callback) { var wrapperVNode = inferno.createComponentVNode(4 /* ComponentClass */, WrapperComponent, { children: vNode, context: parentComponent.context }); var component = inferno.render(wrapperVNode, container); if (callback) { // callback gets the component as context, no other argument. callback.call(component); } return component; } // Credit: preact-compat - https://github.com/developit/preact-compat var ELEMENTS = 'a abbr address area article aside audio b base bdi bdo big blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li link main map mark menu menuitem meta meter nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track u ul var video wbr circle clipPath defs ellipse g image line linearGradient mask path pattern polygon polyline radialGradient rect stop svg text tspan'.split(' '); function createFactory(type) { return createElement$1.bind(null, type); } var DOM = {}; for (var i = ELEMENTS.length; i--;) { DOM[ELEMENTS[i]] = createFactory(ELEMENTS[i]); } function findDOMNode(ref) { if (!inferno.options.findDOMNodeEnabled) { throwError(); } var dom = ref && ref.nodeType ? ref : null; return componentToDOMNodeMap.get(ref) || dom; } // Mask React global in browser enviornments when React is not used. if (isBrowser && typeof window.React === 'undefined') { var exports$1 = { Children: Children, Component: inferno.Component, DOM: DOM, EMPTY_OBJ: inferno.EMPTY_OBJ, NO_OP: NO_OP, PropTypes: PropTypes, PureComponent: PureComponent, cloneElement: cloneElement, cloneVNode: cloneVNode, createClass: infernoCreateClass.createClass, createElement: createElement$1, createFactory: createFactory, createVNode: inferno.createVNode, findDOMNode: findDOMNode, isValidElement: isValidElement, render: inferno.render, unmountComponentAtNode: unmountComponentAtNode, unstable_renderSubtreeIntoContainer: unstable_renderSubtreeIntoContainer, version: version }; window.React = exports$1; window.ReactDOM = exports$1; } /** * @module Inferno-Mobx */ /** TypeDoc Comment */ var EventEmitter = function EventEmitter() { this.listeners = []; }; EventEmitter.prototype.on = function on (cb) { var this$1 = this; this.listeners.push(cb); return function () { var index = this$1.listeners.indexOf(cb); if (index !== -1) { this$1.listeners.splice(index, 1); } }; }; EventEmitter.prototype.emit = function emit (data) { var listeners = this.listeners; for (var i = 0, len = listeners.length; i < len; i++) { listeners[i](data); } }; /** * @module Inferno-Shared */ /** TypeDoc Comment */ // This should be boolean and not reference to window.document var isBrowser$2 = !!(typeof window !== 'undefined' && window.document); function warning(message) { // tslint:disable-next-line:no-console console.error(message); } /** * @module Inferno-Mobx */ /** TypeDoc Comment */ function isStateless(component) { return !(component.prototype && component.prototype.render); } /** * @module Inferno-Mobx */ /** TypeDoc Comment */ /** * dev tool support */ var isDevtoolsEnabled = false; var isUsingStaticRendering = false; var warnedAboutObserverInjectDeprecation = false; var componentByNodeRegistery = new WeakMap(); var renderReporter = new EventEmitter(); function findNode(component) { if (inferno.options.findDOMNodeEnabled) { return findDOMNode(component); } return null; } function reportRendering(component) { var node = findNode(component); if (node) { componentByNodeRegistery.set(node, component); } renderReporter.emit({ component: component, event: 'render', node: node, renderTime: component.__$mobRenderEnd - component.__$mobRenderStart, totalTime: Date.now() - component.__$mobRenderStart }); } function trackComponents() { if (!isDevtoolsEnabled) { isDevtoolsEnabled = true; inferno.options.findDOMNodeEnabled = true; warning('Do not turn trackComponents on in production, its expensive. For tracking dom nodes you need inferno-compat.'); } } function useStaticRendering(useStatic) { isUsingStaticRendering = useStatic; } /** * Errors reporter */ var errorsReporter = new EventEmitter(); /** * Utilities */ function patch(target, funcName, runMixinFirst) { if ( runMixinFirst === void 0 ) runMixinFirst = false; var base = target[funcName]; var mixinFunc = reactiveMixin[funcName]; // MWE: ideally we freeze here to protect against accidental overwrites in component instances, see #195 // ...but that breaks react-hot-loader, see #231... target[funcName] = base ? runMixinFirst === true ? function () { mixinFunc.apply(this, arguments); base.apply(this, arguments); } : function () { base.apply(this, arguments); mixinFunc.apply(this, arguments); } : mixinFunc; } function isObjectShallowModified(prev, next) { if (null == prev || null == next || typeof prev !== 'object' || typeof next !== 'object') { return prev !== next; } var keys = Object.keys(prev); if (keys.length !== Object.keys(next).length) { return true; } var key; for (var i = keys.length - 1; i >= 0; i--) { key = keys[i]; if (next[key] !== prev[key]) { return true; } } return false; } /** * ReactiveMixin */ var reactiveMixin = { componentWillMount: function componentWillMount() { var this$1 = this; if (isUsingStaticRendering === true) { return; } // Generate friendly name for debugging var initialName = this.displayName || this.name || (this.constructor && (this.constructor.displayName || this.constructor.name)) || '<component>'; var rootNodeID = this._reactInternalInstance && this._reactInternalInstance._rootNodeID; /** * If props are shallowly modified, react will render anyway, * so atom.reportChanged() should not result in yet another re-render */ var skipRender = false; /** * forceUpdate will re-assign this.props. We don't want that to cause a loop, * so detect these changes */ function makePropertyObservableReference(propName) { var valueHolder = this[propName]; var atom = new mobx.Atom('reactive ' + propName); Object.defineProperty(this, propName, { configurable: true, enumerable: true, get: function get() { atom.reportObserved(); return valueHolder; }, set: function set(v) { if (isObjectShallowModified(valueHolder, v)) { valueHolder = v; skipRender = true; atom.reportChanged(); skipRender = false; } else { valueHolder = v; } } }); } // make this.props an observable reference, see #124 makePropertyObservableReference.call(this, 'props'); // make state an observable reference makePropertyObservableReference.call(this, 'state'); // wire up reactive render var me = this; var render$$1 = this.render.bind(this); var baseRender = function () { return render$$1(me.props, me.state, me.context); }; var reaction = null; var isRenderingPending = false; var initialRender = function () { reaction = new mobx.Reaction((initialName + "#" + rootNodeID + ".render()"), function () { if (!isRenderingPending) { // N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js) // This unidiomatic React usage but React will correctly warn about this so we continue as usual // See #85 / Pull #44 isRenderingPending = true; if (typeof this$1.componentWillReact === 'function') { this$1.componentWillReact(); // TODO: wrap in action? } if (this$1.__$mobxIsUnmounted !== true) { if (!skipRender) { this$1.$UPD = true; this$1.forceUpdate(); this$1.$UPD = false; } } } }); reaction.reactComponent = this$1; reactiveRender.$mobx = reaction; this$1.render = reactiveRender; return reactiveRender(); }; var reactiveRender = function () { isRenderingPending = false; var exception; var rendering = null; reaction.track(function () { if (isDevtoolsEnabled) { this$1.__$mobRenderStart = Date.now(); } try { rendering = mobx.extras.allowStateChanges(false, baseRender); } catch (e) { exception = e; } if (isDevtoolsEnabled) { this$1.__$mobRenderEnd = Date.now(); } }); if (exception) { errorsReporter.emit(exception); throw exception; } return rendering; }; this.render = initialRender; }, componentWillUnmount: function componentWillUnmount() { if (isUsingStaticRendering === true) { return; } if (this.render.$mobx) { this.render.$mobx.dispose(); } this.__$mobxIsUnmounted = true; if (isDevtoolsEnabled) { var node = findDOMNode(this); if (node) { componentByNodeRegistery.delete(node); } renderReporter.emit({ component: this, event: 'destroy', node: node }); } }, componentDidMount: function componentDidMount() { if (isDevtoolsEnabled) { reportRendering(this); } }, componentDidUpdate: function componentDidUpdate() { if (isDevtoolsEnabled) { reportRendering(this); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { if (isUsingStaticRendering) { warning('[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side.'); } // update on any state changes (as is the default) if (this.state !== nextState) { return true; } // update if props are shallowly not equal, inspired by PureRenderMixin // we could return just 'false' here, and avoid the `skipRender` checks etc // however, it is nicer if lifecycle events are triggered like usually, // so we return true here if props are shallowly modified. return isObjectShallowModified(this.props, nextProps); } }; /** * Observer function / decorator */ function observer(arg1, arg2) { if (typeof arg1 === 'string') { throw new Error('Store names should be provided as array'); } if (Array.isArray(arg1)) { // component needs stores if (!warnedAboutObserverInjectDeprecation) { warnedAboutObserverInjectDeprecation = true; warning('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`'); } if (!arg2) { // invoked as decorator return function (componentClass) { return observer(arg1, componentClass); }; } else { return inject.apply(null, arg1)(observer(arg2)); } } var component = arg1; if (component.isMobxInjector === true) { warning("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'"); } // Stateless function component: // If it is function but doesn't seem to be a react class constructor, // wrap it to a react class automatically if (typeof component === 'function' && (!component.prototype || !component.prototype.render)) { return observer((_a = (function (Component$$1) { function _a () { Component$$1.apply(this, arguments); } if ( Component$$1 ) _a.__proto__ = Component$$1; _a.prototype = Object.create( Component$$1 && Component$$1.prototype ); _a.prototype.constructor = _a; _a.prototype.render = function render$$1 (props, state, context) { return component(props, context); }; return _a; }(inferno.Component)), _a.displayName = component.displayName || component.name, _a.defaultProps = component.defaultProps, _a)); } if (!component) { throw new Error("Please pass a valid component to 'observer'"); } var target = component.prototype || component; mixinLifecycleEvents(target); component.isMobXReactObserver = true; return component; var _a; } function mixinLifecycleEvents(target) { patch(target, 'componentWillMount', true); ['componentDidMount', 'componentWillUnmount', 'componentDidUpdate'].forEach(function (funcName) { patch(target, funcName); }); if (!target.shouldComponentUpdate) { target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate; } } // TODO: support injection somehow as well? var Observer = observer(function (ref) { var children = ref.children; return children(); }); var proxiedInjectorProps = { isMobxInjector: { configurable: true, enumerable: true, value: true, writable: true } }; /** * Store Injection */ function createStoreInjector(grabStoresFn, component, injectNames) { var displayName = 'inject-' + (component.displayName || component.name || (component.constructor && component.constructor.name) || 'Unknown'); if (injectNames) { displayName += '-with-' + injectNames; } var Injector = (function (Component$$1) { function Injector(props, context) { Component$$1.call(this, props, context); this.storeRef = this.storeRef.bind(this); } if ( Component$$1 ) Injector.__proto__ = Component$$1; Injector.prototype = Object.create( Component$$1 && Component$$1.prototype ); Injector.prototype.constructor = Injector; Injector.prototype.storeRef = function storeRef (instance) { this.wrappedInstance = instance; }; Injector.prototype.render = function render$$1 (props, state, context) { // Optimization: it might be more efficient to apply the mapper function *outside* the render method // (if the mapper is a function), that could avoid expensive(?) re-rendering of the injector component // See this test: 'using a custom injector is not too reactive' in inject.js var newProps = {}; var key; for (key in props) { newProps[key] = props[key]; } var additionalProps = grabStoresFn(context.mobxStores || {}, newProps, context) || {}; for (key in additionalProps) { newProps[key] = additionalProps[key]; } return inferno.createComponentVNode(2 /* ComponentUnknown */, component, newProps, null, isStateless(component) ? null : this.storeRef); }; return Injector; }(inferno.Component)); Injector.displayName = displayName; Injector.isMobxInjector = false; // Static fields from component should be visible on the generated Injector hoistNonReactStatics(Injector, component); Injector.wrappedComponent = component; Object.defineProperties(Injector, proxiedInjectorProps); return Injector; } function grabStoresByName(storeNames) { return function (baseStores, nextProps) { for (var i = 0, len = storeNames.length; i < len; i++) { var storeName = storeNames[i]; if (!(storeName in nextProps)) { // Development warning { if (!(storeName in baseStores)) { throw new Error("MobX injector: Store '" + storeName + "' is not available! Make sure it is provided by some Provider"); } } nextProps[storeName] = baseStores[storeName]; } } return nextProps; }; } /** * higher order component that injects stores to a child. * takes either a varargs list of strings, which are stores read from the context, * or a function that manually maps the available stores from the context to props: * storesToProps(mobxStores, props, context) => newProps */ // TODO: Type function inject() { var arguments$1 = arguments; var grabStoresFn; if (typeof arguments[0] === 'function') { grabStoresFn = arguments[0]; return function (componentClass) { var injected = createStoreInjector(grabStoresFn, componentClass); injected.isMobxInjector = false; // supress warning // mark the Injector as observer, to make it react to expressions in `grabStoresFn`, // see #111 injected = observer(injected); injected.isMobxInjector = true; // restore warning return injected; }; } else { var storeNames = []; for (var i = 0; i < arguments.length; i++) { storeNames.push(arguments$1[i]); } grabStoresFn = grabStoresByName(storeNames); return function (componentClass) { return createStoreInjector(grabStoresFn, componentClass, storeNames.join('-')); }; } } /** * @module Inferno-Mobx */ /** TypeDoc Comment */ var specialKeys = new Set(); specialKeys.add('children'); specialKeys.add('key'); specialKeys.add('ref'); var Provider = (function (Component$$1) { function Provider () { Component$$1.apply(this, arguments); } if ( Component$$1 ) Provider.__proto__ = Component$$1; Provider.prototype = Object.create( Component$$1 && Component$$1.prototype ); Provider.prototype.constructor = Provider; Provider.prototype.render = function render$$1 (props) { return props.children; }; Provider.prototype.getChildContext = function getChildContext () { var stores = {}; // inherit stores var props = this.props; var baseStores = this.context.mobxStores; if (baseStores) { for (var key in baseStores) { stores[key] = baseStores[key]; } } // add own stores for (var key$1 in props) { if (!specialKeys.has(key$1) && key$1 !== 'suppressChangedStoreWarning') { stores[key$1] = props[key$1]; } } return { mobxStores: stores }; }; return Provider; }(inferno.Component)); // Development warning { Provider.prototype.componentWillReceiveProps = function (nextProps) { var this$1 = this; // Maybe this warning is too aggressive? if (Object.keys(nextProps).length !== Object.keys(this.props).length) { warning('MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children'); } if (!nextProps.suppressChangedStoreWarning) { for (var key in nextProps) { if (!specialKeys.has(key) && this$1.props[key] !== nextProps[key]) { warning("MobX Provider: Provided store '" + key + "' has changed. Please avoid replacing stores as the change might not propagate to all children"); } } } }; } /** * @module Inferno-Mobx */ /** TypeDoc Comment */ // THIS IS PORT OF AWESOME MOBX-REACT to INFERNO // LAST POINT OF PORT (4.2.2) // https://github.com/mobxjs/mobx-react/commit/acdc338db55b05f256c0ef357c9b71433fbd53d2 var onError = function (fn) { return errorsReporter.on(fn); }; exports.componentByNodeRegistery = componentByNodeRegistery; exports.errorsReporter = errorsReporter; exports.inject = inject; exports.observer = observer; exports.onError = onError; exports.EventEmitter = EventEmitter; exports.Observer = Observer; exports.Provider = Provider; exports.renderReporter = renderReporter; exports.trackComponents = trackComponents; exports.useStaticRendering = useStaticRendering; Object.defineProperty(exports, '__esModule', { value: true }); })));
docs/app/Examples/elements/Loader/Variations/LoaderExampleInline.js
shengnian/shengnian-ui-react
import React from 'react' import { Loader } from 'shengnian-ui-react' const LoaderExampleInline = () => ( <Loader active inline /> ) export default LoaderExampleInline
src/svg-icons/action/update.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionUpdate = (props) => ( <SvgIcon {...props}> <path d="M21 10.12h-6.78l2.74-2.82c-2.73-2.7-7.15-2.8-9.88-.1-2.73 2.71-2.73 7.08 0 9.79 2.73 2.71 7.15 2.71 9.88 0C18.32 15.65 19 14.08 19 12.1h2c0 1.98-.88 4.55-2.64 6.29-3.51 3.48-9.21 3.48-12.72 0-3.5-3.47-3.53-9.11-.02-12.58 3.51-3.47 9.14-3.47 12.65 0L21 3v7.12zM12.5 8v4.25l3.5 2.08-.72 1.21L11 13V8h1.5z"/> </SvgIcon> ); ActionUpdate = pure(ActionUpdate); ActionUpdate.displayName = 'ActionUpdate'; ActionUpdate.muiName = 'SvgIcon'; export default ActionUpdate;
cgi/js/ext/jquery.js
Djang0/limba
/*! * jQuery JavaScript Library v1.4.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h= h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"|| h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La, "`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this, e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a, "margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+ a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/, C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j, s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this, j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length}, toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j=== -1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false; if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--; if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload", b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&& !F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&& l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z], z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j, s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v= s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)|| [];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u, false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"), k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false, scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent= false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom= 1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display= "none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h= c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando); else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this, a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e= c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan", colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType=== 1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "), l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this, "__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one"; if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r= a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true}, attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&& b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0}; c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem, arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid= d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+ c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b= w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k=== "click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+ d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired= B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]=== 0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}}); c.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".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i, [y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3]; break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr, q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h= l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*")); return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!== B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()=== i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m= i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n, m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]- 0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]]; if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m, g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1; for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"), i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g); n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&& function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F|| p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g= t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition? function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML; c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})}, not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h= h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context): c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a, 2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a, b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&& e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={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,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null; else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d= c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a, b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")): this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument|| b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length- 1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script")))); d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i, jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true, zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b), h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b); if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f= d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left; e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b=== "object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset; A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]= encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess", [b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"), e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}}); if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show", 3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay", d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b, d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L|| 1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)} var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle; for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+= parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
server/sonar-web/src/main/js/apps/permission-templates/components/ListItem.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import NameCell from './NameCell'; import PermissionCell from './PermissionCell'; import ActionsCell from './ActionsCell'; import UsersView from '../views/UsersView'; import GroupsView from '../views/GroupsView'; import { PermissionTemplateType, CallbackType } from '../propTypes'; export default class ListItem extends React.Component { static propTypes = { organization: React.PropTypes.object, permissionTemplate: PermissionTemplateType.isRequired, topQualifiers: React.PropTypes.array.isRequired, refresh: CallbackType }; componentWillMount() { this.handleShowGroups = this.handleShowGroups.bind(this); this.handleShowUsers = this.handleShowUsers.bind(this); } handleShowGroups(permission) { new GroupsView({ permission, permissionTemplate: this.props.permissionTemplate, refresh: this.props.refresh }).render(); } handleShowUsers(permission) { new UsersView({ permission, permissionTemplate: this.props.permissionTemplate, refresh: this.props.refresh }).render(); } render() { const permissions = this.props.permissionTemplate.permissions.map(p => ( <PermissionCell key={p.key} permission={p} /> )); return ( <tr data-id={this.props.permissionTemplate.id} data-name={this.props.permissionTemplate.name}> <NameCell organization={this.props.organization} permissionTemplate={this.props.permissionTemplate} topQualifiers={this.props.topQualifiers} /> {permissions} <td className="nowrap thin text-right"> <ActionsCell organization={this.props.organization} permissionTemplate={this.props.permissionTemplate} topQualifiers={this.props.topQualifiers} refresh={this.props.refresh} /> </td> </tr> ); } }
src/svg-icons/device/bluetooth-disabled.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothDisabled = (props) => ( <SvgIcon {...props}> <path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"/> </SvgIcon> ); DeviceBluetoothDisabled = pure(DeviceBluetoothDisabled); DeviceBluetoothDisabled.displayName = 'DeviceBluetoothDisabled'; export default DeviceBluetoothDisabled;
docs/src/PageFooter.js
omerts/react-bootstrap
import React from 'react'; import packageJSON from '../../package.json'; let version = packageJSON.version; if (/docs/.test(version)) { version = version.split('-')[0]; } const PageHeader = React.createClass({ render() { return ( <footer className='bs-docs-footer' role='contentinfo'> <div className='container'> <div className='bs-docs-social'> <ul className='bs-docs-social-buttons'> <li> <iframe className='github-btn' src='https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true' width={95} height={20} title='Star on GitHub' /> </li> <li> <iframe className='github-btn' src='https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true' width={92} height={20} title='Fork on GitHub' /> </li> <li> <iframe src="https://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true" width={230} height={20} allowTransparency="true" frameBorder='0' scrolling='no'> </iframe> </li> </ul> </div> <p>Code licensed under <a href='https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE' target='_blank'>MIT</a>.</p> <ul className='bs-docs-footer-links muted'> <li>Currently v{version}</li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/'>GitHub</a></li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/issues?state=open'>Issues</a></li> <li>·</li> <li><a href='https://github.com/react-bootstrap/react-bootstrap/releases'>Releases</a></li> </ul> </div> </footer> ); } }); export default PageHeader;
ajax/libs/videomail-client/2.3.2/videomail-client.js
joeyparrish/cdnjs
(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.VideomailClient = f()}})(function(){var define,module,exports;return (function(){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}return e})()({1:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; (function webpackUniversalModuleDefinition(root, factory) { if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && (typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object') module.exports = factory();else if (typeof define === 'function' && define.amd) define([], factory);else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') exports["add-eventlistener-with-options"] = factory();else root["add-eventlistener-with-options"] = factory(); })(undefined, function () { return (/******/function (modules) { // webpackBootstrap /******/ // The module cache /******/var installedModules = {}; /******/ // The require function /******/function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/if (installedModules[moduleId]) /******/return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/var module = installedModules[moduleId] = { /******/exports: {}, /******/id: moduleId, /******/loaded: false /******/ }; /******/ // Execute the module function /******/modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/module.loaded = true; /******/ // Return the exports of the module /******/return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/__webpack_require__.m = modules; /******/ // expose the module cache /******/__webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/__webpack_require__.p = ""; /******/ // Load entry module and return exports /******/return __webpack_require__(0); /******/ }( /************************************************************************/ /******/[ /* 0 */ /***/function (module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addEventListenerWithOptions; var _checkSupport = __webpack_require__(1); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } /** * Add event listener with additional options * @param {EventTarget} target - The EventTarget element * @param {string} name - The name of the event * @param {function} listener - The event listener callback * @param {object} options - The options explicitly passed from caller * @param {string} optionName - The additioanl option to add to the event listener */ function addEventListenerWithOptions(target, name, listener, options) { var optionName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'passive'; if (target.addEventListener !== undefined) { var listenerOptions = _checkSupport.SupportMap[optionName] ? Object.assign({}, options, _defineProperty({}, optionName, true)) : options; target.addEventListener(name, listener, listenerOptions); } } /***/ }, /* 1 */ /***/function (module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SupportMap = undefined; var _OptionsMap; var _constants = __webpack_require__(2); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var OptionsMap = (_OptionsMap = {}, _defineProperty(_OptionsMap, _constants.PASSIVE, false), _defineProperty(_OptionsMap, _constants.CAPTURE, false), _defineProperty(_OptionsMap, _constants.ONCE, false), _OptionsMap); var getOptionsMap = function getOptionsMap() { Object.keys(OptionsMap).forEach(function (k, i) { OptionsMap[k] = checkSupportForProperty(k); }); return OptionsMap; }; function checkSupportForProperty(property) { if (!!OptionsMap[property]) { return OptionsMap[property]; } try { var opts = Object.defineProperty({}, property, { get: function get() { OptionsMap[property] = true; } }); window.addEventListener("test", null, opts); window.removeListener("test", null); } catch (e) {} return OptionsMap[property]; } var SupportMap = exports.SupportMap = getOptionsMap(); /***/ }, /* 2 */ /***/function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var PASSIVE = exports.PASSIVE = 'passive'; var CAPTURE = exports.CAPTURE = 'capture'; var ONCE = exports.ONCE = 'once'; /***/ } /******/]) ); }); ; },{}],2:[function(_dereq_,module,exports){ 'use strict'; var EventEmitter = _dereq_('events').EventEmitter, inherits = _dereq_('inherits'), raf = _dereq_('raf'), methods; //the same as off window unless polyfilled or in node var defaultRAFObject = { requestAnimationFrame: raf, cancelAnimationFrame: raf.cancel }; function returnTrue() { return true; } //manage FPS if < 60, else return true; function makeThrottle(fps) { var delay = 1000 / fps; var lastTime = Date.now(); if (fps <= 0 || fps === Infinity) { return returnTrue; } //if an fps throttle has been set then we'll assume //it natively runs at 60fps, var half = Math.ceil(1000 / 60) / 2; return function () { //if a custom fps is requested var now = Date.now(); //is this frame within 8.5ms of the target? //if so then next frame is gonna be too late if (now - lastTime < delay - half) { return false; } lastTime = now; return true; }; } /** * Animitter provides event-based loops for the browser and node, * using `requestAnimationFrame` * @param {Object} [opts] * @param {Number} [opts.fps=Infinity] the framerate requested, defaults to as fast as it can (60fps on window) * @param {Number} [opts.delay=0] milliseconds delay between invoking `start` and initializing the loop * @param {Object} [opts.requestAnimationFrameObject=global] the object on which to find `requestAnimationFrame` and `cancelAnimationFrame` methods * @param {Boolean} [opts.fixedDelta=false] if true, timestamps will pretend to be executed at fixed intervals always * @constructor */ function Animitter(opts) { opts = opts || {}; this.__delay = opts.delay || 0; /** @expose */ this.fixedDelta = !!opts.fixedDelta; /** @expose */ this.frameCount = 0; /** @expose */ this.deltaTime = 0; /** @expose */ this.elapsedTime = 0; /** @private */ this.__running = false; /** @private */ this.__completed = false; this.setFPS(opts.fps || Infinity); this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject); } inherits(Animitter, EventEmitter); function onStart(scope) { var now = Date.now(); var rAFID; //dont let a second animation start on the same object //use *.on('update',fn)* instead if (scope.__running) { return scope; } exports.running += 1; scope.__running = true; scope.__lastTime = now; scope.deltaTime = 0; //emit **start** once at the beginning scope.emit('start', scope.deltaTime, 0, scope.frameCount); var lastRAFObject = scope.requestAnimationFrameObject; var drawFrame = function drawFrame() { if (lastRAFObject !== scope.requestAnimationFrameObject) { //if the requestAnimationFrameObject switched in-between, //then re-request with the new one to ensure proper update execution context //i.e. VRDisplay#submitFrame() may only be requested through VRDisplay#requestAnimationFrame(drawFrame) lastRAFObject = scope.requestAnimationFrameObject; scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame); return; } if (scope.__isReadyForUpdate()) { scope.update(); } if (scope.__running) { rAFID = scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame); } else { scope.requestAnimationFrameObject.cancelAnimationFrame(rAFID); } }; scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame); return scope; } methods = { //EventEmitter Aliases off: EventEmitter.prototype.removeListener, trigger: EventEmitter.prototype.emit, /** * stops the animation and marks it as completed * @emit Animitter#complete * @returns {Animitter} */ complete: function complete() { this.stop(); this.__completed = true; this.emit('complete', this.frameCount, this.deltaTime); return this; }, /** * stops the animation and removes all listeners * @emit Animitter#stop * @returns {Animitter} */ dispose: function dispose() { this.stop(); this.removeAllListeners(); return this; }, /** * get milliseconds between the last 2 updates * * @return {Number} */ getDeltaTime: function getDeltaTime() { return this.deltaTime; }, /** * get the total milliseconds that the animation has ran. * This is the cumlative value of the deltaTime between frames * * @return {Number} */ getElapsedTime: function getElapsedTime() { return this.elapsedTime; }, /** * get the instances frames per second as calculated by the last delta * * @return {Number} */ getFPS: function getFPS() { return this.deltaTime > 0 ? 1000 / this.deltaTime : 0; if (this.deltaTime) { return 1000 / this.deltaTime; } }, /** * get the explicit FPS limit set via `Animitter#setFPS(fps)` or * via the initial `options.fps` property * * @returns {Number} either as set or Infinity */ getFPSLimit: function getFPSLimit() { return this.__fps; }, /** * get the number of frames that have occurred * * @return {Number} */ getFrameCount: function getFrameCount() { return this.frameCount; }, /** * get the object providing `requestAnimationFrame` * and `cancelAnimationFrame` methods * @return {Object} */ getRequestAnimationFrameObject: function getRequestAnimationFrameObject() { return this.requestAnimationFrameObject; }, /** * is the animation loop active * * @return {boolean} */ isRunning: function isRunning() { return this.__running; }, /** * is the animation marked as completed * * @return {boolean} */ isCompleted: function isCompleted() { return this.__completed; }, /** * reset the animation loop, marks as incomplete, * leaves listeners intact * * @emit Animitter#reset * @return {Animitter} */ reset: function reset() { this.stop(); this.__completed = false; this.__lastTime = 0; this.deltaTime = 0; this.elapsedTime = 0; this.frameCount = 0; this.emit('reset', 0, 0, this.frameCount); return this; }, /** * set the framerate for the animation loop * * @param {Number} fps * @return {Animitter} */ setFPS: function setFPS(fps) { this.__fps = fps; this.__isReadyForUpdate = makeThrottle(fps); return this; }, /** * set the object that will provide `requestAnimationFrame` * and `cancelAnimationFrame` methods to this instance * @param {Object} object * @return {Animitter} */ setRequestAnimationFrameObject: function setRequestAnimationFrameObject(object) { if (typeof object.requestAnimationFrame !== 'function' || typeof object.cancelAnimationFrame !== 'function') { throw new Error("Invalid object provide to `setRequestAnimationFrameObject`"); } this.requestAnimationFrameObject = object; return this; }, /** * start an animation loop * @emit Animitter#start * @return {Animitter} */ start: function start() { var self = this; if (this.__delay) { setTimeout(function () { onStart(self); }, this.__delay); } else { onStart(this); } return this; }, /** * stops the animation loop, does not mark as completed * * @emit Animitter#stop * @return {Animitter} */ stop: function stop() { if (this.__running) { this.__running = false; exports.running -= 1; this.emit('stop', this.deltaTime, this.elapsedTime, this.frameCount); } return this; }, /** * update the animation loop once * * @emit Animitter#update * @return {Animitter} */ update: function update() { this.frameCount++; /** @private */ var now = Date.now(); this.__lastTime = this.__lastTime || now; this.deltaTime = this.fixedDelta || exports.globalFixedDelta ? 1000 / Math.min(60, this.__fps) : now - this.__lastTime; this.elapsedTime += this.deltaTime; this.__lastTime = now; this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount); return this; } }; for (var method in methods) { Animitter.prototype[method] = methods[method]; } /** * create an animitter instance, * @param {Object} [options] * @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number ) * @returns {Animitter} */ function createAnimitter(options, fn) { if (arguments.length === 1 && typeof options === 'function') { fn = options; options = {}; } var _instance = new Animitter(options); if (fn) { _instance.on('update', fn); } return _instance; } module.exports = exports = createAnimitter; /** * create an animitter instance, * where the scope is bound in all functions * @param {Object} [options] * @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number ) * @returns {Animitter} */ exports.bound = function (options, fn) { var loop = createAnimitter(options, fn), functionKeys = functions(Animitter.prototype), hasBind = !!Function.prototype.bind, fnKey; for (var i = 0; i < functionKeys.length; i++) { fnKey = functionKeys[i]; loop[fnKey] = hasBind ? loop[fnKey].bind(loop) : bind(loop[fnKey], loop); } return loop; }; exports.Animitter = Animitter; /** * if true, all `Animitter` instances will behave as if `options.fixedDelta = true` */ exports.globalFixedDelta = false; //helpful to inherit from when using bundled exports.EventEmitter = EventEmitter; //keep a global counter of all loops running, helpful to watch in dev tools exports.running = 0; function bind(fn, scope) { if (typeof fn.bind === 'function') { return fn.bind(scope); } return function () { return fn.apply(scope, arguments); }; } function functions(obj) { var keys = Object.keys(obj); var arr = []; for (var i = 0; i < keys.length; i++) { if (typeof obj[keys[i]] === 'function') { arr.push(keys[i]); } } return arr; } //polyfill Date.now for real-old browsers Date.now = Date.now || function now() { return new Date().getTime(); }; },{"events":24,"inherits":37,"raf":52}],3:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; (function (w) { "use strict"; var a2b = w.atob; function atob(str) { // normal window if ('function' === typeof a2b) { return a2b(str); } // browserify (web worker) else if ('function' === typeof Buffer) { return new Buffer(str, 'base64').toString('binary'); } // ios web worker with base64js else if ('object' === _typeof(w.base64js)) { // bufferToBinaryString // https://github.com/coolaj86/unibabel-js/blob/master/index.js#L50 var buf = w.base64js.b64ToByteArray(str); return Array.prototype.map.call(buf, function (ch) { return String.fromCharCode(ch); }).join(''); } // ios web worker without base64js else { throw new Error("you're probably in an ios webworker. please include use beatgammit's base64-js"); } } w.atob = atob; if (typeof module !== 'undefined') { module.exports = atob; } })(window); }).call(this,_dereq_("buffer").Buffer) },{"buffer":8}],4:[function(_dereq_,module,exports){ 'use strict'; var toBuffer = _dereq_('typedarray-to-buffer'); var isFloat32Array = _dereq_('validate.io-float32array'); module.exports = function (float32Array) { if (!float32Array) { throw new Error('A Float32Array parameter is missing.'); } if (!isFloat32Array(float32Array)) { throw new Error('The parameter is not a Float32Array.'); } this.toBuffer = function () { var l = float32Array.length; var arr = new Int16Array(l); var i; for (i = 0; i < l; i++) { arr[i] = Math.min(1, float32Array[i]) * 0x7FFF; } return toBuffer(arr); }; }; },{"typedarray-to-buffer":75,"validate.io-float32array":81}],5:[function(_dereq_,module,exports){ 'use strict'; exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; function placeHoldersCount(b64) { var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; } function byteLength(b64) { // base64 is 4/3 + up to two characters of the original data return b64.length * 3 / 4 - placeHoldersCount(b64); } function toByteArray(b64) { var i, l, tmp, placeHolders, arr; var len = b64.length; placeHolders = placeHoldersCount(b64); arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len; var L = 0; for (i = 0; i < l; i += 4) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[L++] = tmp >> 16 & 0xFF; arr[L++] = tmp >> 8 & 0xFF; arr[L++] = tmp & 0xFF; } if (placeHolders === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[L++] = tmp & 0xFF; } else if (placeHolders === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[L++] = tmp >> 8 & 0xFF; arr[L++] = tmp & 0xFF; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var output = ''; var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; output += lookup[tmp >> 2]; output += lookup[tmp << 4 & 0x3F]; output += '=='; } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; output += lookup[tmp >> 10]; output += lookup[tmp >> 4 & 0x3F]; output += lookup[tmp << 2 & 0x3F]; output += '='; } parts.push(output); return parts.join(''); } },{}],6:[function(_dereq_,module,exports){ "use strict"; },{}],7:[function(_dereq_,module,exports){ "use strict"; /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function self(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + ( // Proposed for ES6 separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; return self; }(); },{}],8:[function(_dereq_,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict'; var base64 = _dereq_('base64-js'); var ieee754 = _dereq_('ieee754'); exports.Buffer = Buffer; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; var K_MAX_LENGTH = 0x7fffffff; exports.kMaxLength = K_MAX_LENGTH; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); } function typedArraySupport() { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1); arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function foo() { return 42; } }; return arr.foo() === 42; } catch (e) { return false; } } Object.defineProperty(Buffer.prototype, 'parent', { get: function get() { if (!(this instanceof Buffer)) { return undefined; } return this.buffer; } }); Object.defineProperty(Buffer.prototype, 'offset', { get: function get() { if (!(this instanceof Buffer)) { return undefined; } return this.byteOffset; } }); function createBuffer(length) { if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length'); } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length); buf.__proto__ = Buffer.prototype; return buf; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error('If encoding is specified then the first argument must be a string'); } return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }); } Buffer.poolSize = 8192; // not used by this implementation function from(value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number'); } if (isArrayBuffer(value) || value && isArrayBuffer(value.buffer)) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof value === 'string') { return fromString(value, encodingOrOffset); } return fromObject(value); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype; Buffer.__proto__ = Uint8Array; function assertSize(size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number'); } else if (size < 0) { throw new RangeError('"size" argument must not be negative'); } } function alloc(size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(size); } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); } return createBuffer(size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding); }; function allocUnsafe(size) { assertSize(size); return createBuffer(size < 0 ? 0 : checked(size) | 0); } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size); }; function fromString(string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } var length = byteLength(string, encoding) | 0; var buf = createBuffer(length); var actual = buf.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual); } return buf; } function fromArrayLike(array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; var buf = createBuffer(length); for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255; } return buf; } function fromArrayBuffer(array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds'); } var buf; if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array); } else if (length === undefined) { buf = new Uint8Array(array, byteOffset); } else { buf = new Uint8Array(array, byteOffset, length); } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype; return buf; } function fromObject(obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0; var buf = createBuffer(len); if (buf.length === 0) { return buf; } obj.copy(buf, 0, 0, len); return buf; } if (obj) { if (ArrayBuffer.isView(obj) || 'length' in obj) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0); } return fromArrayLike(obj); } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data); } } throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.'); } function checked(length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); } return length | 0; } function SlowBuffer(length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0; } return Buffer.alloc(+length); } Buffer.isBuffer = function isBuffer(b) { return b != null && b._isBuffer === true; }; Buffer.compare = function compare(a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers'); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (ArrayBuffer.isView(buf)) { buf = Buffer.from(buf); } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } buf.copy(buffer, pos); pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (Buffer.isBuffer(string)) { return string.length; } if (ArrayBuffer.isView(string) || isArrayBuffer(string)) { return string.byteLength; } if (typeof string !== 'string') { string = '' + string; } var len = string.length; if (len === 0) return 0; // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) return utf8ToBytes(string).length; // assume utf8 encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits'); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits'); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits'); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.toLocaleString = Buffer.prototype.toString; Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = exports.INSPECT_MAX_BYTES; if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); if (this.length > max) str += ' ... '; } return '<Buffer ' + str + '>'; }; Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer'); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } var strLen = string.length; if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (numberIsNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function latin1Write(buf, string, offset, length) { return asciiWrite(buf, string, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } } else { throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': return asciiWrite(this, string, offset, length); case 'latin1': case 'binary': return latin1Write(this, string, offset, length); case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf); } else { return base64.fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype; return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; }; Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | this[offset + 1] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | this[offset] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; return offset + 4; }; Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); } ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); } ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy(target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end); } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } } else { Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); } return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill(val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } if (val.length === 1) { var code = val.charCodeAt(0); if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code; } } } else if (typeof val === 'number') { val = val & 255; } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = Buffer.isBuffer(val) ? val : new Buffer(val, encoding); var len = bytes.length; if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"'); } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; function base64clean(str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str; } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } // valid lead leadSurrogate = codePoint; continue; } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue; } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else { throw new Error('Invalid code point'); } } return bytes; } function asciiToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray; } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 function isArrayBuffer(obj) { return obj instanceof ArrayBuffer || obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && typeof obj.byteLength === 'number'; } function numberIsNaN(obj) { return obj !== obj; // eslint-disable-line no-self-compare } },{"base64-js":5,"ieee754":35}],9:[function(_dereq_,module,exports){ 'use strict'; var toBuffer = _dereq_('typedarray-to-buffer'); var atob = _dereq_('atob'); var isBrowser = typeof document !== 'undefined' && typeof document.createElement === 'function'; // cached, used only once for browser environments var verifiedImageType; module.exports = function (canvas, options) { var self = this; options = options || {}; options.image = options.image ? options.image : {}; options.image.types = options.image.types ? options.image.types : []; // validate some options this class needs if (options.image.types.length > 2) { throw new Error('Too many image types are specified!'); } else if (options.image.types.length < 1) { // Set a default image type, just to be robust options.image.types = isBrowser ? ['webp', 'jpeg'] : ['png']; } if (!options.image.quality) { options.image.quality = 0.5; // default } var quality = parseFloat(options.image.quality); function composeImageType(index) { var imageType; if (options.image.types[index]) { imageType = 'image/' + options.image.types[index]; } return imageType; } function isMatch(uri, imageType) { var match = uri && uri.match(imageType); match && options.debug && options.debug('Image type %s verified', imageType); return match; } // Performance tweak, we do not need a big canvas for finding out the supported image type function getTestCanvas() { var testCanvas; if (isBrowser) { testCanvas = document.createElement('canvas'); testCanvas.width = testCanvas.height = 1; } else { testCanvas = canvas; } return testCanvas; } function canvasSupportsImageTypeAsync(imageType, cb) { try { getTestCanvas().toDataURL(imageType, function (err, uri) { if (err) { cb(err); } else { cb(null, isMatch(uri, imageType)); } }); } catch (exc) { cb(null, false); } } function canvasSupportsImageTypeSync(imageType) { var match; try { var testCanvas = getTestCanvas(); var uri = testCanvas.toDataURL && testCanvas.toDataURL(imageType); match = isMatch(uri, imageType); } catch (exc) { // Can happen when i.E. a spider is coming. Just be robust here and continue. options.debug && options.logger.debug('Failed to call toDataURL() on canvas for image type %s', imageType); } return match; } function verifyImageTypeAsync(imageType, cb) { canvasSupportsImageTypeAsync(imageType, function (err, match) { if (err) { cb(err); } else { if (match) { cb(null, imageType); } else { imageType = composeImageType(1); canvasSupportsImageTypeAsync(imageType, function (err, match) { if (err) { cb(err); } else { cb(null, match ? imageType : null); } }); } } }); } function verifyImageTypeSync(imageType) { if (!canvasSupportsImageTypeSync(imageType)) { if (options.image.types[1]) { imageType = composeImageType(1); if (!canvasSupportsImageTypeSync(imageType)) { imageType = null; } } else { imageType = null; } } !imageType && options.debug && options.logger.debug('Unable to verify image type'); return imageType; } // callbacks are needed for server side tests function verifyImageType(cb) { var imageType = composeImageType(0); if (cb) { verifyImageTypeAsync(imageType, cb); } else { return verifyImageTypeSync(imageType); } } // this method is proven to be fast, see // http://jsperf.com/data-uri-to-buffer-performance/3 function uriToBuffer(uri) { var uriSplitted = uri.split(',')[1]; var bytes; // Beware that the atob function might be a static one for server side tests if (typeof atob === 'function') { bytes = atob(uriSplitted); } else if (typeof self.constructor.atob === 'function') { bytes = self.constructor.atob(uriSplitted); } else { throw new Error('atob function is missing'); } var arr = new Uint8Array(bytes.length); // http://mrale.ph/blog/2014/12/24/array-length-caching.html for (var i = 0, l = bytes.length; i < l; i++) { arr[i] = bytes.charCodeAt(i); } return toBuffer(arr); } function toBufferSync() { var imageType = self.getImageType(); var buffer; if (imageType) { var uri = canvas.toDataURL(imageType, quality); buffer = uriToBuffer(uri); } return buffer; } function toBufferAsync(cb) { self.getImageType(function (err, imageType) { if (err) { cb(err); } else if (!imageType) { cb(); } else { canvas.toDataURL(imageType, function (err, uri) { if (err) { cb(err); } else { cb(null, uriToBuffer(uri)); } }); } }); } this.toBuffer = function (cb) { if (cb) { toBufferAsync(cb); } else { return toBufferSync(); } }; // browsers do not need a callback, but tests do this.getImageType = function (cb) { // only run for the first time this constructor is called and // cache result for the next calls if (cb) { if (!verifiedImageType || !isBrowser) { verifyImageType(function (err, newVerifiedImageType) { if (err) { cb(err); } else { verifiedImageType = newVerifiedImageType; cb(null, verifiedImageType); } }); } else { cb(null, verifiedImageType); } } else { // on the browser side we do cache it for speed if (!verifiedImageType || !isBrowser) { verifiedImageType = verifyImageType(); } return verifiedImageType; } }; }; },{"atob":3,"typedarray-to-buffer":75}],10:[function(_dereq_,module,exports){ "use strict"; // contains, add, remove, toggle var indexof = _dereq_('indexof'); module.exports = ClassList; function ClassList(elem) { var cl = elem.classList; if (cl) { return cl; } var classList = { add: add, remove: remove, contains: contains, toggle: toggle, toString: $toString, length: 0, item: item }; return classList; function add(token) { var list = getTokens(); if (indexof(list, token) > -1) { return; } list.push(token); setTokens(list); } function remove(token) { var list = getTokens(), index = indexof(list, token); if (index === -1) { return; } list.splice(index, 1); setTokens(list); } function contains(token) { return indexof(getTokens(), token) > -1; } function toggle(token) { if (contains(token)) { remove(token); return false; } else { add(token); return true; } } function $toString() { return elem.className; } function item(index) { var tokens = getTokens(); return tokens[index] || null; } function getTokens() { var className = elem.className; return filter(className.split(" "), isTruthy); } function setTokens(list) { var length = list.length; elem.className = list.join(" "); classList.length = length; for (var i = 0; i < list.length; i++) { classList[i] = list[i]; } delete list[length]; } } function filter(arr, fn) { var ret = []; for (var i = 0; i < arr.length; i++) { if (fn(arr[i])) ret.push(arr[i]); } return ret; } function isTruthy(value) { return !!value; } },{"indexof":36}],11:[function(_dereq_,module,exports){ "use strict"; /* * classList.js: Cross-browser full element.classList implementation. * 1.1.20150312 * * By Eli Grey, http://eligrey.com * License: Dedicated to the public domain. * See https://github.com/eligrey/classList.js/blob/master/LICENSE.md */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */ if ("document" in self) { // Full polyfill for browsers with no classList support // Including IE < Edge missing SVGElement.classList if (!("classList" in document.createElement("_")) || document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg", "g"))) { (function (view) { "use strict"; if (!('Element' in view)) return; var classListProp = "classList", protoProp = "prototype", elemCtrProto = view.Element[protoProp], objCtr = Object, strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); }, arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0, len = this.length; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function DOMEx(type, message) { this.name = type; this.code = DOMException[type]; this.message = message; }, checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) { if (token === "") { throw new DOMEx("SYNTAX_ERR", "An invalid or illegal string was specified"); } if (/\s/.test(token)) { throw new DOMEx("INVALID_CHARACTER_ERR", "String contains an invalid character"); } return arrIndexOf.call(classList, token); }, ClassList = function ClassList(elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || ""), classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [], i = 0, len = classes.length; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; }, classListProto = ClassList[protoProp] = [], classListGetter = function classListGetter() { return new ClassList(this); }; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments, i = 0, l = tokens.length, token, updated = false; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments, i = 0, l = tokens.length, token, updated = false, index; do { token = tokens[i] + ""; index = checkTokenAndGetIndex(this, token); while (index !== -1) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { token += ""; var result = this.contains(token), method = result ? force !== true && "remove" : force !== false && "add"; if (method) { this[method](token); } if (force === true || force === false) { return force; } else { return !result; } }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter, enumerable: true, configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } })(self); } else { // There is full or partial native classList support, so just check if we need // to normalize the add/remove and toggle APIs. (function () { "use strict"; var testElement = document.createElement("_"); testElement.classList.add("c1", "c2"); // Polyfill for IE 10/11 and Firefox <26, where classList.add and // classList.remove exist but support only one argument at a time. if (!testElement.classList.contains("c2")) { var createMethod = function createMethod(method) { var original = DOMTokenList.prototype[method]; DOMTokenList.prototype[method] = function (token) { var i, len = arguments.length; for (i = 0; i < len; i++) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle("c3", false); // Polyfill for IE 10 and Firefox <24, where classList.toggle does not // support the second argument. if (testElement.classList.contains("c3")) { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } testElement = null; })(); } } },{}],12:[function(_dereq_,module,exports){ 'use strict'; /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) { this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function (event, fn) { function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) { this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ 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; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function (event) { this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function (event) { return !!this.listeners(event).length; }; },{}],13:[function(_dereq_,module,exports){ "use strict"; var DOCUMENT_POSITION_CONTAINED_BY = 16; module.exports = contains; function contains(container, elem) { if (container.contains) { return container.contains(elem); } var comparison = container.compareDocumentPosition(elem); return comparison === 0 || comparison & DOCUMENT_POSITION_CONTAINED_BY; } },{}],14:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return objectToString(e) === '[object Error]' || e instanceof Error; } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,{"isBuffer":_dereq_("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":41}],15:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // create-error.js 0.3.1 // (c) 2013 Tim Griesser // This source may be freely distributed under the MIT license. (function (factory) { "use strict"; // A simple utility for subclassing the "Error" // object in multiple environments, while maintaining // relevant stack traces, messages, and prototypes. factory(function () { var toString = Object.prototype.toString; // Creates an new error type with a "name", // and any additional properties that should be set // on the error instance. return function () { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } var name = getName(args); var target = getTarget(args); var properties = getProps(args); function ErrorCtor(message, obj) { attachProps(this, properties); attachProps(this, obj); this.message = message || this.message; if (message instanceof Error) { this.message = message.message; this.stack = message.stack; } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } function Err() { this.constructor = ErrorCtor; } Err.prototype = target['prototype']; ErrorCtor.prototype = new Err(); ErrorCtor.prototype.name = '' + name || 'CustomError'; return ErrorCtor; }; // Just a few helpers to clean up the function above // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers function getName(args) { if (args.length === 0) return ''; return isError(args[0]) ? args[1] || '' : args[0]; } function getTarget(args) { if (args.length === 0) return Error; return isError(args[0]) ? args[0] : Error; } function getProps(args) { if (args.length === 0) return null; return isError(args[0]) ? args[2] : args[1]; } function inheritedKeys(obj) { var ret = []; for (var key in obj) { ret.push(key); } return ret; } // Right now we're just assuming that a function in the first argument is an error. function isError(obj) { return typeof obj === "function"; } // We don't need the full underscore check here, since it should either be // an object-literal, or nothing at all. function isObject(obj) { return obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === "object" && toString.call(obj) === "[object Object]"; } // Used to attach attributes to the error object in the constructor. function attachProps(context, target) { if (isObject(target)) { var keys = inheritedKeys(target); for (var i = 0, l = keys.length; i < l; ++i) { context[keys[i]] = clone(target[keys[i]]); } } } // Don't need the full-out "clone" mechanism here, since if you're // trying to set things other than empty arrays/objects on your // sub-classed `Error` object, you're probably doing it wrong. function clone(target) { if (target == null || (typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== "object") return target; var cloned = target.constructor ? target.constructor() : Object.create(null); for (var attr in target) { if (target.hasOwnProperty(attr)) { cloned[attr] = target[attr]; } } return cloned; } }); // Boilerplate UMD definition block... })(function (createErrorLib) { if (typeof define === "function" && define.amd) { define(createErrorLib); } else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') { module.exports = createErrorLib(); } else { var root = this; var lastcreateError = root.createError; var createError = root.createError = createErrorLib(); createError.noConflict = function () { root.createError = lastcreateError; return createError; }; } }); },{}],16:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; (function (global, factory) { (typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.deepmerge = factory(); })(undefined, function () { 'use strict'; var isMergeableObject = function isMergeableObject(value) { return isNonNullObject(value) && !isSpecial(value); }; function isNonNullObject(value) { return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object'; } function isSpecial(value) { var stringValue = Object.prototype.toString.call(value); return stringValue === '[object RegExp]' || stringValue === '[object Date]' || isReactElement(value); } // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 var canUseSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; function isReactElement(value) { return value.$$typeof === REACT_ELEMENT_TYPE; } function emptyTarget(val) { return Array.isArray(val) ? [] : {}; } function cloneUnlessOtherwiseSpecified(value, options) { return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value; } function defaultArrayMerge(target, source, options) { return target.concat(source).map(function (element) { return cloneUnlessOtherwiseSpecified(element, options); }); } function mergeObject(target, source, options) { var destination = {}; if (options.isMergeableObject(target)) { Object.keys(target).forEach(function (key) { destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); }); } Object.keys(source).forEach(function (key) { if (!options.isMergeableObject(source[key]) || !target[key]) { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); } else { destination[key] = deepmerge(target[key], source[key], options); } }); return destination; } function deepmerge(target, source, options) { options = options || {}; options.arrayMerge = options.arrayMerge || defaultArrayMerge; options.isMergeableObject = options.isMergeableObject || isMergeableObject; var sourceIsArray = Array.isArray(source); var targetIsArray = Array.isArray(target); var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; if (!sourceAndTargetTypesMatch) { return cloneUnlessOtherwiseSpecified(source, options); } else if (sourceIsArray) { return options.arrayMerge(target, source, options); } else { return mergeObject(target, source, options); } } deepmerge.all = function deepmergeAll(array, options) { if (!Array.isArray(array)) { throw new Error('first argument should be an array'); } return array.reduce(function (prev, next) { return deepmerge(prev, next, options); }, {}); }; var deepmerge_1 = deepmerge; return deepmerge_1; }); },{}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function () { for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) return arguments[i]; } }; },{}],18:[function(_dereq_,module,exports){ 'use strict'; var util = _dereq_('util'); var global = _dereq_('global'); var EventEmitter = _dereq_('events'); var makeDespot = function makeDespot() { var Despot = function Despot() { if (global._singletonDespotInstance) { return global._singletonDespotInstance; } else { global._singletonDespotInstance = this; EventEmitter.call(this); } }; util.inherits(Despot, EventEmitter); return new Despot(); }; module.exports = makeDespot(); },{"events":24,"global":31,"util":80}],19:[function(_dereq_,module,exports){ 'use strict'; var document = _dereq_('global/document'); var Event = _dereq_('geval'); var Keys = _dereq_('./keys'); module.exports = Visibility; function Visibility() { var keys = Keys(document); if (!keys) return noopShim(); return { visible: visible, onChange: Event(listen) }; function visible() { return !document[keys.hidden]; } function listen(broadcast) { document.addEventListener(keys.event, function onVisibilityChange() { broadcast(visible()); }); } } function noopShim() { return { visible: function visible() { return true; }, onChange: noop }; } function noop() {} },{"./keys":20,"geval":29,"global/document":30}],20:[function(_dereq_,module,exports){ 'use strict'; module.exports = keys; function keys(document) { var prefix = detectPrefix(document); if (prefix == null) return; return { hidden: lowercaseFirst(prefix + 'Hidden'), event: prefix + 'visibilitychange' }; } function detectPrefix(document) { if (document.hidden != null) return ''; if (document.mozHidden != null) return 'moz'; if (document.msHidden != null) return 'ms'; if (document.webkitHidden != null) return 'webkit'; } function lowercaseFirst(string) { return string.substring(0, 1).toLowerCase() + string.substring(1); } },{}],21:[function(_dereq_,module,exports){ (function (process,Buffer){ 'use strict'; var stream = _dereq_('readable-stream'); var eos = _dereq_('end-of-stream'); var inherits = _dereq_('inherits'); var shift = _dereq_('stream-shift'); var SIGNAL_FLUSH = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from([0]) : new Buffer([0]); var onuncork = function onuncork(self, fn) { if (self._corked) self.once('uncork', fn);else fn(); }; var destroyer = function destroyer(self, end) { return function (err) { if (err) self._destroyInterval(err);else if (end && !self._ended) self.end(); }; }; var end = function end(ws, fn) { if (!ws) return fn(); if (ws._writableState && ws._writableState.finished) return fn(); if (ws._writableState) return ws.end(fn); ws.end(); fn(); }; var toStreams2 = function toStreams2(rs) { return new stream.Readable({ objectMode: true, highWaterMark: 16 }).wrap(rs); }; var Duplexify = function Duplexify(writable, readable, opts) { if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts); stream.Duplex.call(this, opts); this._writable = null; this._readable = null; this._readable2 = null; this._forwardDestroy = !opts || opts.destroy !== false; this._forwardEnd = !opts || opts.end !== false; this._corked = 1; // start corked this._ondrain = null; this._drained = false; this._forwarding = false; this._unwrite = null; this._unread = null; this._ended = false; this._error = null; this._preferError = false; this.destroyed = false; if (writable) this.setWritable(writable); if (readable) this.setReadable(readable); }; inherits(Duplexify, stream.Duplex); Duplexify.obj = function (writable, readable, opts) { if (!opts) opts = {}; opts.objectMode = true; opts.highWaterMark = 16; return new Duplexify(writable, readable, opts); }; Duplexify.prototype.cork = function () { if (++this._corked === 1) this.emit('cork'); }; Duplexify.prototype.uncork = function () { if (this._corked && --this._corked === 0) this.emit('uncork'); }; Duplexify.prototype.setWritable = function (writable) { if (this._unwrite) this._unwrite(); if (this.destroyed) { if (writable && writable.destroy) writable.destroy(); return; } if (writable === null || writable === false) { this.end(); return; } var self = this; var unend = eos(writable, { writable: true, readable: false }, destroyer(this, this._forwardEnd)); var ondrain = function ondrain() { var ondrain = self._ondrain; self._ondrain = null; if (ondrain) ondrain(); }; var clear = function clear() { self._writable.removeListener('drain', ondrain); unend(); }; if (this._unwrite) process.nextTick(ondrain); // force a drain on stream reset to avoid livelocks this._writable = writable; this._writable.on('drain', ondrain); this._unwrite = clear; this.uncork(); // always uncork setWritable }; Duplexify.prototype.setReadable = function (readable) { if (this._unread) this._unread(); if (this.destroyed) { if (readable && readable.destroy) readable.destroy(); return; } if (readable === null || readable === false) { this.push(null); this.resume(); return; } var self = this; var unend = eos(readable, { writable: false, readable: true }, destroyer(this)); var onreadable = function onreadable() { self._forward(); }; var onend = function onend() { self.push(null); }; var clear = function clear() { self._readable2.removeListener('readable', onreadable); self._readable2.removeListener('end', onend); unend(); }; this._drained = true; this._readable = readable; this._readable2 = readable._readableState ? readable : toStreams2(readable); this._readable2.on('readable', onreadable); this._readable2.on('end', onend); this._unread = clear; this._forward(); }; Duplexify.prototype._read = function () { this._drained = true; this._forward(); }; Duplexify.prototype._forward = function () { if (this._forwarding || !this._readable2 || !this._drained) return; this._forwarding = true; var data; while (this._drained && (data = shift(this._readable2)) !== null) { if (this.destroyed) continue; this._drained = this.push(data); } this._forwarding = false; }; Duplexify.prototype.destroy = function (err) { if (this._preferError && !this._error && err) this._error = err; if (this.destroyed) return; this.destroyed = true; var self = this; process.nextTick(function () { self._destroy(self._preferError ? self._error : err); }); }; Duplexify.prototype._destroyInterval = function (err) { if (this.destroyed) return; if (err.message !== 'premature close') return this.destroy(err); this._preferError = true; this.destroy(null); }; Duplexify.prototype._destroy = function (err) { if (err) { var ondrain = this._ondrain; this._ondrain = null; if (ondrain) ondrain(err);else this.emit('error', err); } if (this._forwardDestroy) { if (this._readable && this._readable.destroy) this._readable.destroy(); if (this._writable && this._writable.destroy) this._writable.destroy(); } this.emit('close'); }; Duplexify.prototype._write = function (data, enc, cb) { if (this.destroyed) return cb(); if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)); if (data === SIGNAL_FLUSH) return this._finish(cb); if (!this._writable) return cb(); if (this._writable.write(data) === false) this._ondrain = cb;else cb(); }; Duplexify.prototype._finish = function (cb) { var self = this; this.emit('preend'); onuncork(this, function () { end(self._forwardEnd && self._writable, function () { // haxx to not emit prefinish twice if (self._writableState.prefinished === false) self._writableState.prefinished = true; self.emit('prefinish'); onuncork(self, cb); }); }); }; Duplexify.prototype.end = function (data, enc, cb) { if (typeof data === 'function') return this.end(null, null, data); if (typeof enc === 'function') return this.end(data, null, enc); this._ended = true; if (data) this.write(data); if (!this._writableState.ending) this.write(SIGNAL_FLUSH); return stream.Writable.prototype.end.call(this, cb); }; module.exports = Duplexify; }).call(this,_dereq_('_process'),_dereq_("buffer").Buffer) },{"_process":51,"buffer":8,"end-of-stream":23,"inherits":37,"readable-stream":63,"stream-shift":68}],22:[function(_dereq_,module,exports){ 'use strict'; // element-closest | CC0-1.0 | github.com/jonathantneal/closest (function (ElementProto) { if (typeof ElementProto.matches !== 'function') { ElementProto.matches = ElementProto.msMatchesSelector || ElementProto.mozMatchesSelector || ElementProto.webkitMatchesSelector || function matches(selector) { var element = this; var elements = (element.document || element.ownerDocument).querySelectorAll(selector); var index = 0; while (elements[index] && elements[index] !== element) { ++index; } return Boolean(elements[index]); }; } if (typeof ElementProto.closest !== 'function') { ElementProto.closest = function closest(selector) { var element = this; while (element && element.nodeType === 1) { if (element.matches(selector)) { return element; } element = element.parentNode; } return null; }; } })(window.Element.prototype); },{}],23:[function(_dereq_,module,exports){ 'use strict'; var once = _dereq_('once'); var noop = function noop() {}; var isRequest = function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function isChildProcess(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3; }; var eos = function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; var onfinish = function onfinish() { writable = false; if (!readable) callback.call(stream); }; var onend = function onend() { readable = false; if (!writable) callback.call(stream); }; var onexit = function onexit(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function onerror(err) { callback.call(stream, err); }; var onclose = function onclose() { if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); }; var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest();else stream.on('request', onrequest); } else if (writable && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function () { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; }; module.exports = eos; },{"once":49}],24:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var objectCreate = Object.create || objectCreatePolyfill; var objectKeys = Object.keys || objectKeysPolyfill; var bind = Function.prototype.bind || functionBindPolyfill; function EventEmitter() { if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { this._events = objectCreate(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; var hasDefineProperty; try { var o = {}; if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); hasDefineProperty = o.x === 0; } catch (err) { hasDefineProperty = false; } if (hasDefineProperty) { Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function get() { return defaultMaxListeners; }, set: function set(arg) { // check whether the input is a positive number (whose value is zero or // greater and not a NaN). if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number'); defaultMaxListeners = arg; } }); } else { EventEmitter.defaultMaxListeners = defaultMaxListeners; } // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self); } } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1); } } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2); } } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].call(self, arg1, arg2, arg3); } } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { listeners[i].apply(self, args); } } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { if (arguments.length > 1) er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Unhandled "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) { args[i - 1] = arguments[i]; }emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = objectCreate(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' "' + String(type) + '" listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit.'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; if ((typeof console === 'undefined' ? 'undefined' : _typeof(console)) === 'object' && console.warn) { console.warn('%s: %s', w.name, w.message); } } } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; switch (arguments.length) { case 0: return this.listener.call(this.target); case 1: return this.listener.call(this.target, arguments[0]); case 2: return this.listener.call(this.target, arguments[0], arguments[1]); case 3: return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]); default: var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; }this.listener.apply(this.target, args); } } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = bind.call(onceWrapper, state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = objectCreate(null);else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift();else spliceOne(list, position); if (list.length === 1) events[type] = list[0]; if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = objectCreate(null); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = objectCreate(null);else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = objectKeys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = objectCreate(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener); } return ret; }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; }list.pop(); } function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) { copy[i] = arr[i]; }return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function objectCreatePolyfill(proto) { var F = function F() {}; F.prototype = proto; return new F(); } function objectKeysPolyfill(obj) { var keys = []; for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } }return k; } function functionBindPolyfill(context) { var fn = this; return function () { return fn.apply(context, arguments); }; } },{}],25:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = stringify; stringify.default = stringify; stringify.stable = deterministicStringify; stringify.stableStringify = deterministicStringify; var arr = []; // Regular stringify function stringify(obj, replacer, spacer) { decirc(obj, '', [], undefined); var res = JSON.stringify(obj, replacer, spacer); while (arr.length !== 0) { var part = arr.pop(); part[0][part[1]] = part[2]; } return res; } function decirc(val, k, stack, parent) { var i; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && val !== null) { for (i = 0; i < stack.length; i++) { if (stack[i] === val) { parent[k] = '[Circular]'; arr.push([parent, k, val]); return; } } stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise! if (Array.isArray(val)) { for (i = 0; i < val.length; i++) { decirc(val[i], i, stack, val); } } else { var keys = Object.keys(val); for (i = 0; i < keys.length; i++) { var key = keys[i]; decirc(val[key], key, stack, val); } } stack.pop(); } } // Stable-stringify function compareFunction(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } function deterministicStringify(obj, replacer, spacer) { var tmp = deterministicDecirc(obj, '', [], undefined) || obj; var res = JSON.stringify(tmp, replacer, spacer); while (arr.length !== 0) { var part = arr.pop(); part[0][part[1]] = part[2]; } return res; } function deterministicDecirc(val, k, stack, parent) { var i; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && val !== null) { for (i = 0; i < stack.length; i++) { if (stack[i] === val) { parent[k] = '[Circular]'; arr.push([parent, k, val]); return; } } if (typeof val.toJSON === 'function') { return; } stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise! if (Array.isArray(val)) { for (i = 0; i < val.length; i++) { deterministicDecirc(val[i], i, stack, val); } } else { // Create a temporary object in the required way var tmp = {}; var keys = Object.keys(val).sort(compareFunction); for (i = 0; i < keys.length; i++) { var key = keys[i]; deterministicDecirc(val[key], key, stack, val); tmp[key] = val[key]; } if (parent !== undefined) { arr.push([parent, k, val]); parent[k] = tmp; } else { return tmp; } } stack.pop(); } } },{}],26:[function(_dereq_,module,exports){ (function (global){ "use strict"; /** * filesize * * @copyright 2018 Jason Mulligan <[email protected]> * @license BSD-3-Clause * @version 3.6.0 */ (function (global) { var b = /^(b|B)$/, symbol = { iec: { bits: ["b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"], bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] }, jedec: { bits: ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"], bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] } }, fullform = { iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"], jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"] }; /** * filesize * * @method filesize * @param {Mixed} arg String, Int or Float to transform * @param {Object} descriptor [Optional] Flags * @return {String} Readable file size String */ function filesize(arg) { var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var result = [], val = 0, e = void 0, base = void 0, bits = void 0, ceil = void 0, full = void 0, fullforms = void 0, neg = void 0, num = void 0, output = void 0, round = void 0, unix = void 0, separator = void 0, spacer = void 0, standard = void 0, symbols = void 0; if (isNaN(arg)) { throw new Error("Invalid arguments"); } bits = descriptor.bits === true; unix = descriptor.unix === true; base = descriptor.base || 2; round = descriptor.round !== void 0 ? descriptor.round : unix ? 1 : 2; separator = descriptor.separator !== void 0 ? descriptor.separator || "" : ""; spacer = descriptor.spacer !== void 0 ? descriptor.spacer : unix ? "" : " "; symbols = descriptor.symbols || descriptor.suffixes || {}; standard = base === 2 ? descriptor.standard || "jedec" : "jedec"; output = descriptor.output || "string"; full = descriptor.fullform === true; fullforms = descriptor.fullforms instanceof Array ? descriptor.fullforms : []; e = descriptor.exponent !== void 0 ? descriptor.exponent : -1; num = Number(arg); neg = num < 0; ceil = base > 2 ? 1000 : 1024; // Flipping a negative number to determine the size if (neg) { num = -num; } // Determining the exponent if (e === -1 || isNaN(e)) { e = Math.floor(Math.log(num) / Math.log(ceil)); if (e < 0) { e = 0; } } // Exceeding supported length, time to reduce & multiply if (e > 8) { e = 8; } // Zero is now a special case because bytes divide by 1 if (num === 0) { result[0] = 0; result[1] = unix ? "" : symbol[standard][bits ? "bits" : "bytes"][e]; } else { val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e)); if (bits) { val = val * 8; if (val >= ceil && e < 8) { val = val / ceil; e++; } } result[0] = Number(val.toFixed(e > 0 ? round : 0)); result[1] = base === 10 && e === 1 ? bits ? "kb" : "kB" : symbol[standard][bits ? "bits" : "bytes"][e]; if (unix) { result[1] = standard === "jedec" ? result[1].charAt(0) : e > 0 ? result[1].replace(/B$/, "") : result[1]; if (b.test(result[1])) { result[0] = Math.floor(result[0]); result[1] = ""; } } } // Decorating a 'diff' if (neg) { result[0] = -result[0]; } // Applying custom symbol result[1] = symbols[result[1]] || result[1]; // Returning Array, Object, or String (default) if (output === "array") { return result; } if (output === "exponent") { return e; } if (output === "object") { return { value: result[0], suffix: result[1], symbol: result[1] }; } if (full) { result[1] = fullforms[e] ? fullforms[e] : fullform[standard][e] + (bits ? "bit" : "byte") + (result[0] === 1 ? "" : "s"); } if (separator.length > 0) { result[0] = result[0].toString().replace(".", separator); } return result.join(spacer); } // Partial application for functional programming filesize.partial = function (opt) { return function (arg) { return filesize(arg, opt); }; }; // CommonJS, AMD, script tag if (typeof exports !== "undefined") { module.exports = filesize; } else if (typeof define === "function" && define.amd) { define(function () { return filesize; }); } else { global.filesize = filesize; } })(typeof window !== "undefined" ? window : global); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],27:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.default = getFormData; exports.getFieldData = getFieldData; var NODE_LIST_CLASSES = { '[object HTMLCollection]': true, '[object NodeList]': true, '[object RadioNodeList]': true // .type values for elements which can appear in .elements and should be ignored };var IGNORED_ELEMENT_TYPES = { 'button': true, 'fieldset': true, 'reset': true, 'submit': true }; var CHECKED_INPUT_TYPES = { 'checkbox': true, 'radio': true }; var TRIM_RE = /^\s+|\s+$/g; var slice = Array.prototype.slice; var toString = Object.prototype.toString; /** * @param {HTMLFormElement} form * @param {Object} options * @return {Object.<string,(string|Array.<string>)>} an object containing * submittable value(s) held in the form's .elements collection, with * properties named as per element names or ids. */ function getFormData(form) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { trim: false }; if (!form) { throw new Error('A form is required by getFormData, was given form=' + form); } var data = {}; var elementName = void 0; var elementNames = []; var elementNameLookup = {}; // Get unique submittable element names for the form for (var i = 0, l = form.elements.length; i < l; i++) { var element = form.elements[i]; if (IGNORED_ELEMENT_TYPES[element.type] || element.disabled) { continue; } elementName = element.name || element.id; if (elementName && !elementNameLookup[elementName]) { elementNames.push(elementName); elementNameLookup[elementName] = true; } } // Extract element data name-by-name for consistent handling of special cases // around elements which contain multiple inputs. for (var _i = 0, _l = elementNames.length; _i < _l; _i++) { elementName = elementNames[_i]; var value = getFieldData(form, elementName, options); if (value != null) { data[elementName] = value; } } return data; } /** * @param {HTMLFormElement} form * @param {string} fieldName * @param {Object} options * @return {(string|Array.<string>)} submittable value(s) in the form for a * named element from its .elements collection, or null if there was no * element with that name or the element had no submittable value(s). */ function getFieldData(form, fieldName) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { trim: false }; if (!form) { throw new Error('A form is required by getFieldData, was given form=' + form); } if (!fieldName && toString.call(fieldName) !== '[object String]') { throw new Error('A field name is required by getFieldData, was given fieldName=' + fieldName); } var element = form.elements[fieldName]; if (!element || element.disabled) { return null; } if (!NODE_LIST_CLASSES[toString.call(element)]) { return getFormElementValue(element, options.trim); } // Deal with multiple form controls which have the same name var data = []; var allRadios = true; for (var i = 0, l = element.length; i < l; i++) { if (element[i].disabled) { continue; } if (allRadios && element[i].type !== 'radio') { allRadios = false; } var value = getFormElementValue(element[i], options.trim); if (value != null) { data = data.concat(value); } } // Special case for an element with multiple same-named inputs which were all // radio buttons: if there was a selected value, only return the value. if (allRadios && data.length === 1) { return data[0]; } return data.length > 0 ? data : null; } /** * @param {HTMLElement} element a form element. * @param {booleam} trim should values for text entry inputs be trimmed? * @return {(string|Array.<string>|File|Array.<File>)} the element's submittable * value(s), or null if it had none. */ function getFormElementValue(element, trim) { var value = null; var type = element.type; if (type === 'select-one') { if (element.options.length) { value = element.options[element.selectedIndex].value; } return value; } if (type === 'select-multiple') { value = []; for (var i = 0, l = element.options.length; i < l; i++) { if (element.options[i].selected) { value.push(element.options[i].value); } } if (value.length === 0) { value = null; } return value; } // If a file input doesn't have a files attribute, fall through to using its // value attribute. if (type === 'file' && 'files' in element) { if (element.multiple) { value = slice.call(element.files); if (value.length === 0) { value = null; } } else { // Should be null if not present, according to the spec value = element.files[0]; } return value; } if (!CHECKED_INPUT_TYPES[type]) { value = trim ? element.value.replace(TRIM_RE, '') : element.value; } else if (element.checked) { value = element.value; } return value; } // For UMD build access to getFieldData getFormData.getFieldData = getFieldData; },{}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = Event; function Event() { var listeners = []; return { broadcast: broadcast, listen: event }; function broadcast(value) { for (var i = 0; i < listeners.length; i++) { listeners[i](value); } } function event(listener) { listeners.push(listener); return removeListener; function removeListener() { var index = listeners.indexOf(listener); if (index !== -1) { listeners.splice(index, 1); } } } } },{}],29:[function(_dereq_,module,exports){ 'use strict'; var Event = _dereq_('./event.js'); module.exports = Source; function Source(broadcaster) { var tuple = Event(); broadcaster(tuple.broadcast); return tuple.listen; } },{"./event.js":28}],30:[function(_dereq_,module,exports){ (function (global){ 'use strict'; var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {}; var minDoc = _dereq_('min-document'); var doccy; if (typeof document !== 'undefined') { doccy = document; } else { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } } module.exports = doccy; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"min-document":6}],31:[function(_dereq_,module,exports){ (function (global){ "use strict"; var win; if (typeof window !== "undefined") { win = window; } else if (typeof global !== "undefined") { win = global; } else if (typeof self !== "undefined") { win = self; } else { win = {}; } module.exports = win; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],32:[function(_dereq_,module,exports){ 'use strict'; module.exports = shim; function shim(element, value) { if (value === undefined) { return element.style.display === 'none'; } element.style.display = value ? 'none' : ''; } },{}],33:[function(_dereq_,module,exports){ 'use strict'; // HumanizeDuration.js - http://git.io/j0HgmQ ;(function () { var languages = { ar: { y: function y(c) { return c === 1 ? 'سنة' : 'سنوات'; }, mo: function mo(c) { return c === 1 ? 'شهر' : 'أشهر'; }, w: function w(c) { return c === 1 ? 'أسبوع' : 'أسابيع'; }, d: function d(c) { return c === 1 ? 'يوم' : 'أيام'; }, h: function h(c) { return c === 1 ? 'ساعة' : 'ساعات'; }, m: function m(c) { return c === 1 ? 'دقيقة' : 'دقائق'; }, s: function s(c) { return c === 1 ? 'ثانية' : 'ثواني'; }, ms: function ms(c) { return c === 1 ? 'جزء من الثانية' : 'أجزاء من الثانية'; }, decimal: ',' }, bg: { y: function y(c) { return ['години', 'година', 'години'][getSlavicForm(c)]; }, mo: function mo(c) { return ['месеца', 'месец', 'месеца'][getSlavicForm(c)]; }, w: function w(c) { return ['седмици', 'седмица', 'седмици'][getSlavicForm(c)]; }, d: function d(c) { return ['дни', 'ден', 'дни'][getSlavicForm(c)]; }, h: function h(c) { return ['часа', 'час', 'часа'][getSlavicForm(c)]; }, m: function m(c) { return ['минути', 'минута', 'минути'][getSlavicForm(c)]; }, s: function s(c) { return ['секунди', 'секунда', 'секунди'][getSlavicForm(c)]; }, ms: function ms(c) { return ['милисекунди', 'милисекунда', 'милисекунди'][getSlavicForm(c)]; }, decimal: ',' }, ca: { y: function y(c) { return 'any' + (c === 1 ? '' : 's'); }, mo: function mo(c) { return 'mes' + (c === 1 ? '' : 'os'); }, w: function w(c) { return 'setman' + (c === 1 ? 'a' : 'es'); }, d: function d(c) { return 'di' + (c === 1 ? 'a' : 'es'); }, h: function h(c) { return 'hor' + (c === 1 ? 'a' : 'es'); }, m: function m(c) { return 'minut' + (c === 1 ? '' : 's'); }, s: function s(c) { return 'segon' + (c === 1 ? '' : 's'); }, ms: function ms(c) { return 'milisegon' + (c === 1 ? '' : 's'); }, decimal: ',' }, cs: { y: function y(c) { return ['rok', 'roku', 'roky', 'let'][getCzechForm(c)]; }, mo: function mo(c) { return ['měsíc', 'měsíce', 'měsíce', 'měsíců'][getCzechForm(c)]; }, w: function w(c) { return ['týden', 'týdne', 'týdny', 'týdnů'][getCzechForm(c)]; }, d: function d(c) { return ['den', 'dne', 'dny', 'dní'][getCzechForm(c)]; }, h: function h(c) { return ['hodina', 'hodiny', 'hodiny', 'hodin'][getCzechForm(c)]; }, m: function m(c) { return ['minuta', 'minuty', 'minuty', 'minut'][getCzechForm(c)]; }, s: function s(c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getCzechForm(c)]; }, ms: function ms(c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getCzechForm(c)]; }, decimal: ',' }, da: { y: 'år', mo: function mo(c) { return 'måned' + (c === 1 ? '' : 'er'); }, w: function w(c) { return 'uge' + (c === 1 ? '' : 'r'); }, d: function d(c) { return 'dag' + (c === 1 ? '' : 'e'); }, h: function h(c) { return 'time' + (c === 1 ? '' : 'r'); }, m: function m(c) { return 'minut' + (c === 1 ? '' : 'ter'); }, s: function s(c) { return 'sekund' + (c === 1 ? '' : 'er'); }, ms: function ms(c) { return 'millisekund' + (c === 1 ? '' : 'er'); }, decimal: ',' }, de: { y: function y(c) { return 'Jahr' + (c === 1 ? '' : 'e'); }, mo: function mo(c) { return 'Monat' + (c === 1 ? '' : 'e'); }, w: function w(c) { return 'Woche' + (c === 1 ? '' : 'n'); }, d: function d(c) { return 'Tag' + (c === 1 ? '' : 'e'); }, h: function h(c) { return 'Stunde' + (c === 1 ? '' : 'n'); }, m: function m(c) { return 'Minute' + (c === 1 ? '' : 'n'); }, s: function s(c) { return 'Sekunde' + (c === 1 ? '' : 'n'); }, ms: function ms(c) { return 'Millisekunde' + (c === 1 ? '' : 'n'); }, decimal: ',' }, en: { y: function y(c) { return 'year' + (c === 1 ? '' : 's'); }, mo: function mo(c) { return 'month' + (c === 1 ? '' : 's'); }, w: function w(c) { return 'week' + (c === 1 ? '' : 's'); }, d: function d(c) { return 'day' + (c === 1 ? '' : 's'); }, h: function h(c) { return 'hour' + (c === 1 ? '' : 's'); }, m: function m(c) { return 'minute' + (c === 1 ? '' : 's'); }, s: function s(c) { return 'second' + (c === 1 ? '' : 's'); }, ms: function ms(c) { return 'millisecond' + (c === 1 ? '' : 's'); }, decimal: '.' }, es: { y: function y(c) { return 'año' + (c === 1 ? '' : 's'); }, mo: function mo(c) { return 'mes' + (c === 1 ? '' : 'es'); }, w: function w(c) { return 'semana' + (c === 1 ? '' : 's'); }, d: function d(c) { return 'día' + (c === 1 ? '' : 's'); }, h: function h(c) { return 'hora' + (c === 1 ? '' : 's'); }, m: function m(c) { return 'minuto' + (c === 1 ? '' : 's'); }, s: function s(c) { return 'segundo' + (c === 1 ? '' : 's'); }, ms: function ms(c) { return 'milisegundo' + (c === 1 ? '' : 's'); }, decimal: ',' }, fa: { y: 'سال', mo: 'ماه', w: 'هفته', d: 'روز', h: 'ساعت', m: 'دقیقه', s: 'ثانیه', ms: 'میلی ثانیه', decimal: '.' }, fi: { y: function y(c) { return c === 1 ? 'vuosi' : 'vuotta'; }, mo: function mo(c) { return c === 1 ? 'kuukausi' : 'kuukautta'; }, w: function w(c) { return 'viikko' + (c === 1 ? '' : 'a'); }, d: function d(c) { return 'päivä' + (c === 1 ? '' : 'ä'); }, h: function h(c) { return 'tunti' + (c === 1 ? '' : 'a'); }, m: function m(c) { return 'minuutti' + (c === 1 ? '' : 'a'); }, s: function s(c) { return 'sekunti' + (c === 1 ? '' : 'a'); }, ms: function ms(c) { return 'millisekunti' + (c === 1 ? '' : 'a'); }, decimal: ',' }, fr: { y: function y(c) { return 'an' + (c >= 2 ? 's' : ''); }, mo: 'mois', w: function w(c) { return 'semaine' + (c >= 2 ? 's' : ''); }, d: function d(c) { return 'jour' + (c >= 2 ? 's' : ''); }, h: function h(c) { return 'heure' + (c >= 2 ? 's' : ''); }, m: function m(c) { return 'minute' + (c >= 2 ? 's' : ''); }, s: function s(c) { return 'seconde' + (c >= 2 ? 's' : ''); }, ms: function ms(c) { return 'milliseconde' + (c >= 2 ? 's' : ''); }, decimal: ',' }, gr: { y: function y(c) { return c === 1 ? 'χρόνος' : 'χρόνια'; }, mo: function mo(c) { return c === 1 ? 'μήνας' : 'μήνες'; }, w: function w(c) { return c === 1 ? 'εβδομάδα' : 'εβδομάδες'; }, d: function d(c) { return c === 1 ? 'μέρα' : 'μέρες'; }, h: function h(c) { return c === 1 ? 'ώρα' : 'ώρες'; }, m: function m(c) { return c === 1 ? 'λεπτό' : 'λεπτά'; }, s: function s(c) { return c === 1 ? 'δευτερόλεπτο' : 'δευτερόλεπτα'; }, ms: function ms(c) { return c === 1 ? 'χιλιοστό του δευτερολέπτου' : 'χιλιοστά του δευτερολέπτου'; }, decimal: ',' }, hu: { y: 'év', mo: 'hónap', w: 'hét', d: 'nap', h: 'óra', m: 'perc', s: 'másodperc', ms: 'ezredmásodperc', decimal: ',' }, id: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'menit', s: 'detik', ms: 'milidetik', decimal: '.' }, is: { y: 'ár', mo: function mo(c) { return 'mánuð' + (c === 1 ? 'ur' : 'ir'); }, w: function w(c) { return 'vik' + (c === 1 ? 'a' : 'ur'); }, d: function d(c) { return 'dag' + (c === 1 ? 'ur' : 'ar'); }, h: function h(c) { return 'klukkutím' + (c === 1 ? 'i' : 'ar'); }, m: function m(c) { return 'mínút' + (c === 1 ? 'a' : 'ur'); }, s: function s(c) { return 'sekúnd' + (c === 1 ? 'a' : 'ur'); }, ms: function ms(c) { return 'millisekúnd' + (c === 1 ? 'a' : 'ur'); }, decimal: '.' }, it: { y: function y(c) { return 'ann' + (c === 1 ? 'o' : 'i'); }, mo: function mo(c) { return 'mes' + (c === 1 ? 'e' : 'i'); }, w: function w(c) { return 'settiman' + (c === 1 ? 'a' : 'e'); }, d: function d(c) { return 'giorn' + (c === 1 ? 'o' : 'i'); }, h: function h(c) { return 'or' + (c === 1 ? 'a' : 'e'); }, m: function m(c) { return 'minut' + (c === 1 ? 'o' : 'i'); }, s: function s(c) { return 'second' + (c === 1 ? 'o' : 'i'); }, ms: function ms(c) { return 'millisecond' + (c === 1 ? 'o' : 'i'); }, decimal: ',' }, ja: { y: '年', mo: '月', w: '週', d: '日', h: '時間', m: '分', s: '秒', ms: 'ミリ秒', decimal: '.' }, ko: { y: '년', mo: '개월', w: '주일', d: '일', h: '시간', m: '분', s: '초', ms: '밀리 초', decimal: '.' }, lt: { y: function y(c) { return c % 10 === 0 || c % 100 >= 10 && c % 100 <= 20 ? 'metų' : 'metai'; }, mo: function mo(c) { return ['mėnuo', 'mėnesiai', 'mėnesių'][getLithuanianForm(c)]; }, w: function w(c) { return ['savaitė', 'savaitės', 'savaičių'][getLithuanianForm(c)]; }, d: function d(c) { return ['diena', 'dienos', 'dienų'][getLithuanianForm(c)]; }, h: function h(c) { return ['valanda', 'valandos', 'valandų'][getLithuanianForm(c)]; }, m: function m(c) { return ['minutė', 'minutės', 'minučių'][getLithuanianForm(c)]; }, s: function s(c) { return ['sekundė', 'sekundės', 'sekundžių'][getLithuanianForm(c)]; }, ms: function ms(c) { return ['milisekundė', 'milisekundės', 'milisekundžių'][getLithuanianForm(c)]; }, decimal: ',' }, ms: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'minit', s: 'saat', ms: 'milisaat', decimal: '.' }, nl: { y: 'jaar', mo: function mo(c) { return c === 1 ? 'maand' : 'maanden'; }, w: function w(c) { return c === 1 ? 'week' : 'weken'; }, d: function d(c) { return c === 1 ? 'dag' : 'dagen'; }, h: 'uur', m: function m(c) { return c === 1 ? 'minuut' : 'minuten'; }, s: function s(c) { return c === 1 ? 'seconde' : 'seconden'; }, ms: function ms(c) { return c === 1 ? 'milliseconde' : 'milliseconden'; }, decimal: ',' }, no: { y: 'år', mo: function mo(c) { return 'måned' + (c === 1 ? '' : 'er'); }, w: function w(c) { return 'uke' + (c === 1 ? '' : 'r'); }, d: function d(c) { return 'dag' + (c === 1 ? '' : 'er'); }, h: function h(c) { return 'time' + (c === 1 ? '' : 'r'); }, m: function m(c) { return 'minutt' + (c === 1 ? '' : 'er'); }, s: function s(c) { return 'sekund' + (c === 1 ? '' : 'er'); }, ms: function ms(c) { return 'millisekund' + (c === 1 ? '' : 'er'); }, decimal: ',' }, pl: { y: function y(c) { return ['rok', 'roku', 'lata', 'lat'][getPolishForm(c)]; }, mo: function mo(c) { return ['miesiąc', 'miesiąca', 'miesiące', 'miesięcy'][getPolishForm(c)]; }, w: function w(c) { return ['tydzień', 'tygodnia', 'tygodnie', 'tygodni'][getPolishForm(c)]; }, d: function d(c) { return ['dzień', 'dnia', 'dni', 'dni'][getPolishForm(c)]; }, h: function h(c) { return ['godzina', 'godziny', 'godziny', 'godzin'][getPolishForm(c)]; }, m: function m(c) { return ['minuta', 'minuty', 'minuty', 'minut'][getPolishForm(c)]; }, s: function s(c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getPolishForm(c)]; }, ms: function ms(c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getPolishForm(c)]; }, decimal: ',' }, pt: { y: function y(c) { return 'ano' + (c === 1 ? '' : 's'); }, mo: function mo(c) { return c === 1 ? 'mês' : 'meses'; }, w: function w(c) { return 'semana' + (c === 1 ? '' : 's'); }, d: function d(c) { return 'dia' + (c === 1 ? '' : 's'); }, h: function h(c) { return 'hora' + (c === 1 ? '' : 's'); }, m: function m(c) { return 'minuto' + (c === 1 ? '' : 's'); }, s: function s(c) { return 'segundo' + (c === 1 ? '' : 's'); }, ms: function ms(c) { return 'milissegundo' + (c === 1 ? '' : 's'); }, decimal: ',' }, ru: { y: function y(c) { return ['лет', 'год', 'года'][getSlavicForm(c)]; }, mo: function mo(c) { return ['месяцев', 'месяц', 'месяца'][getSlavicForm(c)]; }, w: function w(c) { return ['недель', 'неделя', 'недели'][getSlavicForm(c)]; }, d: function d(c) { return ['дней', 'день', 'дня'][getSlavicForm(c)]; }, h: function h(c) { return ['часов', 'час', 'часа'][getSlavicForm(c)]; }, m: function m(c) { return ['минут', 'минута', 'минуты'][getSlavicForm(c)]; }, s: function s(c) { return ['секунд', 'секунда', 'секунды'][getSlavicForm(c)]; }, ms: function ms(c) { return ['миллисекунд', 'миллисекунда', 'миллисекунды'][getSlavicForm(c)]; }, decimal: ',' }, uk: { y: function y(c) { return ['років', 'рік', 'роки'][getSlavicForm(c)]; }, mo: function mo(c) { return ['місяців', 'місяць', 'місяці'][getSlavicForm(c)]; }, w: function w(c) { return ['тижнів', 'тиждень', 'тижні'][getSlavicForm(c)]; }, d: function d(c) { return ['днів', 'день', 'дні'][getSlavicForm(c)]; }, h: function h(c) { return ['годин', 'година', 'години'][getSlavicForm(c)]; }, m: function m(c) { return ['хвилин', 'хвилина', 'хвилини'][getSlavicForm(c)]; }, s: function s(c) { return ['секунд', 'секунда', 'секунди'][getSlavicForm(c)]; }, ms: function ms(c) { return ['мілісекунд', 'мілісекунда', 'мілісекунди'][getSlavicForm(c)]; }, decimal: ',' }, sv: { y: 'år', mo: function mo(c) { return 'månad' + (c === 1 ? '' : 'er'); }, w: function w(c) { return 'veck' + (c === 1 ? 'a' : 'or'); }, d: function d(c) { return 'dag' + (c === 1 ? '' : 'ar'); }, h: function h(c) { return 'timm' + (c === 1 ? 'e' : 'ar'); }, m: function m(c) { return 'minut' + (c === 1 ? '' : 'er'); }, s: function s(c) { return 'sekund' + (c === 1 ? '' : 'er'); }, ms: function ms(c) { return 'millisekund' + (c === 1 ? '' : 'er'); }, decimal: ',' }, tr: { y: 'yıl', mo: 'ay', w: 'hafta', d: 'gün', h: 'saat', m: 'dakika', s: 'saniye', ms: 'milisaniye', decimal: ',' }, vi: { y: 'năm', mo: 'tháng', w: 'tuần', d: 'ngày', h: 'giờ', m: 'phút', s: 'giây', ms: 'mili giây', decimal: ',' }, zh_CN: { y: '年', mo: '个月', w: '周', d: '天', h: '小时', m: '分钟', s: '秒', ms: '毫秒', decimal: '.' }, zh_TW: { y: '年', mo: '個月', w: '周', d: '天', h: '小時', m: '分鐘', s: '秒', ms: '毫秒', decimal: '.' } // You can create a humanizer, which returns a function with default // parameters. };function humanizer(passedOptions) { var result = function humanizer(ms, humanizerOptions) { var options = extend({}, result, humanizerOptions || {}); return doHumanization(ms, options); }; return extend(result, { language: 'en', delimiter: ', ', spacer: ' ', conjunction: '', serialComma: true, units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'], languages: {}, round: false, unitMeasures: { y: 31557600000, mo: 2629800000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000, ms: 1 } }, passedOptions); } // The main function is just a wrapper around a default humanizer. var humanizeDuration = humanizer({}); // doHumanization does the bulk of the work. function doHumanization(ms, options) { var i, len, piece; // Make sure we have a positive number. // Has the nice sideffect of turning Number objects into primitives. ms = Math.abs(ms); var dictionary = options.languages[options.language] || languages[options.language]; if (!dictionary) { throw new Error('No language ' + dictionary + '.'); } var pieces = []; // Start at the top and keep removing units, bit by bit. var unitName, unitMS, unitCount; for (i = 0, len = options.units.length; i < len; i++) { unitName = options.units[i]; unitMS = options.unitMeasures[unitName]; // What's the number of full units we can fit? if (i + 1 === len) { unitCount = ms / unitMS; } else { unitCount = Math.floor(ms / unitMS); } // Add the string. pieces.push({ unitCount: unitCount, unitName: unitName }); // Remove what we just figured out. ms -= unitCount * unitMS; } var firstOccupiedUnitIndex = 0; for (i = 0; i < pieces.length; i++) { if (pieces[i].unitCount) { firstOccupiedUnitIndex = i; break; } } if (options.round) { var ratioToLargerUnit, previousPiece; for (i = pieces.length - 1; i >= 0; i--) { piece = pieces[i]; piece.unitCount = Math.round(piece.unitCount); if (i === 0) { break; } previousPiece = pieces[i - 1]; ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName]; if (piece.unitCount % ratioToLargerUnit === 0 || options.largest && options.largest - 1 < i - firstOccupiedUnitIndex) { previousPiece.unitCount += piece.unitCount / ratioToLargerUnit; piece.unitCount = 0; } } } var result = []; for (i = 0, pieces.length; i < len; i++) { piece = pieces[i]; if (piece.unitCount) { result.push(render(piece.unitCount, piece.unitName, dictionary, options)); } if (result.length === options.largest) { break; } } if (result.length) { if (!options.conjunction || result.length === 1) { return result.join(options.delimiter); } else if (result.length === 2) { return result.join(options.conjunction); } else if (result.length > 2) { return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1); } } else { return render(0, options.units[options.units.length - 1], dictionary, options); } } function render(count, type, dictionary, options) { var decimal; if (options.decimal === void 0) { decimal = dictionary.decimal; } else { decimal = options.decimal; } var countStr = count.toString().replace('.', decimal); var dictionaryValue = dictionary[type]; var word; if (typeof dictionaryValue === 'function') { word = dictionaryValue(count); } else { word = dictionaryValue; } return countStr + options.spacer + word; } function extend(destination) { var source; for (var i = 1; i < arguments.length; i++) { source = arguments[i]; for (var prop in source) { if (source.hasOwnProperty(prop)) { destination[prop] = source[prop]; } } } return destination; } // Internal helper function for Czech language. function getCzechForm(c) { if (c === 1) { return 0; } else if (Math.floor(c) !== c) { return 1; } else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) { return 2; } else { return 3; } } // Internal helper function for Polish language. function getPolishForm(c) { if (c === 1) { return 0; } else if (Math.floor(c) !== c) { return 1; } else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) { return 2; } else { return 3; } } // Internal helper function for Russian and Ukranian languages. function getSlavicForm(c) { if (Math.floor(c) !== c) { return 2; } else if (c % 100 >= 5 && c % 100 <= 20 || c % 10 >= 5 && c % 10 <= 9 || c % 10 === 0) { return 0; } else if (c % 10 === 1) { return 1; } else if (c > 1) { return 2; } else { return 0; } } // Internal helper function for Lithuanian language. function getLithuanianForm(c) { if (c === 1 || c % 10 === 1 && c % 100 > 20) { return 0; } else if (Math.floor(c) !== c || c % 10 >= 2 && c % 100 > 20 || c % 10 >= 2 && c % 100 < 10) { return 1; } else { return 2; } } humanizeDuration.getSupportedLanguages = function getSupportedLanguages() { var result = []; for (var language in languages) { if (languages.hasOwnProperty(language)) { result.push(language); } } return result; }; humanizeDuration.humanizer = humanizer; if (typeof define === 'function' && define.amd) { define(function () { return humanizeDuration; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = humanizeDuration; } else { this.humanizeDuration = humanizeDuration; } })(); // eslint-disable-line semi },{}],34:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var split = _dereq_('browser-split'); var ClassList = _dereq_('class-list'); var w = typeof window === 'undefined' ? _dereq_('html-element') : window; var document = w.document; var Text = w.Text; function context() { var cleanupFuncs = []; function h() { var args = [].slice.call(arguments), e = null; function item(l) { var r; function parseClass(string) { // Our minimal parser doesn’t understand escaping CSS special // characters like `#`. Don’t use them. More reading: // https://mathiasbynens.be/notes/css-escapes . var m = split(string, /([\.#]?[^\s#.]+)/); if (/^\.|#/.test(m[1])) e = document.createElement('div'); forEach(m, function (v) { var s = v.substring(1, v.length); if (!v) return; if (!e) e = document.createElement(v);else if (v[0] === '.') ClassList(e).add(s);else if (v[0] === '#') e.setAttribute('id', s); }); } if (l == null) ;else if ('string' === typeof l) { if (!e) parseClass(l);else e.appendChild(r = document.createTextNode(l)); } else if ('number' === typeof l || 'boolean' === typeof l || l instanceof Date || l instanceof RegExp) { e.appendChild(r = document.createTextNode(l.toString())); } //there might be a better way to handle this... else if (isArray(l)) forEach(l, item);else if (isNode(l)) e.appendChild(r = l);else if (l instanceof Text) e.appendChild(r = l);else if ('object' === (typeof l === 'undefined' ? 'undefined' : _typeof(l))) { for (var k in l) { if ('function' === typeof l[k]) { if (/^on\w+/.test(k)) { (function (k, l) { // capture k, l in the closure if (e.addEventListener) { e.addEventListener(k.substring(2), l[k], false); cleanupFuncs.push(function () { e.removeEventListener(k.substring(2), l[k], false); }); } else { e.attachEvent(k, l[k]); cleanupFuncs.push(function () { e.detachEvent(k, l[k]); }); } })(k, l); } else { // observable e[k] = l[k](); cleanupFuncs.push(l[k](function (v) { e[k] = v; })); } } else if (k === 'style') { if ('string' === typeof l[k]) { e.style.cssText = l[k]; } else { for (var s in l[k]) { (function (s, v) { if ('function' === typeof v) { // observable e.style.setProperty(s, v()); cleanupFuncs.push(v(function (val) { e.style.setProperty(s, val); })); } else var match = l[k][s].match(/(.*)\W+!important\W*$/); if (match) { e.style.setProperty(s, match[1], 'important'); } else { e.style.setProperty(s, l[k][s]); } })(s, l[k][s]); } } } else if (k === 'attrs') { for (var v in l[k]) { e.setAttribute(v, l[k][v]); } } else if (k.substr(0, 5) === "data-") { e.setAttribute(k, l[k]); } else { e[k] = l[k]; } } } else if ('function' === typeof l) { //assume it's an observable! var v = l(); e.appendChild(r = isNode(v) ? v : document.createTextNode(v)); cleanupFuncs.push(l(function (v) { if (isNode(v) && r.parentElement) r.parentElement.replaceChild(v, r), r = v;else r.textContent = v; })); } return r; } while (args.length) { item(args.shift()); }return e; } h.cleanup = function () { for (var i = 0; i < cleanupFuncs.length; i++) { cleanupFuncs[i](); } cleanupFuncs.length = 0; }; return h; } var h = module.exports = context(); h.context = context; function isNode(el) { return el && el.nodeName && el.nodeType; } function forEach(arr, fn) { if (arr.forEach) return arr.forEach(fn); for (var i = 0; i < arr.length; i++) { fn(arr[i], i); } } function isArray(arr) { return Object.prototype.toString.call(arr) == '[object Array]'; } },{"browser-split":7,"class-list":10,"html-element":6}],35:[function(_dereq_,module,exports){ "use strict"; exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & (1 << -nBits) - 1; s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; }; },{}],36:[function(_dereq_,module,exports){ "use strict"; var indexOf = [].indexOf; module.exports = function (arr, obj) { if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],37:[function(_dereq_,module,exports){ 'use strict'; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function TempCtor() {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } },{}],38:[function(_dereq_,module,exports){ 'use strict'; var containers = []; // will store container HTMLElement references var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement} var usage = 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).'; function insertCss(css, options) { options = options || {}; if (css === undefined) { throw new Error(usage); } var position = options.prepend === true ? 'prepend' : 'append'; var container = options.container !== undefined ? options.container : document.querySelector('head'); var containerId = containers.indexOf(container); // first time we see this container, create the necessary entries if (containerId === -1) { containerId = containers.push(container) - 1; styleElements[containerId] = {}; } // try to get the correponding container + position styleElement, create it otherwise var styleElement; if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) { styleElement = styleElements[containerId][position]; } else { styleElement = styleElements[containerId][position] = createStyleElement(); if (position === 'prepend') { container.insertBefore(styleElement, container.childNodes[0]); } else { container.appendChild(styleElement); } } // strip potential UTF-8 BOM if css was read from a file if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); } // actually add the stylesheet if (styleElement.styleSheet) { styleElement.styleSheet.cssText += css; } else { styleElement.textContent += css; } return styleElement; }; function createStyleElement() { var styleElement = document.createElement('style'); styleElement.setAttribute('type', 'text/css'); return styleElement; } module.exports = insertCss; module.exports.insertCss = insertCss; },{}],39:[function(_dereq_,module,exports){ /*! npm.im/intervalometer */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function intervalometer(cb, request, cancel, requestParameter) { var requestId; var previousLoopTime; function loop(now) { // must be requested before cb() because that might call .stop() requestId = request(loop, requestParameter); // called with "ms since last call". 0 on start() cb(now - (previousLoopTime || now)); previousLoopTime = now; } return { start: function start() { if (!requestId) { // prevent double starts loop(0); } }, stop: function stop() { cancel(requestId); requestId = null; previousLoopTime = 0; } }; } function frameIntervalometer(cb) { return intervalometer(cb, requestAnimationFrame, cancelAnimationFrame); } function timerIntervalometer(cb, delay) { return intervalometer(cb, setTimeout, clearTimeout, delay); } exports.intervalometer = intervalometer; exports.frameIntervalometer = frameIntervalometer; exports.timerIntervalometer = timerIntervalometer; },{}],40:[function(_dereq_,module,exports){ /*! npm.im/iphone-inline-video 2.2.2 */ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var intervalometer = _dereq_('intervalometer'); function preventEvent(element, eventName, test) { function handler(e) { if (!test || test(element, eventName)) { e.stopImmediatePropagation(); // // console.log(eventName, 'prevented on', element); } } element.addEventListener(eventName, handler); // Return handler to allow to disable the prevention. Usage: // const preventionHandler = preventEvent(el, 'click'); // el.removeEventHandler('click', preventionHandler); return handler; } function proxyProperty(object, propertyName, sourceObject, copyFirst) { function get() { return sourceObject[propertyName]; } function set(value) { sourceObject[propertyName] = value; } if (copyFirst) { set(object[propertyName]); } Object.defineProperty(object, propertyName, { get: get, set: set }); } function proxyEvent(object, eventName, sourceObject) { sourceObject.addEventListener(eventName, function () { return object.dispatchEvent(new Event(eventName)); }); } function dispatchEventAsync(element, type) { Promise.resolve().then(function () { element.dispatchEvent(new Event(type)); }); } var iOS8or9 = (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object' && 'object-fit' in document.head.style && !matchMedia('(-webkit-video-playable-inline)').matches; var IIV = 'bfred-it:iphone-inline-video'; var IIVEvent = 'bfred-it:iphone-inline-video:event'; var IIVPlay = 'bfred-it:iphone-inline-video:nativeplay'; var IIVPause = 'bfred-it:iphone-inline-video:nativepause'; /** * UTILS */ function getAudioFromVideo(video) { var audio = new Audio(); proxyEvent(video, 'play', audio); proxyEvent(video, 'playing', audio); proxyEvent(video, 'pause', audio); audio.crossOrigin = video.crossOrigin; // 'data:' causes audio.networkState > 0 // which then allows to keep <audio> in a resumable playing state // i.e. once you set a real src it will keep playing if it was if .play() was called audio.src = video.src || video.currentSrc || 'data:'; // // if (audio.src === 'data:') { // TODO: wait for video to be selected // // } return audio; } var lastRequests = []; var requestIndex = 0; var lastTimeupdateEvent; function setTime(video, time, rememberOnly) { // Allow one timeupdate event every 200+ ms if ((lastTimeupdateEvent || 0) + 200 < Date.now()) { video[IIVEvent] = true; lastTimeupdateEvent = Date.now(); } if (!rememberOnly) { video.currentTime = time; } lastRequests[++requestIndex % 3] = time * 100 | 0 / 100; } function isPlayerEnded(player) { return player.driver.currentTime >= player.video.duration; } function update(timeDiff) { var player = this; // // console.log('update', player.video.readyState, player.video.networkState, player.driver.readyState, player.driver.networkState, player.driver.paused); if (player.video.readyState >= player.video.HAVE_FUTURE_DATA) { if (!player.hasAudio) { player.driver.currentTime = player.video.currentTime + timeDiff * player.video.playbackRate / 1000; if (player.video.loop && isPlayerEnded(player)) { player.driver.currentTime = 0; } } setTime(player.video, player.driver.currentTime); } else if (player.video.networkState === player.video.NETWORK_IDLE && player.video.buffered.length === 0) { // This should happen when the source is available but: // - it's potentially playing (.paused === false) // - it's not ready to play // - it's not loading // If it hasAudio, that will be loaded in the 'emptied' handler below player.video.load(); // // console.log('Will load'); } // // console.assert(player.video.currentTime === player.driver.currentTime, 'Video not updating!'); if (player.video.ended) { delete player.video[IIVEvent]; // Allow timeupdate event player.video.pause(true); } } /** * METHODS */ function play() { // // console.log('play'); var video = this; var player = video[IIV]; // If it's fullscreen, use the native player if (video.webkitDisplayingFullscreen) { video[IIVPlay](); return; } if (player.driver.src !== 'data:' && player.driver.src !== video.src) { // // console.log('src changed on play', video.src); setTime(video, 0, true); player.driver.src = video.src; } if (!video.paused) { return; } player.paused = false; if (video.buffered.length === 0) { // .load() causes the emptied event // the alternative is .play()+.pause() but that triggers play/pause events, even worse // possibly the alternative is preventing this event only once video.load(); } player.driver.play(); player.updater.start(); if (!player.hasAudio) { dispatchEventAsync(video, 'play'); if (player.video.readyState >= player.video.HAVE_ENOUGH_DATA) { // // console.log('onplay'); dispatchEventAsync(video, 'playing'); } } } function pause(forceEvents) { // // console.log('pause'); var video = this; var player = video[IIV]; player.driver.pause(); player.updater.stop(); // If it's fullscreen, the developer the native player.pause() // This is at the end of pause() because it also // needs to make sure that the simulation is paused if (video.webkitDisplayingFullscreen) { video[IIVPause](); } if (player.paused && !forceEvents) { return; } player.paused = true; if (!player.hasAudio) { dispatchEventAsync(video, 'pause'); } // Handle the 'ended' event only if it's not fullscreen if (video.ended && !video.webkitDisplayingFullscreen) { video[IIVEvent] = true; dispatchEventAsync(video, 'ended'); } } /** * SETUP */ function addPlayer(video, hasAudio) { var player = {}; video[IIV] = player; player.paused = true; // Track whether 'pause' events have been fired player.hasAudio = hasAudio; player.video = video; player.updater = intervalometer.frameIntervalometer(update.bind(player)); if (hasAudio) { player.driver = getAudioFromVideo(video); } else { video.addEventListener('canplay', function () { if (!video.paused) { // // console.log('oncanplay'); dispatchEventAsync(video, 'playing'); } }); player.driver = { src: video.src || video.currentSrc || 'data:', muted: true, paused: true, pause: function pause() { player.driver.paused = true; }, play: function play() { player.driver.paused = false; // Media automatically goes to 0 if .play() is called when it's done if (isPlayerEnded(player)) { setTime(video, 0); } }, get ended() { return isPlayerEnded(player); } }; } // .load() causes the emptied event video.addEventListener('emptied', function () { // // console.log('driver src is', player.driver.src); var wasEmpty = !player.driver.src || player.driver.src === 'data:'; if (player.driver.src && player.driver.src !== video.src) { // // console.log('src changed to', video.src); setTime(video, 0, true); player.driver.src = video.src; // Playing videos will only keep playing if no src was present when .play()’ed if (wasEmpty || !hasAudio && video.autoplay) { player.driver.play(); } else { player.updater.stop(); } } }, false); // Stop programmatic player when OS takes over video.addEventListener('webkitbeginfullscreen', function () { if (!video.paused) { // Make sure that the <audio> and the syncer/updater are stopped video.pause(); // Play video natively video[IIVPlay](); } else if (hasAudio && player.driver.buffered.length === 0) { // If the first play is native, // the <audio> needs to be buffered manually // so when the fullscreen ends, it can be set to the same current time player.driver.load(); } }); if (hasAudio) { video.addEventListener('webkitendfullscreen', function () { // Sync audio to new video position player.driver.currentTime = video.currentTime; // // console.assert(player.driver.currentTime === video.currentTime, 'Audio not synced'); }); // Allow seeking video.addEventListener('seeking', function () { if (lastRequests.indexOf(video.currentTime * 100 | 0 / 100) < 0) { // // console.log('User-requested seeking'); player.driver.currentTime = video.currentTime; } }); } } function preventWithPropOrFullscreen(el) { var isAllowed = el[IIVEvent]; delete el[IIVEvent]; return !el.webkitDisplayingFullscreen && !isAllowed; } function overloadAPI(video) { var player = video[IIV]; video[IIVPlay] = video.play; video[IIVPause] = video.pause; video.play = play; video.pause = pause; proxyProperty(video, 'paused', player.driver); proxyProperty(video, 'muted', player.driver, true); proxyProperty(video, 'playbackRate', player.driver, true); proxyProperty(video, 'ended', player.driver); proxyProperty(video, 'loop', player.driver, true); // IIV works by seeking 60 times per second. // These events are now useless. preventEvent(video, 'seeking', function (el) { return !el.webkitDisplayingFullscreen; }); preventEvent(video, 'seeked', function (el) { return !el.webkitDisplayingFullscreen; }); // Limit timeupdate events preventEvent(video, 'timeupdate', preventWithPropOrFullscreen); // Prevent occasional native ended events preventEvent(video, 'ended', preventWithPropOrFullscreen); } function enableInlineVideo(video, opts) { if (opts === void 0) opts = {}; // Stop if already enabled if (video[IIV]) { return; } // Allow the user to skip detection if (!opts.everywhere) { // Only iOS8 and 9 are supported if (!iOS8or9) { return; } // Stop if it's not an allowed device if (!(opts.iPad || opts.ipad ? /iPhone|iPod|iPad/ : /iPhone|iPod/).test(navigator.userAgent)) { return; } } // Try to pause video.pause(); // Prevent autoplay. // An non-started autoplaying video can't be .pause()'d var willAutoplay = video.autoplay; video.autoplay = false; addPlayer(video, !video.muted); overloadAPI(video); video.classList.add('IIV'); // Autoplay if (video.muted && willAutoplay) { video.play(); video.addEventListener('playing', function restoreAutoplay() { video.autoplay = true; video.removeEventListener('playing', restoreAutoplay); }); } if (!/iPhone|iPod|iPad/.test(navigator.platform)) { console.warn('iphone-inline-video is not guaranteed to work in emulated environments'); } } module.exports = enableInlineVideo; },{"intervalometer":39}],41:[function(_dereq_,module,exports){ 'use strict'; /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer); }; function isBuffer(obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); } // For Node v0.10 support. Remove this eventually. function isSlowBuffer(obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)); } },{}],42:[function(_dereq_,module,exports){ 'use strict'; var numberIsNan = _dereq_('number-is-nan'); module.exports = Number.isFinite || function (val) { return !(typeof val !== 'number' || numberIsNan(val) || val === Infinity || val === -Infinity); }; },{"number-is-nan":48}],43:[function(_dereq_,module,exports){ "use strict"; module.exports = isPowerOfTwo; function isPowerOfTwo(n) { return n !== 0 && (n & n - 1) === 0; } },{}],44:[function(_dereq_,module,exports){ 'use strict'; module.exports = isTypedArray; isTypedArray.strict = isStrictTypedArray; isTypedArray.loose = isLooseTypedArray; var toString = Object.prototype.toString; var names = { '[object Int8Array]': true, '[object Int16Array]': true, '[object Int32Array]': true, '[object Uint8Array]': true, '[object Uint8ClampedArray]': true, '[object Uint16Array]': true, '[object Uint32Array]': true, '[object Float32Array]': true, '[object Float64Array]': true }; function isTypedArray(arr) { return isStrictTypedArray(arr) || isLooseTypedArray(arr); } function isStrictTypedArray(arr) { return arr instanceof Int8Array || arr instanceof Int16Array || arr instanceof Int32Array || arr instanceof Uint8Array || arr instanceof Uint8ClampedArray || arr instanceof Uint16Array || arr instanceof Uint32Array || arr instanceof Float32Array || arr instanceof Float64Array; } function isLooseTypedArray(arr) { return names[toString.call(arr)]; } },{}],45:[function(_dereq_,module,exports){ 'use strict'; var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ "use strict"; /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function keyMirror(obj) { var ret = {}; var key; if (!(obj instanceof Object && !Array.isArray(obj))) { throw new Error('keyMirror(...): Argument must be an object.'); } for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{}],47:[function(_dereq_,module,exports){ 'use strict'; var numberIsFinite = _dereq_('is-finite'); module.exports = Number.isInteger || function (x) { return numberIsFinite(x) && Math.floor(x) === x; }; },{"is-finite":42}],48:[function(_dereq_,module,exports){ 'use strict'; module.exports = Number.isNaN || function (x) { return x !== x; }; },{}],49:[function(_dereq_,module,exports){ 'use strict'; var wrappy = _dereq_('wrappy'); module.exports = wrappy(once); module.exports.strict = wrappy(onceStrict); once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function value() { return once(this); }, configurable: true }); Object.defineProperty(Function.prototype, 'onceStrict', { value: function value() { return onceStrict(this); }, configurable: true }); }); function once(fn) { var f = function f() { if (f.called) return f.value; f.called = true; return f.value = fn.apply(this, arguments); }; f.called = false; return f; } function onceStrict(fn) { var f = function f() { if (f.called) throw new Error(f.onceError); f.called = true; return f.value = fn.apply(this, arguments); }; var name = fn.name || 'Function wrapped with `once`'; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f; } },{"wrappy":84}],50:[function(_dereq_,module,exports){ (function (process){ "use strict"; // Generated by CoffeeScript 1.12.2 (function () { var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; if (typeof performance !== "undefined" && performance !== null && performance.now) { module.exports = function () { return performance.now(); }; } else if (typeof process !== "undefined" && process !== null && process.hrtime) { module.exports = function () { return (getNanoSeconds() - nodeLoadTime) / 1e6; }; hrtime = process.hrtime; getNanoSeconds = function getNanoSeconds() { var hr; hr = hrtime(); return hr[0] * 1e9 + hr[1]; }; moduleLoadTime = getNanoSeconds(); upTime = process.uptime() * 1e9; nodeLoadTime = moduleLoadTime - upTime; } else if (Date.now) { module.exports = function () { return Date.now() - loadTime; }; loadTime = Date.now(); } else { module.exports = function () { return new Date().getTime() - loadTime; }; loadTime = new Date().getTime(); } }).call(undefined); }).call(this,_dereq_('_process')) },{"_process":51}],51:[function(_dereq_,module,exports){ 'use strict'; // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } })(); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return []; }; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; },{}],52:[function(_dereq_,module,exports){ (function (global){ 'use strict'; var now = _dereq_('performance-now'), root = typeof window === 'undefined' ? global : window, vendors = ['moz', 'webkit'], suffix = 'AnimationFrame', raf = root['request' + suffix], caf = root['cancel' + suffix] || root['cancelRequest' + suffix]; for (var i = 0; !raf && i < vendors.length; i++) { raf = root[vendors[i] + 'Request' + suffix]; caf = root[vendors[i] + 'Cancel' + suffix] || root[vendors[i] + 'CancelRequest' + suffix]; } // Some versions of FF have rAF but not cAF if (!raf || !caf) { var last = 0, id = 0, queue = [], frameDuration = 1000 / 60; raf = function raf(callback) { if (queue.length === 0) { var _now = now(), next = Math.max(0, frameDuration - (_now - last)); last = next + _now; setTimeout(function () { var cp = queue.slice(0); // Clear queue here to prevent // callbacks from appending listeners // to the current frame's queue queue.length = 0; for (var i = 0; i < cp.length; i++) { if (!cp[i].cancelled) { try { cp[i].callback(last); } catch (e) { setTimeout(function () { throw e; }, 0); } } } }, Math.round(next)); } queue.push({ handle: ++id, callback: callback, cancelled: false }); return id; }; caf = function caf(handle) { for (var i = 0; i < queue.length; i++) { if (queue[i].handle === handle) { queue[i].cancelled = true; } } }; } module.exports = function (fn) { // Wrap in a new function to prevent // `cancel` potentially being assigned // to the native rAF function return raf.call(root, fn); }; module.exports.cancel = function () { caf.apply(root, arguments); }; module.exports.polyfill = function (object) { if (!object) { object = root; } object.requestAnimationFrame = raf; object.cancelAnimationFrame = caf; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"performance-now":50}],53:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var pna = _dereq_('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /*</replacement>*/ module.exports = Duplex; /*<replacement>*/ var util = _dereq_('core-util-is'); util.inherits = _dereq_('inherits'); /*</replacement>*/ var Readable = _dereq_('./_stream_readable'); var Writable = _dereq_('./_stream_writable'); util.inherits(Duplex, Readable); var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } },{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":14,"inherits":37,"process-nextick-args":61}],54:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = _dereq_('./_stream_transform'); /*<replacement>*/ var util = _dereq_('core-util-is'); util.inherits = _dereq_('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":56,"core-util-is":14,"inherits":37}],55:[function(_dereq_,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /*<replacement>*/ var pna = _dereq_('process-nextick-args'); /*</replacement>*/ module.exports = Readable; /*<replacement>*/ var isArray = _dereq_('isarray'); /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Readable.ReadableState = ReadableState; /*<replacement>*/ var EE = _dereq_('events').EventEmitter; var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ /*<replacement>*/ var Stream = _dereq_('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = _dereq_('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ /*<replacement>*/ var util = _dereq_('core-util-is'); util.inherits = _dereq_('inherits'); /*</replacement>*/ /*<replacement>*/ var debugUtil = _dereq_('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function debug() {}; } /*</replacement>*/ var BufferList = _dereq_('./internal/streams/BufferList'); var destroyImpl = _dereq_('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || _dereq_('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || _dereq_('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":53,"./internal/streams/BufferList":58,"./internal/streams/destroy":59,"./internal/streams/stream":60,"_process":51,"core-util-is":14,"events":24,"inherits":37,"isarray":45,"process-nextick-args":61,"safe-buffer":67,"string_decoder/":62,"util":6}],56:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = _dereq_('./_stream_duplex'); /*<replacement>*/ var util = _dereq_('core-util-is'); util.inherits = _dereq_('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":53,"core-util-is":14,"inherits":37}],57:[function(_dereq_,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /*<replacement>*/ var pna = _dereq_('process-nextick-args'); /*</replacement>*/ module.exports = Writable; /* <replacement> */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* </replacement> */ /*<replacement>*/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = _dereq_('core-util-is'); util.inherits = _dereq_('inherits'); /*</replacement>*/ /*<replacement>*/ var internalUtil = { deprecate: _dereq_('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream = _dereq_('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = _dereq_('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ var destroyImpl = _dereq_('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || _dereq_('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function realHasInstance(object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || _dereq_('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /*<replacement>*/ asyncWrite(afterWrite, stream, state, finished, cb); /*</replacement>*/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":53,"./internal/streams/destroy":59,"./internal/streams/stream":60,"_process":51,"core-util-is":14,"inherits":37,"process-nextick-args":61,"safe-buffer":67,"util-deprecate":77}],58:[function(_dereq_,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = _dereq_('safe-buffer').Buffer; var util = _dereq_('util'); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } },{"safe-buffer":67,"util":6}],59:[function(_dereq_,module,exports){ 'use strict'; /*<replacement>*/ var pna = _dereq_('process-nextick-args'); /*</replacement>*/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { pna.nextTick(emitErrorNT, this, err); } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { pna.nextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":61}],60:[function(_dereq_,module,exports){ 'use strict'; module.exports = _dereq_('events').EventEmitter; },{"events":24}],61:[function(_dereq_,module,exports){ (function (process){ 'use strict'; if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process; } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this,_dereq_('_process')) },{"_process":51}],62:[function(_dereq_,module,exports){ 'use strict'; var Buffer = _dereq_('safe-buffer').Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return -1; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\uFFFD'.repeat(p); } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\uFFFD'.repeat(p + 1); } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\uFFFD'.repeat(p + 2); } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character for each buffered byte of a (partial) // character needs to be added to the output. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\uFFFD'.repeat(this.lastTotal - this.lastNeed); return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":67}],63:[function(_dereq_,module,exports){ 'use strict'; exports = module.exports = _dereq_('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = _dereq_('./lib/_stream_writable.js'); exports.Duplex = _dereq_('./lib/_stream_duplex.js'); exports.Transform = _dereq_('./lib/_stream_transform.js'); exports.PassThrough = _dereq_('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57}],64:[function(_dereq_,module,exports){ 'use strict'; var readystate = module.exports = _dereq_('./readystate'), win = new Function('return this')(), complete = 'complete', root = true, doc = win.document, html = doc.documentElement; (function wrapper() { // // Bail out early if the document is already fully loaded. This means that this // script is loaded after the onload event. // if (complete === doc.readyState) { return readystate.change(complete); } // // Use feature detection to see what kind of browser environment we're dealing // with. Old versions of Internet Explorer do not support the addEventListener // interface so we can also safely assume that we need to fall back to polling. // var modern = !!doc.addEventListener, prefix = modern ? '' : 'on', on = modern ? 'addEventListener' : 'attachEvent', off = modern ? 'removeEventListener' : 'detachEvent'; if (!modern && 'function' === typeof html.doScroll) { try { root = !win.frameElement; } catch (e) {} if (root) (function polling() { try { html.doScroll('left'); } catch (e) { return setTimeout(polling, 50); } readystate.change('interactive'); })(); } /** * Handle the various of event listener calls. * * @param {Event} evt Simple DOM event. * @api private */ function change(evt) { evt = evt || win.event; if ('readystatechange' === evt.type) { readystate.change(doc.readyState); if (complete !== doc.readyState) return; } if ('load' === evt.type) readystate.change('complete');else readystate.change('interactive'); // // House keeping, remove our assigned event listeners. // (evt.type === 'load' ? win : doc)[off](evt.type, change, false); } // // Assign a shit load of event listeners so we can update our internal state. // doc[on](prefix + 'DOMContentLoaded', change, false); doc[on](prefix + 'readystatechange', change, false); win[on](prefix + 'load', change, false); })(); },{"./readystate":65}],65:[function(_dereq_,module,exports){ 'use strict'; /** * Generate a new prototype method which will the given function once the * desired state has been reached. The returned function accepts 2 arguments: * * - fn: The assigned function which needs to be called. * - context: Context/this value of the function we need to execute. * * @param {String} state The state we need to operate upon. * @returns {Function} * @api private */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function generate(state) { return function proxy(fn, context) { var rs = this; if (rs.is(state)) { setTimeout(function () { fn.call(context, rs.readyState); }, 0); } else { if (!rs._events[state]) rs._events[state] = []; rs._events[state].push({ fn: fn, context: context }); } return rs; }; } /** * RS (readyState) instance. * * @constructor * @api public */ function RS() { this.readyState = RS.UNKNOWN; this._events = {}; } /** * The environment can be in different states. The following states are * generated: * * - ALL: The I don't really give a fuck state. * - UNKNOWN: We got an unknown readyState we should start listening for events. * - LOADING: Environment is currently loading. * - INTERACTIVE: Environment is ready for modification. * - COMPLETE: All resources have been loaded. * * Please note that the order of the `states` string/array is of vital * importance as it's used in the readyState check. * * @type {Number} * @private */ RS.states = 'ALL,UNKNOWN,LOADING,INTERACTIVE,COMPLETE'.split(','); for (var s = 0, state; s < RS.states.length; s++) { state = RS.states[s]; RS[state] = RS.prototype[state] = s; RS.prototype[state.toLowerCase()] = generate(state); } /** * A change in the environment has been detected so we need to change our * readyState and call assigned event listeners and those of the previous * states. * * @param {Number} state The new readyState that we detected. * @returns {RS} * @api private */ RS.prototype.change = function change(state) { state = this.clean(state, true); var j, name, i = 0, listener, rs = this, previously = rs.readyState; if (previously >= state) return rs; rs.readyState = state; for (; i < RS.states.length; i++) { if (i > state) break; name = RS.states[i]; if (name in rs._events) { for (j = 0; j < rs._events[name].length; j++) { listener = rs._events[name][j]; listener.fn.call(listener.context || rs, previously); } delete rs._events[name]; } } return rs; }; /** * Check if we're currently in a given readyState. * * @param {String|Number} state The required readyState. * @returns {Boolean} Indication if this state has been reached. * @api public */ RS.prototype.is = function is(state) { return this.readyState >= this.clean(state, true); }; /** * Transform a state to a number or toUpperCase. * * @param {Mixed} state State to transform. * @param {Boolean} nr Change to number. * @returns {Mixed} * @api public */ RS.prototype.clean = function transform(state, nr) { var type = typeof state === 'undefined' ? 'undefined' : _typeof(state); if (nr) return 'number' !== type ? +RS[state.toUpperCase()] || 0 : state; return ('number' === type ? RS.states[state] : state).toUpperCase(); }; /** * Removes all event listeners. Useful when you want to unload readystatechange * completely so that it won't react to any events anymore. See * https://github.com/unshiftio/readystate/issues/8 * * @returns {Function} rs so that calls can be chained. * @api public */ RS.prototype.removeAllListeners = function removeAllListeners() { this._events = {}; return this; }; // // Expose the module. // module.exports = new RS(); },{}],66:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * request-frame - requestAnimationFrame & cancelAnimationFrame polyfill for optimal cross-browser development. * @version v1.5.3 * @license MIT * Copyright Julien Etienne 2015 All Rights Reserved. */ (function (global, factory) { (typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.requestFrame = factory(); })(undefined, function () { 'use strict'; /** * @param {String} type - request | cancel | native. * @return {Function} Timing function. */ function requestFrame(type) { // The only vendor prefixes required. var vendors = ['moz', 'webkit']; // Disassembled timing function abbreviations. var aF = 'AnimationFrame'; var rqAF = 'Request' + aF; // Checks for firefox 4 - 10 function pair mismatch. var mozRAF = window.mozRequestAnimationFrame; var mozCAF = window.mozCancelAnimationFrame; var hasMozMismatch = mozRAF && !mozCAF; // Final assigned functions. var assignedRequestAnimationFrame; var assignedCancelAnimationFrame; // Initial time of the timing lapse. var previousTime = 0; var requestFrameMain; // Date.now polyfill, mainly for legacy IE versions. if (!Date.now) { Date.now = function () { return new Date().getTime(); }; } /** * hasIOS6RequestAnimationFrameBug. * @See {@Link https://gist.github.com/julienetie/86ac394ec41f1271ff0a} * - for Commentary. * @Copyright 2015 - Julien Etienne. * @License: MIT. */ function hasIOS6RequestAnimationFrameBug() { var webkitRAF = window.webkitRequestAnimationFrame; var rAF = window.requestAnimationFrame; // CSS/ Device with max for iOS6 Devices. var hasMobileDeviceWidth = screen.width <= 768 ? true : false; // Only supports webkit prefixed requestAnimtionFrane. var requiresWebkitprefix = !(webkitRAF && rAF); // iOS6 webkit browsers don't support performance now. var hasNoNavigationTiming = window.performance ? false : true; var iOS6Notice = 'setTimeout is being used as a substitiue for \n requestAnimationFrame due to a bug within iOS 6 builds'; var hasIOS6Bug = requiresWebkitprefix && hasMobileDeviceWidth && hasNoNavigationTiming; var bugCheckresults = function bugCheckresults(timingFnA, timingFnB, notice) { if (timingFnA || timingFnB) { console.warn(notice); return true; } else { return false; } }; var displayResults = function displayResults(hasBug, hasBugNotice, webkitFn, nativeFn) { if (hasBug) { return bugCheckresults(webkitFn, nativeFn, hasBugNotice); } else { return false; } }; return displayResults(hasIOS6Bug, iOS6Notice, webkitRAF, rAF); } /** * Native clearTimeout function. * @return {Function} */ function clearTimeoutWithId(id) { clearTimeout(id); } /** * Based on a polyfill by Erik, introduced by Paul Irish & * further improved by Darius Bacon. * @see {@link http://www.paulirish.com/2011/ * requestanimationframe-for-smart-animating} * @see {@link https://github.com/darius/requestAnimationFrame/blob/ * master/requestAnimationFrame.js} * @callback {Number} Timestamp. * @return {Function} setTimeout Function. */ function setTimeoutWithTimestamp(callback) { var immediateTime = Date.now(); var lapsedTime = Math.max(previousTime + 16, immediateTime); return setTimeout(function () { callback(previousTime = lapsedTime); }, lapsedTime - immediateTime); } /** * Queries the native function, prefixed function * or use the setTimeoutWithTimestamp function. * @return {Function} */ function queryRequestAnimationFrame() { if (Array.prototype.filter) { assignedRequestAnimationFrame = window['request' + aF] || window[vendors.filter(function (vendor) { if (window[vendor + rqAF] !== undefined) return vendor; }) + rqAF] || setTimeoutWithTimestamp; } else { return setTimeoutWithTimestamp; } if (!hasIOS6RequestAnimationFrameBug()) { return assignedRequestAnimationFrame; } else { return setTimeoutWithTimestamp; } } /** * Queries the native function, prefixed function * or use the clearTimeoutWithId function. * @return {Function} */ function queryCancelAnimationFrame() { var cancellationNames = []; if (Array.prototype.map) { vendors.map(function (vendor) { return ['Cancel', 'CancelRequest'].map(function (cancellationNamePrefix) { cancellationNames.push(vendor + cancellationNamePrefix + aF); }); }); } else { return clearTimeoutWithId; } /** * Checks for the prefixed cancelAnimationFrame implementation. * @param {Array} prefixedNames - An array of the prefixed names. * @param {Number} i - Iteration start point. * @return {Function} prefixed cancelAnimationFrame function. */ function prefixedCancelAnimationFrame(prefixedNames, i) { var cancellationFunction = void 0; for (; i < prefixedNames.length; i++) { if (window[prefixedNames[i]]) { cancellationFunction = window[prefixedNames[i]]; break; } } return cancellationFunction; } // Use truthly function assignedCancelAnimationFrame = window['cancel' + aF] || prefixedCancelAnimationFrame(cancellationNames, 0) || clearTimeoutWithId; // Check for iOS 6 bug if (!hasIOS6RequestAnimationFrameBug()) { return assignedCancelAnimationFrame; } else { return clearTimeoutWithId; } } function getRequestFn() { if (hasMozMismatch) { return setTimeoutWithTimestamp; } else { return queryRequestAnimationFrame(); } } function getCancelFn() { return queryCancelAnimationFrame(); } function setNativeFn() { if (hasMozMismatch) { window.requestAnimationFrame = setTimeoutWithTimestamp; window.cancelAnimationFrame = clearTimeoutWithId; } else { window.requestAnimationFrame = queryRequestAnimationFrame(); window.cancelAnimationFrame = queryCancelAnimationFrame(); } } /** * The type value "request" singles out firefox 4 - 10 and * assigns the setTimeout function if plausible. */ switch (type) { case 'request': case '': requestFrameMain = getRequestFn(); break; case 'cancel': requestFrameMain = getCancelFn(); break; case 'native': setNativeFn(); break; default: throw new Error('RequestFrame parameter is not a type.'); } return requestFrameMain; } return requestFrame; }); },{}],67:[function(_dereq_,module,exports){ 'use strict'; /* eslint-disable node/no-deprecated-api */ var buffer = _dereq_('buffer'); var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer; } else { // Copy properties from require('buffer') copyProps(buffer, exports); exports.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length); } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer); SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number'); } return Buffer(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } var buf = Buffer(size); if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding); } else { buf.fill(fill); } } else { buf.fill(0); } return buf; }; SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return Buffer(size); }; SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return buffer.SlowBuffer(size); }; },{"buffer":8}],68:[function(_dereq_,module,exports){ "use strict"; module.exports = shift; function shift(stream) { var rs = stream._readableState; if (!rs) return null; return rs.objectMode ? stream.read() : stream.read(getStateLength(rs)); } function getStateLength(state) { if (state.buffer.length) { // Since node 6.3.0 state.buffer is a BufferList not an array if (state.buffer.head) { return state.buffer.head.data.length; } return state.buffer[0].length; } return state.length; } },{}],69:[function(_dereq_,module,exports){ "use strict"; function Agent() { this._defaults = []; } ["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects", "timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function (fn) { /** Default setting for all requests from this agent */ Agent.prototype[fn] = function () /*varargs*/{ this._defaults.push({ fn: fn, arguments: arguments }); return this; }; }); Agent.prototype._setDefaults = function (req) { this._defaults.forEach(function (def) { req[def.fn].apply(req, def.arguments); }); }; module.exports = Agent; },{}],70:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { // Browser window root = window; } else if (typeof self !== 'undefined') { // Web Worker root = self; } else { // Other environments console.warn("Using browser-only version of superagent in non-browser environment"); root = undefined; } var Emitter = _dereq_('component-emitter'); var RequestBase = _dereq_('./request-base'); var isObject = _dereq_('./is-object'); var ResponseBase = _dereq_('./response-base'); var Agent = _dereq_('./agent-base'); /** * Noop. */ function noop() {}; /** * Expose `request`. */ var request = exports = module.exports = function (method, url) { // callback if ('function' == typeof url) { return new exports.Request('GET', method).end(url); } // url first if (1 == arguments.length) { return new exports.Request('GET', method); } return new exports.Request(method, url); }; exports.Request = Request; /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || 'file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest(); } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {} } throw Error("Browser-only version of superagent could not find XHR"); }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function (s) { return s.trim(); } : function (s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { pushEncodedKeyValuePair(pairs, key, obj[key]); } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (val != null) { if (Array.isArray(val)) { val.forEach(function (v) { pushEncodedKeyValuePair(pairs, key, v); }); } else if (isObject(val)) { for (var subkey in val) { pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); } } else { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } } else if (val === null) { pairs.push(encodeURIComponent(key)); } } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var pair; var pos; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; pos = pair.indexOf('='); if (pos == -1) { obj[decodeURIComponent(pair)] = ''; } else { obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); } } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'text/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); if (index === -1) { // could be empty line, just skip it continue; } field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { // should match /json or +json // but not /json-seq return (/[\/+]json($|[^-\w])/.test(mime) ); } /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req) { this.req = req; this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers this.text = this.req.method != 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request if (status === 1223) { status = 204; } this._setStatusProperties(status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but // getResponseHeader still works. so we get content-type even if getting // other headers fails. this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this._setHeaderProperties(this.header); if (null === this.text && req._responseType) { this.body = this.xhr.response; } else { this.body = this.req.method != 'HEAD' ? this._parseBody(this.text ? this.text : this.xhr.response) : null; } } ResponseBase(Response.prototype); /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype._parseBody = function (str) { var parse = request.parse[this.type]; if (this.req._parser) { return this.req._parser(this, str); } if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length || str instanceof Object) ? parse(str) : null; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function () { var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; // preserves header name case this._header = {}; // coerces header names to lowercase this.on('end', function () { var err = null; var res = null; try { res = new Response(self); } catch (e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; // issue #675: return the raw response if the response parsing fails if (self.xhr) { // ie9 doesn't have 'response' property err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails err.status = self.xhr.status ? self.xhr.status : null; err.statusCode = err.status; // backwards-compat only } else { err.rawResponse = null; err.status = null; } return self.callback(err); } self.emit('response', res); var new_err; try { if (!self._isResponseOK(res)) { new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); } } catch (custom_err) { new_err = custom_err; // ok() callback can throw } // #1000 don't catch errors from the callback to avoid double calling it if (new_err) { new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); } else { self.callback(null, res); } }); } /** * Mixin `Emitter` and `RequestBase`. */ Emitter(Request.prototype); RequestBase(Request.prototype); /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function (type) { this.set('Content-Type', request.types[type] || type); return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function (type) { this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} [pass] optional in case of using 'bearer' as type * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function (user, pass, options) { if (1 === arguments.length) pass = ''; if ((typeof pass === 'undefined' ? 'undefined' : _typeof(pass)) === 'object' && pass !== null) { // pass is optional and can be replaced with options options = pass; pass = ''; } if (!options) { options = { type: 'function' === typeof btoa ? 'basic' : 'auto' }; } var encoder = function encoder(string) { if ('function' === typeof btoa) { return btoa(string); } throw new Error('Cannot use basic auth, btoa is not a function'); }; return this._auth(user, pass, options, encoder); }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function (val) { if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `options` (or filename). * * ``` js * request.post('/upload') * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String|Object} options * @return {Request} for chaining * @api public */ Request.prototype.attach = function (field, file, options) { if (file) { if (this._data) { throw Error("superagent can't mix .send() and .attach()"); } this._getFormData().append(field, file, options || file.name); } return this; }; Request.prototype._getFormData = function () { if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function (err, res) { if (this._shouldRetry(err, res)) { return this._retry(); } var fn = this._callback; this.clearTimeout(); if (err) { if (this._maxRetries) err.retries = this._retries - 1; this.emit('error', err); } fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function () { var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; // This only warns, because the request is still likely to work Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function () { console.warn("This is not supported in browser version of superagent"); return this; }; // This throws, because it can't send/receive data as expected Request.prototype.pipe = Request.prototype.write = function () { throw Error("Streaming is not supported in browser version of superagent"); }; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * @param {Object} obj * @return {Boolean} * @api private */ Request.prototype._isHost = function _isHost(obj) { // Native objects stringify to [object File], [object Blob], [object FormData], etc. return obj && 'object' === (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function (fn) { if (this._endCalled) { console.warn("Warning: .end() was called twice. This is not supported in superagent"); } this._endCalled = true; // store callback this._callback = fn || noop; // querystring this._finalizeQueryString(); return this._end(); }; Request.prototype._end = function () { var self = this; var xhr = this.xhr = request.getXHR(); var data = this._formData || this._data; this._setTimeouts(); // state change xhr.onreadystatechange = function () { var readyState = xhr.readyState; if (readyState >= 2 && self._responseTimeoutTimer) { clearTimeout(self._responseTimeoutTimer); } if (4 != readyState) { return; } // In IE9, reads to any property (e.g. status) off of an aborted XHR will // result in the error "Could not complete the operation due to error c00c023f" var status; try { status = xhr.status; } catch (e) { status = 0; } if (!status) { if (self.timedout || self._aborted) return; return self.crossDomainError(); } self.emit('end'); }; // progress var handleProgress = function handleProgress(direction, e) { if (e.total > 0) { e.percent = e.loaded / e.total * 100; } e.direction = direction; self.emit('progress', e); }; if (this.hasListeners('progress')) { try { xhr.onprogress = handleProgress.bind(null, 'download'); if (xhr.upload) { xhr.upload.onprogress = handleProgress.bind(null, 'upload'); } } catch (e) { // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. // Reported here: // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context } } // initiate request try { if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } } catch (err) { // see #1149 return this.callback(err); } // CORS if (this._withCredentials) xhr.withCredentials = true; // body if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { // serialize stuff var contentType = this._header['content-type']; var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!serialize && isJSON(contentType)) { serialize = request.serialize['application/json']; } if (serialize) data = serialize(data); } // set header fields for (var field in this.header) { if (null == this.header[field]) continue; if (this.header.hasOwnProperty(field)) xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } // send stuff this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) // We need null here if data is undefined xhr.send(typeof data !== 'undefined' ? data : null); return this; }; request.agent = function () { return new Agent(); }; ["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function (method) { Agent.prototype[method.toLowerCase()] = function (url, fn) { var req = new request.Request(method, url); this._setDefaults(req); if (fn) { req.end(fn); } return req; }; }); Agent.prototype.del = Agent.prototype['delete']; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.get = function (url, data, fn) { var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.head = function (url, data, fn) { var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * OPTIONS query to `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.options = function (url, data, fn) { var req = request('OPTIONS', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ function del(url, data, fn) { var req = request('DELETE', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; } request['del'] = del; request['delete'] = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ request.patch = function (url, data, fn) { var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ request.post = function (url, data, fn) { var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.put = function (url, data, fn) { var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; },{"./agent-base":69,"./is-object":71,"./request-base":72,"./response-base":73,"component-emitter":12}],71:[function(_dereq_,module,exports){ 'use strict'; /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function isObject(obj) { return null !== obj && 'object' === (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)); } module.exports = isObject; },{}],72:[function(_dereq_,module,exports){ 'use strict'; /** * Module of mixed-in functions shared between node and client code */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var isObject = _dereq_('./is-object'); /** * Expose `RequestBase`. */ module.exports = RequestBase; /** * Initialize a new `RequestBase`. * * @api public */ function RequestBase(obj) { if (obj) return mixin(obj); } /** * Mixin the prototype properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in RequestBase.prototype) { obj[key] = RequestBase.prototype[key]; } return obj; } /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ RequestBase.prototype.clearTimeout = function _clearTimeout() { clearTimeout(this._timer); clearTimeout(this._responseTimeoutTimer); delete this._timer; delete this._responseTimeoutTimer; return this; }; /** * Override default response body parser * * This function will be called to convert incoming data into request.body * * @param {Function} * @api public */ RequestBase.prototype.parse = function parse(fn) { this._parser = fn; return this; }; /** * Set format of binary response body. * In browser valid formats are 'blob' and 'arraybuffer', * which return Blob and ArrayBuffer, respectively. * * In Node all values result in Buffer. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ RequestBase.prototype.responseType = function (val) { this._responseType = val; return this; }; /** * Override default request body serializer * * This function will be called to convert data set via .send or .attach into payload to send * * @param {Function} * @api public */ RequestBase.prototype.serialize = function serialize(fn) { this._serializer = fn; return this; }; /** * Set timeouts. * * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. * * Value of 0 or false means no timeout. * * @param {Number|Object} ms or {response, deadline} * @return {Request} for chaining * @api public */ RequestBase.prototype.timeout = function timeout(options) { if (!options || 'object' !== (typeof options === 'undefined' ? 'undefined' : _typeof(options))) { this._timeout = options; this._responseTimeout = 0; return this; } for (var option in options) { switch (option) { case 'deadline': this._timeout = options.deadline; break; case 'response': this._responseTimeout = options.response; break; default: console.warn("Unknown timeout option", option); } } return this; }; /** * Set number of retry attempts on error. * * Failed requests will be retried 'count' times if timeout or err.code >= 500. * * @param {Number} count * @param {Function} [fn] * @return {Request} for chaining * @api public */ RequestBase.prototype.retry = function retry(count, fn) { // Default to 1 if no count passed or true if (arguments.length === 0 || count === true) count = 1; if (count <= 0) count = 0; this._maxRetries = count; this._retries = 0; this._retryCallback = fn; return this; }; var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT']; /** * Determine if a request should be retried. * (Borrowed from segmentio/superagent-retry) * * @param {Error} err * @param {Response} [res] * @returns {Boolean} */ RequestBase.prototype._shouldRetry = function (err, res) { if (!this._maxRetries || this._retries++ >= this._maxRetries) { return false; } if (this._retryCallback) { try { var override = this._retryCallback(err, res); if (override === true) return true; if (override === false) return false; // undefined falls back to defaults } catch (e) { console.error(e); } } if (res && res.status && res.status >= 500 && res.status != 501) return true; if (err) { if (err.code && ~ERROR_CODES.indexOf(err.code)) return true; // Superagent timeout if (err.timeout && err.code == 'ECONNABORTED') return true; if (err.crossDomain) return true; } return false; }; /** * Retry request * * @return {Request} for chaining * @api private */ RequestBase.prototype._retry = function () { this.clearTimeout(); // node if (this.req) { this.req = null; this.req = this.request(); } this._aborted = false; this.timedout = false; return this._end(); }; /** * Promise support * * @param {Function} resolve * @param {Function} [reject] * @return {Request} */ RequestBase.prototype.then = function then(resolve, reject) { if (!this._fullfilledPromise) { var self = this; if (this._endCalled) { console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"); } this._fullfilledPromise = new Promise(function (innerResolve, innerReject) { self.end(function (err, res) { if (err) innerReject(err);else innerResolve(res); }); }); } return this._fullfilledPromise.then(resolve, reject); }; RequestBase.prototype.catch = function (cb) { return this.then(undefined, cb); }; /** * Allow for extension */ RequestBase.prototype.use = function use(fn) { fn(this); return this; }; RequestBase.prototype.ok = function (cb) { if ('function' !== typeof cb) throw Error("Callback required"); this._okCallback = cb; return this; }; RequestBase.prototype._isResponseOK = function (res) { if (!res) { return false; } if (this._okCallback) { return this._okCallback(res); } return res.status >= 200 && res.status < 300; }; /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ RequestBase.prototype.get = function (field) { return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ RequestBase.prototype.getHeader = RequestBase.prototype.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ RequestBase.prototype.set = function (field, val) { if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field */ RequestBase.prototype.unset = function (field) { delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val`, or multiple fields with one object * for "multipart/form-data" request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * * request.post('/upload') * .field({ foo: 'bar', baz: 'qux' }) * .end(callback); * ``` * * @param {String|Object} name * @param {String|Blob|File|Buffer|fs.ReadStream} val * @return {Request} for chaining * @api public */ RequestBase.prototype.field = function (name, val) { // name should be either a string or an object. if (null === name || undefined === name) { throw new Error('.field(name, val) name can not be empty'); } if (this._data) { console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); } if (isObject(name)) { for (var key in name) { this.field(key, name[key]); } return this; } if (Array.isArray(val)) { for (var i in val) { this.field(name, val[i]); } return this; } // val should be defined now if (null === val || undefined === val) { throw new Error('.field(name, val) val can not be empty'); } if ('boolean' === typeof val) { val = '' + val; } this._getFormData().append(name, val); return this; }; /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ RequestBase.prototype.abort = function () { if (this._aborted) { return this; } this._aborted = true; this.xhr && this.xhr.abort(); // browser this.req && this.req.abort(); // node this.clearTimeout(); this.emit('abort'); return this; }; RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { switch (options.type) { case 'basic': this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass)); break; case 'auto': this.username = user; this.password = pass; break; case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) this.set('Authorization', 'Bearer ' + user); break; } return this; }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ RequestBase.prototype.withCredentials = function (on) { // This is browser-only functionality. Node side is no-op. if (on == undefined) on = true; this._withCredentials = on; return this; }; /** * Set the max redirects to `n`. Does noting in browser XHR implementation. * * @param {Number} n * @return {Request} for chaining * @api public */ RequestBase.prototype.redirects = function (n) { this._maxRedirects = n; return this; }; /** * Maximum size of buffered response body, in bytes. Counts uncompressed size. * Default 200MB. * * @param {Number} n * @return {Request} for chaining */ RequestBase.prototype.maxResponseSize = function (n) { if ('number' !== typeof n) { throw TypeError("Invalid argument"); } this._maxResponseSize = n; return this; }; /** * Convert to a plain javascript object (not JSON string) of scalar properties. * Note as this method is designed to return a useful non-this value, * it cannot be chained. * * @return {Object} describing method, url, and data of this request * @api public */ RequestBase.prototype.toJSON = function () { return { method: this.method, url: this.url, data: this._data, headers: this._header }; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * // manual json * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * // auto json * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * // manual x-www-form-urlencoded * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * // auto x-www-form-urlencoded * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * // defaults to x-www-form-urlencoded * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ RequestBase.prototype.send = function (data) { var isObj = isObject(data); var type = this._header['content-type']; if (this._formData) { console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); } if (isObj && !this._data) { if (Array.isArray(data)) { this._data = []; } else if (!this._isHost(data)) { this._data = {}; } } else if (data && this._data && this._isHost(this._data)) { throw Error("Can't merge these send calls"); } // merge if (isObj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { // default to x-www-form-urlencoded if (!type) this.type('form'); type = this._header['content-type']; if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!isObj || this._isHost(data)) { return this; } // default to json if (!type) this.type('json'); return this; }; /** * Sort `querystring` by the sort function * * * Examples: * * // default order * request.get('/user') * .query('name=Nick') * .query('search=Manny') * .sortQuery() * .end(callback) * * // customized sort function * request.get('/user') * .query('name=Nick') * .query('search=Manny') * .sortQuery(function(a, b){ * return a.length - b.length; * }) * .end(callback) * * * @param {Function} sort * @return {Request} for chaining * @api public */ RequestBase.prototype.sortQuery = function (sort) { // _sort default to true but otherwise can be a function or boolean this._sort = typeof sort === 'undefined' ? true : sort; return this; }; /** * Compose querystring to append to req.url * * @api private */ RequestBase.prototype._finalizeQueryString = function () { var query = this._query.join('&'); if (query) { this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query; } this._query.length = 0; // Makes the call idempotent if (this._sort) { var index = this.url.indexOf('?'); if (index >= 0) { var queryArr = this.url.substring(index + 1).split('&'); if ('function' === typeof this._sort) { queryArr.sort(this._sort); } else { queryArr.sort(); } this.url = this.url.substring(0, index) + '?' + queryArr.join('&'); } } }; // For backwards compat only RequestBase.prototype._appendQueryString = function () { console.trace("Unsupported"); }; /** * Invoke callback with timeout error. * * @api private */ RequestBase.prototype._timeoutError = function (reason, timeout, errno) { if (this._aborted) { return; } var err = new Error(reason + timeout + 'ms exceeded'); err.timeout = timeout; err.code = 'ECONNABORTED'; err.errno = errno; this.timedout = true; this.abort(); this.callback(err); }; RequestBase.prototype._setTimeouts = function () { var self = this; // deadline if (this._timeout && !this._timer) { this._timer = setTimeout(function () { self._timeoutError('Timeout of ', self._timeout, 'ETIME'); }, this._timeout); } // response timeout if (this._responseTimeout && !this._responseTimeoutTimer) { this._responseTimeoutTimer = setTimeout(function () { self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); }, this._responseTimeout); } }; },{"./is-object":71}],73:[function(_dereq_,module,exports){ 'use strict'; /** * Module dependencies. */ var utils = _dereq_('./utils'); /** * Expose `ResponseBase`. */ module.exports = ResponseBase; /** * Initialize a new `ResponseBase`. * * @api public */ function ResponseBase(obj) { if (obj) return mixin(obj); } /** * Mixin the prototype properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in ResponseBase.prototype) { obj[key] = ResponseBase.prototype[key]; } return obj; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ ResponseBase.prototype.get = function (field) { return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ ResponseBase.prototype._setHeaderProperties = function (header) { // TODO: moar! // TODO: make this a util // content-type var ct = header['content-type'] || ''; this.type = utils.type(ct); // params var params = utils.params(ct); for (var key in params) { this[key] = params[key]; }this.links = {}; // links try { if (header.link) { this.links = utils.parseLinks(header.link); } } catch (err) { // ignore } }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ ResponseBase.prototype._setStatusProperties = function (status) { var type = status / 100 | 0; // status / class this.status = this.statusCode = status; this.statusType = type; // basics this.info = 1 == type; this.ok = 2 == type; this.redirect = 3 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = 4 == type || 5 == type ? this.toError() : false; // sugar this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.forbidden = 403 == status; this.notFound = 404 == status; }; },{"./utils":74}],74:[function(_dereq_,module,exports){ 'use strict'; /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ exports.type = function (str) { return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ exports.params = function (str) { return str.split(/ *; */).reduce(function (obj, str) { var parts = str.split(/ *= */); var key = parts.shift(); var val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Parse Link header fields. * * @param {String} str * @return {Object} * @api private */ exports.parseLinks = function (str) { return str.split(/ *, */).reduce(function (obj, str) { var parts = str.split(/ *; */); var url = parts[0].slice(1, -1); var rel = parts[1].split(/ *= */)[1].slice(1, -1); obj[rel] = url; return obj; }, {}); }; /** * Strip content related fields from `header`. * * @param {Object} header * @return {Object} header * @api private */ exports.cleanHeader = function (header, changesOrigin) { delete header['content-type']; delete header['content-length']; delete header['transfer-encoding']; delete header['host']; // secuirty if (changesOrigin) { delete header['authorization']; delete header['cookie']; } return header; }; },{}],75:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; /** * Convert a typed array to a Buffer without a copy * * Author: Feross Aboukhadijeh <https://feross.org> * License: MIT * * `npm install typedarray-to-buffer` */ var isTypedArray = _dereq_('is-typedarray').strict; module.exports = function typedarrayToBuffer(arr) { if (isTypedArray(arr)) { // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer var buf = Buffer.from(arr.buffer); if (arr.byteLength !== arr.buffer.byteLength) { // Respect the "view", i.e. byteOffset and byteLength, without doing a copy buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength); } return buf; } else { // Pass through all other types to `Buffer.from` return Buffer.from(arr); } }; }).call(this,_dereq_("buffer").Buffer) },{"buffer":8,"is-typedarray":44}],76:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * UAParser.js v0.7.17 * Lightweight JavaScript-based User-Agent string parser * https://github.com/faisalman/ua-parser-js * * Copyright © 2012-2016 Faisal Salman <[email protected]> * Dual licensed under GPLv2 & MIT */ (function (window, undefined) { 'use strict'; ////////////// // Constants ///////////// var LIBVERSION = '0.7.17', EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', STR_TYPE = 'string', MAJOR = 'major', // deprecated MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE = 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet', SMARTTV = 'smarttv', WEARABLE = 'wearable', EMBEDDED = 'embedded'; /////////// // Helper ////////// var util = { extend: function extend(regexes, extensions) { var margedRegexes = {}; for (var i in regexes) { if (extensions[i] && extensions[i].length % 2 === 0) { margedRegexes[i] = extensions[i].concat(regexes[i]); } else { margedRegexes[i] = regexes[i]; } } return margedRegexes; }, has: function has(str1, str2) { if (typeof str1 === "string") { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; } else { return false; } }, lowerize: function lowerize(str) { return str.toLowerCase(); }, major: function major(version) { return (typeof version === 'undefined' ? 'undefined' : _typeof(version)) === STR_TYPE ? version.replace(/[^\d\.]/g, '').split(".")[0] : undefined; }, trim: function trim(str) { return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } }; /////////////// // Map helper ////////////// var mapper = { rgx: function rgx(ua, arrays) { //var result = {}, var i = 0, j, k, p, q, matches, match; //, args = arguments; /*// construct object barebones for (p = 0; p < args[1].length; p++) { q = args[1][p]; result[typeof q === OBJ_TYPE ? q[0] : q] = undefined; }*/ // loop through all regexes maps while (i < arrays.length && !matches) { var regex = arrays[i], // even sequence (0,2,4,..) props = arrays[i + 1]; // odd sequence (1,3,5,..) j = k = 0; // try matching uastring with regexes while (j < regex.length && !matches) { matches = regex[j++].exec(ua); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if ((typeof q === 'undefined' ? 'undefined' : _typeof(q)) === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (_typeof(q[1]) == FUNC_TYPE) { // assign modified match this[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match this[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (_typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex this[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { this[q] = match ? match : undefined; } } } } i += 2; } // console.log(this); //return this; }, str: function str(_str, map) { for (var i in map) { // check if array if (_typeof(map[i]) === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], _str)) { return i === UNKNOWN ? undefined : i; } } } else if (util.has(map[i], _str)) { return i === UNKNOWN ? undefined : i; } } return _str; } }; /////////////// // String map ////////////// var maps = { browser: { oldsafari: { version: { '1.0': '/8', '1.2': '/1', '1.3': '/3', '2.0': '/412', '2.0.2': '/416', '2.0.3': '/417', '2.0.4': '/419', '?': '/' } } }, device: { amazon: { model: { 'Fire Phone': ['SD', 'KF'] } }, sprint: { model: { 'Evo Shift 4G': '7373KT' }, vendor: { 'HTC': 'APA', 'Sprint': 'Sprint' } } }, os: { windows: { version: { 'ME': '4.90', 'NT 3.11': 'NT3.51', 'NT 4.0': 'NT4.0', '2000': 'NT 5.0', 'XP': ['NT 5.1', 'NT 5.2'], 'Vista': 'NT 6.0', '7': 'NT 6.1', '8': 'NT 6.2', '8.1': 'NT 6.3', '10': ['NT 6.4', 'NT 10.0'], 'RT': 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser: [[ // Presto based /(opera\smini)\/([\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/([\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION], [/(opios)[\/\s]+([\w\.]+)/i // Opera mini on iphone >= 8.0 ], [[NAME, 'Opera Mini'], VERSION], [/\s(opr)\/([\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION], [ // Mixed /(kindle)\/([\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)\/([\w\.]+)*/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser ], [NAME, VERSION], [/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION], [/(edge)\/((\d+)?[\w\.]+)/i // Microsoft Edge ], [NAME, VERSION], [/(yabrowser)\/([\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION], [/(puffin)\/([\w\.]+)/i // Puffin ], [[NAME, 'Puffin'], VERSION], [/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i // UCBrowser ], [[NAME, 'UCBrowser'], VERSION], [/(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION], [/(micromessenger)\/([\w\.]+)/i // WeChat ], [[NAME, 'WeChat'], VERSION], [/(QQ)\/([\d\.]+)/i // QQ, aka ShouQ ], [NAME, VERSION], [/m?(qqbrowser)[\/\s]?([\w\.]+)/i // QQBrowser ], [NAME, VERSION], [/xiaomi\/miuibrowser\/([\w\.]+)/i // MIUI Browser ], [VERSION, [NAME, 'MIUI Browser']], [/;fbav\/([\w\.]+);/i // Facebook App for iOS & Android ], [VERSION, [NAME, 'Facebook']], [/headlesschrome(?:\/([\w\.]+)|\s)/i // Chrome Headless ], [VERSION, [NAME, 'Chrome Headless']], [/\swv\).+(chrome)\/([\w\.]+)/i // Chrome WebView ], [[NAME, /(.+)/, '$1 WebView'], VERSION], [/((?:oculus|samsung)browser)\/([\w\.]+)/i], [[NAME, /(.+(?:g|us))(.+)/, '$1 $2'], VERSION], [// Oculus / Samsung Browser /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i // Android Browser ], [VERSION, [NAME, 'Android Browser']], [/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION], [/(dolfin)\/([\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION], [/((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION], [/(coast)\/([\w\.]+)/i // Opera Coast ], [[NAME, 'Opera Coast'], VERSION], [/fxios\/([\w\.-]+)/i // Firefox for iOS ], [VERSION, [NAME, 'Firefox']], [/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, [NAME, 'Mobile Safari']], [/version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, NAME], [/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Google Search Appliance on iOS ], [[NAME, 'GSA'], VERSION], [/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0 ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [/(konqueror)\/([\w\.]+)/i, // Konqueror /(webkit|khtml)\/([\w\.]+)/i], [NAME, VERSION], [ // Gecko based /(navigator|netscape)\/([\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION], [/(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i, // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir /(links)\s\(([\w\.]+)/i, // Links /(gobrowser)\/?([\w\.]+)*/i, // GoBrowser /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]([\w\.]+)/i // Mosaic ], [NAME, VERSION] /* ///////////////////// // Media players BEGIN //////////////////////// , [ /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i, // Generic Apple CoreMedia /(coremedia) v((\d+)[\w\._]+)/i ], [NAME, VERSION], [ /(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i // Aqualung/Lyssna/BSPlayer ], [NAME, VERSION], [ /(ares|ossproxy)\s((\d+)[\w\.-]+)/i // Ares/OSSProxy ], [NAME, VERSION], [ /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i, // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC // NSPlayer/PSP-InternetRadioPlayer/Videos /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i, // Clementine/MPD /(lg player|nexplayer)\s((\d+)[\d\.]+)/i, /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i // NexPlayer/LG Player ], [NAME, VERSION], [ /(nexplayer)\s((\d+)[\w\.-]+)/i // Nexplayer ], [NAME, VERSION], [ /(flrp)\/((\d+)[\w\.-]+)/i // Flip Player ], [[NAME, 'Flip Player'], VERSION], [ /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit ], [NAME], [ /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i // Gstreamer ], [NAME, VERSION], [ /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i, // HTC Streaming Player /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i, // Java/urllib/requests/wget/cURL /(lavf)((\d+)[\d\.]+)/i // Lavf (FFMPEG) ], [NAME, VERSION], [ /(htc_one_s)\/((\d+)[\d\.]+)/i // HTC One S ], [[NAME, /_/g, ' '], VERSION], [ /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i // MPlayer SVN ], [NAME, VERSION], [ /(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i // MPlayer ], [NAME, VERSION], [ /(mplayer)/i, // MPlayer (no other info) /(yourmuze)/i, // YourMuze /(media player classic|nero showtime)/i // Media Player Classic/Nero ShowTime ], [NAME], [ /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i // Nero Home/Nero Scout ], [NAME, VERSION], [ /(nokia\d+)\/((\d+)[\w\.-]+)/i // Nokia ], [NAME, VERSION], [ /\s(songbird)\/((\d+)[\w\.-]+)/i // Songbird/Philips-Songbird ], [NAME, VERSION], [ /(winamp)3 version ((\d+)[\w\.-]+)/i, // Winamp /(winamp)\s((\d+)[\w\.-]+)/i, /(winamp)mpeg\/((\d+)[\w\.-]+)/i ], [NAME, VERSION], [ /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info) // inlight radio ], [NAME], [ /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i // QuickTime/RealMedia/RadioApp/RadioClientApplication/ // SoundTap/Totem/Stagefright/Streamium ], [NAME, VERSION], [ /(smp)((\d+)[\d\.]+)/i // SMP ], [NAME, VERSION], [ /(vlc) media player - version ((\d+)[\w\.]+)/i, // VLC Videolan /(vlc)\/((\d+)[\w\.-]+)/i, /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i, // XBMC/gvfs/Xine/XMMS/irapp /(foobar2000)\/((\d+)[\d\.]+)/i, // Foobar2000 /(itunes)\/((\d+)[\d\.]+)/i // iTunes ], [NAME, VERSION], [ /(wmplayer)\/((\d+)[\w\.-]+)/i, // Windows Media Player /(windows-media-player)\/((\d+)[\w\.-]+)/i ], [[NAME, /-/g, ' '], VERSION], [ /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i // Windows Media Server ], [VERSION, [NAME, 'Windows']], [ /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i // RiseUP Radio Alarm ], [NAME, VERSION], [ /(rad.io)\s((\d+)[\d\.]+)/i, // Rad.io /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i ], [[NAME, 'rad.io'], VERSION] ////////////////////// // Media players END ////////////////////*/ ], cpu: [[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64 ], [[ARCHITECTURE, 'amd64']], [/(ia32(?=;))/i // IA32 (quicktime) ], [[ARCHITECTURE, util.lowerize]], [/((?:i[346]|x)86)[;\)]/i // IA32 ], [[ARCHITECTURE, 'ia32']], [ // PocketPC mistakenly identified as PowerPC /windows\s(ce|mobile);\sppc;/i], [[ARCHITECTURE, 'arm']], [/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [/(sun4\w)[;\)]/i // SPARC ], [[ARCHITECTURE, 'sparc']], [/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC ], [[ARCHITECTURE, util.lowerize]]], device: [[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i // iPad/PlayBook ], [MODEL, VENDOR, [TYPE, TABLET]], [/applecoremedia\/[\w\.]+ \((ipad)/ // iPad ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [/(apple\s{0,1}tv)/i // Apple TV ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [/(archos)\s(gamepad2?)/i, // Archos /(hp).+(touchpad)/i, // HP TouchPad /(hp).+(tablet)/i, // HP Tablet /(kindle)\/([\w\.]+)/i, // Kindle /\s(nook)[\w\s]+build\/(\w+)/i, // Nook /(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak ], [VENDOR, MODEL, [TYPE, TABLET]], [/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i // Kindle Fire HD ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i // Fire Phone ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [/\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone ], [MODEL, VENDOR, [TYPE, MOBILE]], [/\((ip[honed|\s\w*]+);/i // iPod/iPhone ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [/(blackberry)[\s-]?(\w+)/i, // BlackBerry /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i, // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron /(hp)\s([\w\s]+\w)/i, // HP iPAQ /(asus)-?(\w+)/i // Asus ], [VENDOR, MODEL, [TYPE, MOBILE]], [/\(bb10;\s(\w+)/i // BlackBerry 10 ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [ // Asus Tablets /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [/(sony)\s(tablet\s[ps])\sbuild\//i, // Sony /(sony)?(?:sgp.+)\sbuild\//i], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i], [MODEL, [VENDOR, 'Sony'], [TYPE, MOBILE]], [/\s(ouya)\s/i, // Ouya /(nintendo)\s([wids3u]+)/i // Nintendo ], [VENDOR, MODEL, [TYPE, CONSOLE]], [/android.+;\s(shield)\sbuild/i // Nvidia ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [/(playstation\s[34portablevi]+)/i // Playstation ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [/(sprint\s(\w+))/i // Sprint Phones ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i // Lenovo tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i, // HTC /(zte)-(\w+)*/i, // ZTE /(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i // Alcatel/GeeksPhone/Lenovo/Nexian/Panasonic/Sony ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [/(nexus\s9)/i // HTC Nexus 9 ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [/d\/huawei([\w\s-]+)[;\)]/i, /(nexus\s6p)/i // Huawei ], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [/(microsoft);\s(lumia[\s\w]+)/i // Microsoft Lumia ], [VENDOR, MODEL, [TYPE, MOBILE]], [/[\s\(;](xbox(?:\sone)?)[\s\);]/i // Microsoft Xbox ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [/(kin\.[onetw]{3})/i // Microsoft Kin ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [ // Motorola /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i, /mot[\s-]?(\w+)*/i, /(XT\d{3,4}) build\//i, /(nexus\s6)/i], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i // HbbTV devices ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [/hbbtv.+maple;(\d+)/i], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [/\(dtv[\);].+(aquos)/i // Sharp ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i, /((SM-T\w+))/i], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [// Samsung /smart-tv.+(samsung)/i], [VENDOR, [TYPE, SMARTTV], MODEL], [/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i, /(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i, /sec-((sgh\w+))/i], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [/sie-(\w+)*/i // Siemens ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [/(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia /(nokia)[\s_-]?([\w-]+)*/i], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [/android\s3\.[\s\w;-]{10}(a\d{3})/i // Acer ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [/android.+([vl]k\-?\d{3})\s+build/i // LG Tablet ], [MODEL, [VENDOR, 'LG'], [TYPE, TABLET]], [/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i // LG Tablet ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [/(lg) netcast\.tv/i // LG SmartTV ], [VENDOR, MODEL, [TYPE, SMARTTV]], [/(nexus\s[45])/i, // LG /lg[e;\s\/-]+(\w+)*/i, /android.+lg(\-?[\d\w]+)\s+build/i], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [/android.+(ideatab[a-z0-9\-\s]+)/i // Lenovo ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [/linux;.+((jolla));/i // Jolla ], [VENDOR, MODEL, [TYPE, MOBILE]], [/((pebble))app\/[\d\.]+\s/i // Pebble ], [VENDOR, MODEL, [TYPE, WEARABLE]], [/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i // OPPO ], [VENDOR, MODEL, [TYPE, MOBILE]], [/crkey/i // Google Chromecast ], [[MODEL, 'Chromecast'], [VENDOR, 'Google']], [/android.+;\s(glass)\s\d/i // Google Glass ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [/android.+;\s(pixel c)\s/i // Google Pixel C ], [MODEL, [VENDOR, 'Google'], [TYPE, TABLET]], [/android.+;\s(pixel xl|pixel)\s/i // Google Pixel ], [MODEL, [VENDOR, 'Google'], [TYPE, MOBILE]], [/android.+(\w+)\s+build\/hm\1/i, // Xiaomi Hongmi 'numeric' models /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Hongmi /android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Mi /android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i // Redmi Phones ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i // Mi Pad tablets ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, TABLET]], [/android.+;\s(m[1-5]\snote)\sbuild/i // Meizu Tablet ], [MODEL, [VENDOR, 'Meizu'], [TYPE, TABLET]], [/android.+a000(1)\s+build/i // OnePlus ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i // RCA Tablets ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i // Dell Venue Tablets ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i // Verizon Tablet ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i // Barnes & Noble Tablet ], [[VENDOR, 'Barnes & Noble'], MODEL, [TYPE, TABLET]], [/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i // Barnes & Noble Tablet ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i // ZTE K Series Tablet ], [[VENDOR, 'ZTE'], MODEL, [TYPE, TABLET]], [/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i // Swiss GEN Mobile ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [/android.+[;\/]\s*(zur\d{3})\s+build/i // Swiss ZUR Tablet ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i // Zeki Tablets ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i, /android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i // Dragon Touch Tablet ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [/android.+[;\/]\s*(NS-?.+)\s+build/i // Insignia Tablets ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i // NextBook Tablets ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [// Voice Xtreme Phones /android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i // LvTel Phones ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i // Envizen Tablets ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i // Le Pan Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i // MachSpeed Tablets ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i // Trinity Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [/android.+[;\/]\s*TU_(1491)\s+build/i // Rotor Tablets ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [/android.+(KS(.+))\s+build/i // Amazon Kindle Tablets ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i // Gigaset Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [/\s(tablet|tab)[;\/]/i, // Unidentifiable Tablet /\s(mobile)(?:[;\/]|\ssafari)/i // Unidentifiable Mobile ], [[TYPE, util.lowerize], VENDOR, MODEL], [/(android.+)[;\/].+build/i // Generic Android Device ], [MODEL, [VENDOR, 'Generic']] /*////////////////////////// // TODO: move to string map //////////////////////////// /(C6603)/i // Sony Xperia Z C6603 ], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ /(C6903)/i // Sony Xperia Z 1 ], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ /(SM-G900[F|H])/i // Samsung Galaxy S5 ], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-G7102)/i // Samsung Galaxy Grand 2 ], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-G530H)/i // Samsung Galaxy Grand Prime ], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-G313HZ)/i // Samsung Galaxy V ], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-T805)/i // Samsung Galaxy Tab S 10.5 ], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ /(SM-G800F)/i // Samsung Galaxy S5 Mini ], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-T311)/i // Samsung Galaxy Tab 3 8.0 ], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ /(T3C)/i // Advan Vandroid T3C ], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [ /(ADVAN T1J\+)/i // Advan Vandroid T1J+ ], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [ /(ADVAN S4A)/i // Advan Vandroid S4A ], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [ /(V972M)/i // ZTE V972M ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [ /(i-mobile)\s(IQ\s[\d\.]+)/i // i-mobile IQ ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /(IQ6.3)/i // i-mobile IQ IQ 6.3 ], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ /(i-mobile)\s(i-style\s[\d\.]+)/i // i-mobile i-STYLE ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /(i-STYLE2.1)/i // i-mobile i-STYLE 2.1 ], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ /(mobiistar touch LAI 512)/i // mobiistar touch LAI 512 ], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [ ///////////// // END TODO ///////////*/ ], engine: [[/windows.+\sedge\/([\w\.]+)/i // EdgeHTML ], [VERSION, [NAME, 'EdgeHTML']], [/(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [/rv\:([\w\.]+).*(gecko)/i // Gecko ], [VERSION, NAME]], os: [[ // Windows based /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes) ], [NAME, VERSION], [/(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i, // Windows Phone /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [/(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry /(tizen)[\/\s]([\w\.]+)/i, // Tizen /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i, // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki /linux;.+(sailfish);/i // Sailfish OS ], [NAME, VERSION], [/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian ], [[NAME, 'Symbian'], VERSION], [/\((series40);/i // Series 40 ], [NAME], [/mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids34portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w+)*/i, // Mint /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux /(gnu)\s?([\w\.]+)*/i // GNU ], [NAME, VERSION], [/(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION], [ // Solaris /(sunos)\s?([\w\.]+\d)*/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION], [/(haiku)\s(\w+)/i // Haiku ], [NAME, VERSION], [/cfnetwork\/.+darwin/i, /ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i // iOS ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [/(mac\sos\sx)\s?([\w\s\.]+\w)*/i, /(macintosh|mac(?=_powerpc)\s)/i // Mac OS ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [ // Other /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i, // Solaris /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS /(unix)\s?([\w\.]+)*/i // UNIX ], [NAME, VERSION]] }; ///////////////// // Constructor //////////////// /* var Browser = function (name, version) { this[NAME] = name; this[VERSION] = version; }; var CPU = function (arch) { this[ARCHITECTURE] = arch; }; var Device = function (vendor, model, type) { this[VENDOR] = vendor; this[MODEL] = model; this[TYPE] = type; }; var Engine = Browser; var OS = Browser; */ var UAParser = function UAParser(uastring, extensions) { if ((typeof uastring === 'undefined' ? 'undefined' : _typeof(uastring)) === 'object') { extensions = uastring; uastring = undefined; } if (!(this instanceof UAParser)) { return new UAParser(uastring, extensions).getResult(); } var ua = uastring || (window && window.navigator && window.navigator.userAgent ? window.navigator.userAgent : EMPTY); var rgxmap = extensions ? util.extend(regexes, extensions) : regexes; //var browser = new Browser(); //var cpu = new CPU(); //var device = new Device(); //var engine = new Engine(); //var os = new OS(); this.getBrowser = function () { var browser = { name: undefined, version: undefined }; mapper.rgx.call(browser, ua, rgxmap.browser); browser.major = util.major(browser.version); // deprecated return browser; }; this.getCPU = function () { var cpu = { architecture: undefined }; mapper.rgx.call(cpu, ua, rgxmap.cpu); return cpu; }; this.getDevice = function () { var device = { vendor: undefined, model: undefined, type: undefined }; mapper.rgx.call(device, ua, rgxmap.device); return device; }; this.getEngine = function () { var engine = { name: undefined, version: undefined }; mapper.rgx.call(engine, ua, rgxmap.engine); return engine; }; this.getOS = function () { var os = { name: undefined, version: undefined }; mapper.rgx.call(os, ua, rgxmap.os); return os; }; this.getResult = function () { return { ua: this.getUA(), browser: this.getBrowser(), engine: this.getEngine(), os: this.getOS(), device: this.getDevice(), cpu: this.getCPU() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; //browser = new Browser(); //cpu = new CPU(); //device = new Device(); //engine = new Engine(); //os = new OS(); return this; }; return this; }; UAParser.VERSION = LIBVERSION; UAParser.BROWSER = { NAME: NAME, MAJOR: MAJOR, // deprecated VERSION: VERSION }; UAParser.CPU = { ARCHITECTURE: ARCHITECTURE }; UAParser.DEVICE = { MODEL: MODEL, VENDOR: VENDOR, TYPE: TYPE, CONSOLE: CONSOLE, MOBILE: MOBILE, SMARTTV: SMARTTV, TABLET: TABLET, WEARABLE: WEARABLE, EMBEDDED: EMBEDDED }; UAParser.ENGINE = { NAME: NAME, VERSION: VERSION }; UAParser.OS = { NAME: NAME, VERSION: VERSION }; //UAParser.Utils = util; /////////// // Export ////////// // check js environment if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) !== UNDEF_TYPE) { // nodejs env if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) !== UNDEF_TYPE && module.exports) { exports = module.exports = UAParser; } // TODO: test!!!!!!!! /* if (require && require.main === module && process) { // cli var jsonize = function (arr) { var res = []; for (var i in arr) { res.push(new UAParser(arr[i]).getResult()); } process.stdout.write(JSON.stringify(res, null, 2) + '\n'); }; if (process.stdin.isTTY) { // via args jsonize(process.argv.slice(2)); } else { // via pipe var str = ''; process.stdin.on('readable', function() { var read = process.stdin.read(); if (read !== null) { str += read; } }); process.stdin.on('end', function () { jsonize(str.replace(/\n$/, '').split('\n')); }); } } */ exports.UAParser = UAParser; } else { // requirejs env (optional) if ((typeof define === 'undefined' ? 'undefined' : _typeof(define)) === FUNC_TYPE && define.amd) { define(function () { return UAParser; }); } else if (window) { // browser env window.UAParser = UAParser; } } // jQuery/Zepto specific (optional) // Note: // In AMD env the global scope should be kept clean, but jQuery is an exception. // jQuery always exports to global scope, unless jQuery.noConflict(true) is used, // and we should catch that. var $ = window && (window.jQuery || window.Zepto); if ((typeof $ === 'undefined' ? 'undefined' : _typeof($)) !== UNDEF_TYPE) { var parser = new UAParser(); $.ua = parser.getResult(); $.ua.get = function () { return parser.getUA(); }; $.ua.set = function (uastring) { parser.setUA(uastring); var result = parser.getResult(); for (var prop in result) { $.ua[prop] = result[prop]; } }; } })((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' ? window : undefined); },{}],77:[function(_dereq_,module,exports){ (function (global){ 'use strict'; /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate(fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config(name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],78:[function(_dereq_,module,exports){ arguments[4][37][0].apply(exports,arguments) },{"dup":37}],79:[function(_dereq_,module,exports){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function isBuffer(arg) { return arg && (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; },{}],80:[function(_dereq_,module,exports){ (function (process,global){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function (f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function (x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function (fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function () { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function (set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function () { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function () {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold': [1, 22], 'italic': [3, 23], 'underline': [4, 24], 'inverse': [7, 27], 'white': [37, 39], 'grey': [90, 39], 'black': [30, 39], 'blue': [34, 39], 'cyan': [36, 39], 'green': [32, 39], 'magenta': [35, 39], 'red': [31, 39], 'yellow': [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\x1B[' + inspect.colors[style][0] + 'm' + str + '\x1B[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function (val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function (key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function (key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function (line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function (line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function (prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = _dereq_('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function () { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = _dereq_('inherits'); exports._extend = function (origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":79,"_process":51,"inherits":78}],81:[function(_dereq_,module,exports){ 'use strict'; // FUNCTIONS // var isStr = Object.prototype.toString; // IS FLOAT32ARRAY // /** * FUNCTION: isFloat32Array( value ) * Validates if a value is a Float32Array. * * @param {*} value - value to validate * @returns {Boolean} boolean indicating if a value is a Float32Array */ function isFloat32Array(value) { return isStr.call(value) === '[object Float32Array]'; } // end FUNCTION isFloat32Array() // EXPORTS // module.exports = isFloat32Array; },{}],82:[function(_dereq_,module,exports){ (function (process,global){ 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var Transform = _dereq_('readable-stream').Transform; var duplexify = _dereq_('duplexify'); var WS = _dereq_('ws'); var Buffer = _dereq_('safe-buffer').Buffer; module.exports = WebSocketStream; function buildProxy(options, socketWrite, socketEnd) { var proxy = new Transform({ objectMode: options.objectMode }); proxy._write = socketWrite; proxy._flush = socketEnd; return proxy; } function WebSocketStream(target, protocols, options) { var stream, socket; var isBrowser = process.title === 'browser'; var isNative = !!global.WebSocket; var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode; if (protocols && !Array.isArray(protocols) && 'object' === (typeof protocols === 'undefined' ? 'undefined' : _typeof(protocols))) { // accept the "options" Object as the 2nd argument options = protocols; protocols = null; if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) { protocols = options.protocol; } } if (!options) options = {}; if (options.objectMode === undefined) { options.objectMode = !(options.binary === true || options.binary === undefined); } var proxy = buildProxy(options, socketWrite, socketEnd); if (!options.objectMode) { proxy._writev = writev; } // browser only: sets the maximum socket buffer size before throttling var bufferSize = options.browserBufferSize || 1024 * 512; // browser only: how long to wait when throttling var bufferTimeout = options.browserBufferTimeout || 1000; // use existing WebSocket object that was passed in if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object') { socket = target; // otherwise make a new one } else { // special constructor treatment for native websockets in browsers, see // https://github.com/maxogden/websocket-stream/issues/82 if (isNative && isBrowser) { socket = new WS(target, protocols); } else { socket = new WS(target, protocols, options); } socket.binaryType = 'arraybuffer'; } // was already open when passed in if (socket.readyState === socket.OPEN) { stream = proxy; } else { stream = duplexify.obj(); socket.onopen = onopen; } stream.socket = socket; socket.onclose = onclose; socket.onerror = onerror; socket.onmessage = onmessage; proxy.on('close', destroy); var coerceToBuffer = !options.objectMode; function socketWriteNode(chunk, enc, next) { // avoid errors, this never happens unless // destroy() is called if (socket.readyState !== socket.OPEN) { next(); return; } if (coerceToBuffer && typeof chunk === 'string') { chunk = Buffer.from(chunk, 'utf8'); } socket.send(chunk, next); } function socketWriteBrowser(chunk, enc, next) { if (socket.bufferedAmount > bufferSize) { setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next); return; } if (coerceToBuffer && typeof chunk === 'string') { chunk = Buffer.from(chunk, 'utf8'); } try { socket.send(chunk); } catch (err) { return next(err); } next(); } function socketEnd(done) { socket.close(); done(); } function onopen() { stream.setReadable(proxy); stream.setWritable(proxy); stream.emit('connect'); } function onclose() { stream.end(); stream.destroy(); } function onerror(err) { stream.destroy(err); } function onmessage(event) { var data = event.data; if (data instanceof ArrayBuffer) data = Buffer.from(data);else data = Buffer.from(data, 'utf8'); proxy.push(data); } function destroy() { socket.close(); } // this is to be enabled only if objectMode is false function writev(chunks, cb) { var buffers = new Array(chunks.length); for (var i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = Buffer.from(chunks[i], 'utf8'); } else { buffers[i] = chunks[i].chunk; } } this._write(Buffer.concat(buffers), 'binary', cb); } return stream; } }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":51,"duplexify":21,"readable-stream":63,"safe-buffer":67,"ws":83}],83:[function(_dereq_,module,exports){ 'use strict'; var ws = null; if (typeof WebSocket !== 'undefined') { ws = WebSocket; } else if (typeof MozWebSocket !== 'undefined') { ws = MozWebSocket; } else if (typeof window !== 'undefined') { ws = window.WebSocket || window.MozWebSocket; } module.exports = ws; },{}],84:[function(_dereq_,module,exports){ 'use strict'; // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy; function wrappy(fn, cb) { if (fn && cb) return wrappy(fn)(cb); if (typeof fn !== 'function') throw new TypeError('need wrapper function'); Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k]; }); return wrapper; function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb = args[args.length - 1]; if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k]; }); } return ret; } } },{}],85:[function(_dereq_,module,exports){ module.exports={ "name": "videomail-client", "version": "2.3.2", "description": "A wicked npm package to record videos directly in the browser, wohooo!", "author": "Michael Heuberger <[email protected]>", "contributors": [ { "name": "Michael Heuberger", "email": "[email protected]" } ], "homepage": "https://videomail.io", "repository": { "type": "git", "url": "https://github.com/binarykitchen/videomail-client.git" }, "license": "CC0-1.0", "readmeFilename": "README.md", "module": "src/index.js", "main": "dist/videomail-client.js", "scripts": { "test": "gulp test", "start": "NODE_NO_HTTP2=1 gulp examples", "patch": "./env/dev/release.sh --importance=patch", "minor": "./env/dev/release.sh --importance=minor", "major": "./env/dev/release.sh --importance=major" }, "engines": { "node": "^8.3.0", "yarn": "^1.1.0" }, "keywords": [ "webcam", "video", "videomail", "encoder", "getusermedia", "audio", "recorder" ], "dependencies": { "add-eventlistener-with-options": "1.25.0", "animitter": "3.0.0", "audio-sample": "1.0.4", "canvas-to-buffer": "1.0.12", "classlist.js": "1.1.20150312", "contains": "0.1.1", "create-error": "0.3.1", "deepmerge": "2.1.0", "defined": "1.0.0", "despot": "1.1.3", "document-visibility": "1.0.1", "element-closest": "2.0.2", "fast-safe-stringify": "2.0.3", "filesize": "3.6.0", "get-form-data": "2.0.0", "hidden": "1.1.1", "humanize-duration": "3.12.1", "hyperscript": "2.0.2", "insert-css": "2.0.0", "iphone-inline-video": "2.2.2", "is-power-of-two": "1.0.0", "keymirror": "0.1.1", "number-is-integer": "1.0.1", "readystate": "0.3.0", "request-frame": "1.5.3", "superagent": "3.8.2", "ua-parser-js": "0.7.17", "websocket-stream": "5.1.2" }, "devDependencies": { "babel-core": "6.26.0", "babel-polyfill": "6.26.0", "babel-preset-env": "1.6.1", "babelify": "8.0.0", "body-parser": "1.18.2", "browserify": "16.1.1", "connect-send-json": "1.0.0", "del": "3.0.0", "fancy-log": "1.3.2", "glob": "7.1.2", "gulp": "3.9.1", "gulp-autoprefixer": "5.0.0", "gulp-bump": "3.1.0", "gulp-bytediff": "1.0.0", "gulp-concat": "2.6.1", "gulp-connect": "5.5.0", "gulp-cssnano": "2.1.2", "gulp-derequire": "2.1.0", "gulp-if": "2.0.2", "gulp-inject-string": "1.1.1", "gulp-load-plugins": "1.5.0", "gulp-plumber": "1.2.0", "gulp-rename": "1.2.2", "gulp-sourcemaps": "2.6.4", "gulp-standard": "10.1.2", "gulp-stylus": "2.7.0", "gulp-todo": "5.4.0", "gulp-uglify": "3.0.0", "minimist": "1.2.0", "nib": "1.1.2", "router": "1.3.2", "ssl-root-cas": "1.2.5", "standard": "11.0.0", "tap-summary": "4.0.0", "tape": "4.9.0", "tape-catch": "1.0.6", "tape-run": "3.0.4", "vinyl-buffer": "1.0.1", "vinyl-source-stream": "2.0.0", "watchify": "3.11.0" } } },{}],86:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _deepmerge = _dereq_('deepmerge'); var _deepmerge2 = _interopRequireDefault(_deepmerge); var _readystate = _dereq_('readystate'); var _readystate2 = _interopRequireDefault(_readystate); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _options = _dereq_('./options'); var _options2 = _interopRequireDefault(_options); var _constants = _dereq_('./constants'); var _constants2 = _interopRequireDefault(_constants); var _events = _dereq_('./events'); var _events2 = _interopRequireDefault(_events); var _collectLogger = _dereq_('./util/collectLogger'); var _collectLogger2 = _interopRequireDefault(_collectLogger); var _eventEmitter = _dereq_('./util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _container = _dereq_('./wrappers/container'); var _container2 = _interopRequireDefault(_container); var _replay = _dereq_('./wrappers/visuals/replay'); var _replay2 = _interopRequireDefault(_replay); var _optionsWrapper = _dereq_('./wrappers/optionsWrapper'); var _optionsWrapper2 = _interopRequireDefault(_optionsWrapper); var _browser = _dereq_('./util/browser'); var _browser2 = _interopRequireDefault(_browser); var _resource = _dereq_('./resource'); var _resource2 = _interopRequireDefault(_resource); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var collectLogger; var browser; function adjustOptions() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var localOptions = (0, _deepmerge2.default)(_options2.default, options, { arrayMerge: function arrayMerge(destination, source) { return source; } }); collectLogger = collectLogger || new _collectLogger2.default(localOptions); localOptions.logger = collectLogger; localOptions.debug = localOptions.logger.debug; _optionsWrapper2.default.addFunctions(localOptions); return localOptions; } function getBrowser(localOptions) { if (!browser) { browser = new _browser2.default(localOptions); } return browser; } var VideomailClient = function VideomailClient(options) { var localOptions = adjustOptions(options); var container = new _container2.default(localOptions); var debug = localOptions.debug; var replay; _eventEmitter2.default.call(this, localOptions, 'VideomailClient'); // expose all possible events this.events = _events2.default; function build() { var building = false; _readystate2.default.interactive(function (previousState) { debug('Client: interactive(),', 'previousState =', previousState + ',', '!building =', !building + ',', '!isBuilt() =', !container.isBuilt()); // it can happen that it gets called twice, i.E. when an error is thrown // in the middle of the build() fn if (!building && !container.isBuilt()) { building = true; try { container.build(); } catch (exc) { throw exc; } finally { building = false; } } }); } this.show = function () { if (container.isBuilt()) { container.show(); } else { this.once(_events2.default.BUILT, container.show); } }; // automatically adds a <video> element inside the given parentElement and loads // it with the videomail this.replay = function (videomail, parentElement) { function buildReplay() { if (typeof parentElement === 'string') { parentElement = document.getElementById(parentElement); } if (!parentElement) { if (!container.isBuilt()) { // this will try build all over again container.build(); } if (!container.hasElement()) { // if container.setElement() failed too, then complain _readystate2.default.removeAllListeners(); throw new Error('Unable to replay video without a container nor parent element.'); } } else { if (container.isOutsideElementOf(parentElement)) { replay = new _replay2.default(parentElement, localOptions); replay.build(); } } if (!replay) { replay = container.getReplay(); } if (!parentElement) { parentElement = replay.getParentElement(); } if (videomail) { videomail = container.addPlayerDimensions(videomail, parentElement); } if (container.isOutsideElementOf(parentElement)) { // replay element must be outside of the container container.hideForm({ deep: true }); } else { container.loadForm(videomail); } // slight delay needed to avoid HTTP 416 errors (request range unavailable) setTimeout(function () { replay.setVideomail(videomail); container.showReplayOnly(); }, 10e2); // not sure, but probably can be reduced a bit } _readystate2.default.interactive(buildReplay); }; this.startOver = function (params) { if (replay) { replay.hide(); replay.reset(); } container.startOver(params); }; this.unload = function (e) { _readystate2.default.removeAllListeners(); container.unload(e); }; this.hide = function () { container.hide(); }; this.get = function (key, cb) { new _resource2.default(localOptions).get(key, function (err, videomail) { if (err) { cb(err); } else { cb(null, container.addPlayerDimensions(videomail)); } }); }; this.canRecord = function () { return getBrowser(localOptions).canRecord(); }; // return true when a video has been recorded but is not sent yet this.isDirty = function () { return container.isDirty(); }; this.isRecording = function () { return container.isRecording(); }; this.submit = function () { container.submit(); }; this.getLogLines = function () { if (localOptions.logger && localOptions.logger.getLines) { return localOptions.logger.getLines(); } }; build(); }; _util2.default.inherits(VideomailClient, _eventEmitter2.default); Object.keys(_constants2.default.public).forEach(function (name) { VideomailClient[name] = _constants2.default.public[name]; }); // just another convenient thing VideomailClient.events = _events2.default; exports.default = VideomailClient; },{"./constants":87,"./events":88,"./options":89,"./resource":90,"./util/browser":93,"./util/collectLogger":94,"./util/eventEmitter":95,"./wrappers/container":102,"./wrappers/optionsWrapper":105,"./wrappers/visuals/replay":114,"deepmerge":16,"readystate":64,"util":80}],87:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // constants (changing these only break down functionality, so be careful) exports.default = { SITE_NAME_LABEL: 'x-videomail-site-name', VERSION_LABEL: 'videomailClientVersion', public: { ENC_TYPE_APP_JSON: 'application/json', ENC_TYPE_FORM: 'application/x-www-form-urlencoded' } }; },{}],88:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keymirror = _dereq_('keymirror'); var _keymirror2 = _interopRequireDefault(_keymirror); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _keymirror2.default)({ BUILT: null, // all dom elements are ready, are in the DOM FORM_READY: null, // form is ready, available in the DOM LOADING_USER_MEDIA: null, // asking for webcam access USER_MEDIA_READY: null, // user media (= webcam) is ready, loaded CONNECTING: null, // socket is connecting to server CONNECTED: null, // socket is connected to server DISCONNECTED: null, // socket to server is disconnected COUNTDOWN: null, // countdown for recording has started RECORDING: null, // webcam is recording STOPPING: null, // recording is being stopped (= preview) PROGRESS: null, // start sending BEGIN_AUDIO_ENCODING: null, // encoding video BEGIN_VIDEO_ENCODING: null, // encoding video RESETTING: null, // resetting everything to go back to initial state PAUSED: null, // recording is being paused RESUMING: null, // recording is resumed PREVIEW: null, // video preview is set PREVIEW_SHOWN: null, // video preview is shown REPLAY_SHOWN: null, // submitted video is shown INVALID: null, // form is invalid VALIDATING: null, // form is being validated VALID: null, // form is valid SUBMITTING: null, // form is being submitted SUBMITTED: null, // form has been successfully submitted ERROR: null, // an error occured BLOCKING: null, // something serious, most likely an error, is shown and blocks SENDING_FIRST_FRAME: null, // emitted before the first frame is being computed FIRST_FRAME_SENT: null, // emitted once when fist frame has been sent to server HIDE: null, // emitted when hidden NOTIFYING: null, // notifies user about something (not blocking) ENABLING_AUDIO: null, // about to enable audio DISABLING_AUDIO: null, // about to disable audio LOADED_META_DATA: null, // raised when webcam knows its dimensions EVENT_EMITTED: null, // for debugging only, is emitted when an event is emitted lol, GOING_BACK: null, // switch from replaying back to recording STARTING_OVER: null, // starting all over again back to its inital state ASKING_WEBCAM_PERMISSION: null, // when about to ask for webcam permissions VISIBLE: null, // document just became visible INVISIBLE: null // document just became INvisible }); },{"keymirror":46}],89:[function(_dereq_,module,exports){ (function (process){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _package = _dereq_('../package.json'); var PRODUCTION = process.env.NODE_ENV === 'production'; exports.default = { logger: null, // define logging instance. leave null for default, console. logStackSize: 30, // limits the stack size of log outputs to collect verbose: !PRODUCTION, // set true to log more info baseUrl: 'https://videomail.io', // leave as it, permanent url to post videos socketUrl: 'wss://videomail.io', // leave as it, permanent url to send frames siteName: 'videomail-client-demo', // Required for API, use https://videomail.io/whitelist cache: true, // reduces GET queries when loading videos insertCss: true, // inserts predefined CSS, see examples enablePause: true, // enable pause/resume button enableAutoPause: true, // automatically pauses when window becomes inactive enableSpace: true, // hitting space can pause recording disableSubmit: false, // set this to true if you do not want to submit videos, // but just want to record and replay these temporarily enableAutoValidation: true, // automatically validates all form inputs if any exist and // does not /enable disable submit button after recording // when something else seems invalid. enableAutoSubmission: true, // automatically submits the form where the videomail-client // appears upon press of submit button. disable it when // you want a framework to deal with the form submission itself. enctype: 'application/json', // enctype for the form submission. currently implemented are: // 'application/json' and 'application/x-www-form-urlencoded' // default CSS selectors you can alter, see examples selectors: { containerId: 'videomail', replayClass: 'replay', userMediaClass: 'userMedia', visualsClass: 'visuals', buttonClass: null, // can also be used as a default class for all buttons buttonsClass: 'buttons', recordButtonClass: 'record', pauseButtonClass: 'pause', resumeButtonClass: 'resume', previewButtonClass: 'preview', recordAgainButtonClass: 'recordAgain', submitButtonClass: 'submit', subjectInputName: 'subject', // the form input name for subject fromInputName: 'from', // the form input name for the from email toInputName: 'to', // the form input name for the to email bodyInputName: 'body', // the form input name for the message (body) sendCopyInputName: 'sendCopy', // the form checkbox name for sending myself a copy keyInputName: 'videomail_key', parentKeyInputName: 'videomail_parent_key', aliasInputName: 'videomail_alias', formId: null, // automatically detects form if any submitButtonId: null, // semi-automatically detects submit button in the form // but if that does not work, try using the submitButtonSelector: null // submitButtonSelector }, audio: { enabled: false, // set to true for experimential audio recording 'switch': false, // enables a switcher for audio recording (on/off) volume: 0.2, // must be between 0 .. 1 but 0.20 is recommeded to avoid // distorting at the higher volume peaks bufferSize: 1024 // decides how often the audio is being sampled, must be a power of two. // the higher the less traffic, but harder to adjust with rubberband // to match with the video length on server side during encoding }, video: { fps: 15, // depends on your connection limitSeconds: 30, // recording automatically stops after that limit countdown: 3, // set it to 0 or false to disable it // it is recommended to set one dimension only and leave the other one to auto // because each webcam has a different aspect ratio width: 'auto', // or use an integer for exact pixels height: 'auto' // or use an integer for exact pixels }, image: { quality: 0.44, types: ['webp', 'jpeg'] // recommended settings to make most of all browsers }, // alter these text for internationalisation text: { pausedHeader: 'Paused', pausedHint: null, sending: 'Teleporting', encoding: 'Encoding', limitReached: 'Limit reached', buttons: { 'record': 'Record video', 'recordAgain': 'Record again', 'resume': 'Resume', 'pause': 'Pause', 'preview': 'Preview' } }, notifier: { entertain: false, // when true, user is entertained while waiting, see examples entertainClass: 'bg', entertainLimit: 6, entertainInterval: 9000 }, timeouts: { userMedia: 20e3, // in milliseconds, increase if you want user give more time to enable webcam connection: 1e4, // in seconds, increase if api is slow pingInterval: 45e3 // in milliseconds, keeps webstream (connection) alive when pausing }, callbacks: { // a custom callback to tweak form data before posting to server // this is for advanced use only and shouldn't be used if possible adjustFormDataBeforePosting: null }, defaults: { from: null, // define default FROM email address to: null, // define default TO email address subject: null, // define default subject line body: null // define default body content }, // a special flag to indicate that everything to be initialised // serves only for playing existing videomails with the replay function playerOnly: false, // show errors inside the container? displayErrors: true, // true = all form inputs get disabled and disappear when browser can't record adjustFormOnBrowserError: false, // when true, any errors will be sent to the videomail server for analysis // ps: can be a function too returning a boolean reportErrors: false, // just for testing purposes to simulate browser agent handling fakeUaString: null, version: _package.version }; }).call(this,_dereq_('_process')) },{"../package.json":85,"_process":51}],90:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (options) { var cache = {}; function applyDefaultValue(videomail, name) { if (options.defaults[name] && !videomail[name]) { videomail[name] = options.defaults[name]; } return videomail; } function applyDefaultValues(videomail) { if (options.defaults) { videomail = applyDefaultValue(videomail, 'from'); videomail = applyDefaultValue(videomail, 'to'); videomail = applyDefaultValue(videomail, 'subject'); videomail = applyDefaultValue(videomail, 'body'); } return videomail; } function packError(err, res) { if (res && res.body && res.body.error) { // use the server generated text instead of the superagent's default text err = res.body.error; if (!err.message && res.text) { err.message = res.text; } } return err; } function fetch(alias, cb) { _superagent2.default.get('/videomail/' + alias + '/snapshot').set('Accept', 'application/json').set(_constants2.default.SITE_NAME_LABEL, options.siteName).timeout(options.timeouts.connection).end(function (err, res) { err = packError(err, res); if (err) { cb(err); } else { var videomail = res.body ? res.body : null; if (options.cache) { cache[CACHE_KEY] = videomail; } cb(null, videomail); } }); } function write(method, videomail, identifier, cb) { if (!cb) { cb = identifier; identifier = null; } var queryParams = {}; var url = options.baseUrl + '/videomail/'; var request; if (identifier) { url += identifier; } request = (0, _superagent2.default)(method, url); queryParams[_constants2.default.SITE_NAME_LABEL] = options.siteName; request.query(queryParams).send(videomail).timeout(options.timeout).end(function (err, res) { err = packError(err, res); if (err) { cb(err); } else { if (options.cache && videomail[CACHE_KEY]) { cache[videomail[CACHE_KEY]] = res.body.videomail; } cb(null, res.body.videomail, res.body); } }); } this.get = function (alias, cb) { if (options.cache && cache[alias]) { // keep all callbacks async setTimeout(function () { cb(null, cache[alias]); }, 0); } else { fetch(alias, cb); } }; this.reportError = function (err, cb) { var queryParams = {}; var url = options.baseUrl + '/client-error/'; var request = (0, _superagent2.default)('post', url); queryParams[_constants2.default.SITE_NAME_LABEL] = options.siteName; request.query(queryParams).send(err).timeout(options.timeout).end(function (err, res) { err = packError(err, res); if (err) { cb && cb(err); } else { cb && cb(); } }); }; this.post = function (videomail, cb) { videomail = applyDefaultValues(videomail); // always good to know the version of the client // the videomail was submitted with videomail[_constants2.default.VERSION_LABEL] = options.version; if (options.callbacks.adjustFormDataBeforePosting) { options.callbacks.adjustFormDataBeforePosting(videomail, function (err, adjustedVideomail) { if (err) { cb(err); } else { write('post', adjustedVideomail, cb); } }); } else { write('post', videomail, cb); } }; this.put = function (videomail, cb) { write('put', videomail, videomail.key, cb); }; this.form = function (formData, url, cb) { var formType; switch (options.enctype) { case _constants2.default.public.ENC_TYPE_APP_JSON: formType = 'json'; break; case _constants2.default.public.ENC_TYPE_FORM: formType = 'form'; break; default: // keep all callbacks async setTimeout(function () { cb(new Error('Invalid enctype given: ' + options.enctype)); }, 0); } if (formType) { _superagent2.default.post(url).type(formType).send(formData).timeout(options.timeout).end(function (err, res) { err = packError(err, res); if (err) { cb(err); } else { cb(null, res); } }); } }; }; var _superagent = _dereq_('superagent'); var _superagent2 = _interopRequireDefault(_superagent); var _constants = _dereq_('./constants'); var _constants2 = _interopRequireDefault(_constants); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CACHE_KEY = 'alias'; },{"./constants":87,"superagent":70}],91:[function(_dereq_,module,exports){ 'use strict'; module.exports = '@keyframes a{0%{opacity:.9}35%{opacity:.9}50%{opacity:.1}85%{opacity:.1}to{opacity:.9}}.IIV::-webkit-media-controls-play-button,.IIV::-webkit-media-controls-start-playback-button{opacity:0;pointer-events:none;width:5px}.videomail .visuals{position:relative}.videomail .visuals video.replay{width:100%;height:100%}.videomail .countdown,.videomail .pausedHeader,.videomail .pausedHint,.videomail .recordNote,.videomail .recordTimer{margin:0;height:auto}.videomail .countdown,.videomail .paused,.videomail .recordNote,.videomail .recordTimer,.videomail noscript{position:absolute}.videomail .countdown,.videomail .pausedHeader,.videomail .pausedHint,.videomail .recordNote,.videomail .recordTimer,.videomail noscript{font-weight:700}.videomail .countdown,.videomail .paused,.videomail noscript{width:100%;top:50%;transform:translateY(-50%)}.videomail .countdown,.videomail .pausedHeader,.videomail .pausedHint{text-align:center;text-shadow:0 0 2px #fff}.videomail .countdown,.videomail .pausedHeader{opacity:.85;font-size:440%}.videomail .pausedHint{font-size:150%}.videomail .recordNote,.videomail .recordTimer{right:.7em;background:hsla(0,0%,4%,.8);padding:.4em .4em .3em;transition:all 1s ease;color:#00d814;font-family:monospace;opacity:.9}.videomail .recordNote.near,.videomail .recordTimer.near{color:#eb9369}.videomail .recordNote.nigh,.videomail .recordTimer.nigh{color:#ea4b2a}.videomail .recordTimer{top:.7em}.videomail .recordNote{top:3.6em}.videomail .recordNote:before{content:"REC";animation:a 1s infinite}.videomail .notifier{overflow:hidden;box-sizing:border-box;height:100%}.videomail .radioGroup{display:block}.videomail video{margin-bottom:0}'; },{}],92:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (userMedia, options) { var scriptProcessor; var audioInput; var vcAudioContext; function hasAudioContext() { return !!getAudioContext(); } function getAudioContext() { // instantiate only once if (!vcAudioContext) { var AudioContext = window.AudioContext || window.webkitAudioContext; vcAudioContext = new AudioContext(); } return vcAudioContext; } function onAudioProcess(e, cb) { if (!userMedia.isRecording() || userMedia.isPaused()) { return; } // Returns a Float32Array containing the PCM data associated with the channel, // defined by the channel parameter (with 0 representing the first channel) var float32Array = e.inputBuffer.getChannelData(0); cb(new _audioSample2.default(float32Array)); } this.init = function (localMediaStream) { options.debug('AudioRecorder: init()'); // creates an audio node from the microphone incoming stream var volume = getAudioContext().createGain(); try { audioInput = getAudioContext().createMediaStreamSource(localMediaStream); } catch (exc) { throw _videomailError2.default.create('Webcam has no audio', exc.toString(), options); } if (!(0, _isPowerOfTwo2.default)(options.audio.bufferSize)) { throw _videomailError2.default.create('Audio buffer size must be a power of two.', options); } else if (!options.audio.volume || options.audio.volume > 1) { throw _videomailError2.default.create('Audio volume must be between zero and one.', options); } volume.gain.value = options.audio.volume; // Create a ScriptProcessorNode with the given bufferSize and // a single input and output channel scriptProcessor = getAudioContext().createScriptProcessor(options.audio.bufferSize, CHANNELS, CHANNELS); // connect stream to our scriptProcessor audioInput.connect(scriptProcessor); // connect our scriptProcessor to the previous destination scriptProcessor.connect(getAudioContext().destination); // connect volume audioInput.connect(volume); volume.connect(scriptProcessor); }; this.record = function (cb) { options.debug('AudioRecorder: record()'); scriptProcessor.onaudioprocess = function (e) { onAudioProcess(e, cb); }; }; this.stop = function () { options.debug('AudioRecorder: stop()'); if (scriptProcessor) { scriptProcessor.onaudioprocess = undefined; } if (audioInput) { audioInput.disconnect(); } // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/close if (hasAudioContext()) { if (getAudioContext().close) { getAudioContext().close().then(function () { options.debug('AudioRecorder: audio context is closed'); vcAudioContext = null; }).catch(function (err) { throw _videomailError2.default.create(err, options); }); } else { vcAudioContext = null; } } }; this.getSampleRate = function () { if (hasAudioContext()) { return getAudioContext().sampleRate; } else { return -1; } }; }; var _isPowerOfTwo = _dereq_('is-power-of-two'); var _isPowerOfTwo2 = _interopRequireDefault(_isPowerOfTwo); var _audioSample = _dereq_('audio-sample'); var _audioSample2 = _interopRequireDefault(_audioSample); var _videomailError = _dereq_('./videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CHANNELS = 1; // for inspiration see // https://github.com/saebekassebil/microphone-stream // todo code needs rewrite },{"./videomailError":100,"audio-sample":4,"is-power-of-two":43}],93:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _uaParserJs = _dereq_('ua-parser-js'); var _uaParserJs2 = _interopRequireDefault(_uaParserJs); var _defined = _dereq_('defined'); var _defined2 = _interopRequireDefault(_defined); var _videomailError = _dereq_('./videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Browser = function Browser(options) { options = options || {}; var firefoxDownload = 'http://www.mozilla.org/firefox/update/'; var edgeDownload = 'https://www.microsoft.com/en-us/download/details.aspx?id=48126'; var chromeDownload = 'http://www.google.com/chrome/'; var chromiumDownload = 'http://www.chromium.org/getting-involved/download-chromium'; var browseHappyLink = 'http://browsehappy.com'; var ua = (0, _defined2.default)(options.fakeUaString, typeof window !== 'undefined' && window.navigator && window.navigator.userAgent, ''); var uaParser = new _uaParserJs2.default(ua).getResult(); var isIOS = uaParser.os.name === 'iOS'; var browserVersion = parseFloat(uaParser.browser.version); var isChrome = uaParser.browser.name === 'Chrome'; var isChromium = uaParser.browser.name === 'Chromium'; var firefox = uaParser.browser.name === 'Firefox'; var osVersion = parseFloat(uaParser.os.version); var isWindows = uaParser.os.name === 'Windows'; var isEdge = uaParser.browser.name === 'Edge' || isWindows && osVersion >= 10; var isIE = /IE/.test(uaParser.browser.name); var isSafari = /Safari/.test(uaParser.browser.name); var isOpera = /Opera/.test(uaParser.browser.name); var isAndroid = /Android/.test(uaParser.os.name); var chromeBased = isChrome || isChromium; var isOkSafari = isSafari && browserVersion >= 11; var isOkIOS = isIOS && osVersion >= 11; var isBadIOS = isIOS && osVersion < 11; var okBrowser = chromeBased || firefox || isAndroid || isOpera || isEdge || isOkSafari || isOkIOS; var self = this; var videoType; function getRecommendation() { var warning; if (firefox) { if (isIOS) { warning = 'Firefox on iOS is not ready for webcams yet. Hopefully in near future ...'; } else { warning = 'Probably you need to <a href="' + firefoxDownload + '" target="_blank">' + 'upgrade Firefox</a> to fix this.'; } } else if (isChrome) { if (isIOS) { warning = 'Chrome on iOS is not ready for webcams yet. Hopefully in near future ...'; } else { warning = 'Probably you need to <a href="' + chromeDownload + '" target="_blank">' + 'upgrade Chrome</a> to fix this.'; } } else if (isChromium) { warning = 'Probably you need to <a href="' + chromiumDownload + '" target="_blank">' + 'upgrade Chromium</a> to fix this.'; } else if (isIE) { warning = 'Instead of Internet Explorer you need to upgrade to' + ' <a href="' + edgeDownload + '" target="_blank">Edge</a>.'; } else if (isOkSafari) { warning = 'Probably you need to shut down Safari and restart it, this for correct webcam access.'; } else if (isSafari) { warning = 'Safari below version 11 has no webcam support.<br/>Better upgrade Safari or pick' + ' <a href="' + chromeDownload + '" target="_blank">Chrome</a>,' + ' <a href="' + firefoxDownload + '" target="_blank">Firefox</a> or Android.'; } return warning; } function getUserMediaWarning() { var warning; if (isBadIOS) { warning = 'On iPads/iPhones below iOS v11 this webcam feature is missing.<br/><br/>' + 'For now, we recommend you to upgrade iOS or to use an Android device.'; } else { warning = getRecommendation(); } if (!warning) { if (self.isChromeBased() || self.isFirefox() || isSafari) { warning = 'For the webcam feature, your browser needs an upgrade.'; } else { warning = 'Hence we recommend you to use either ' + '<a href="' + chromeDownload + '" target="_blank">Chrome</a>, ' + '<a href="' + firefoxDownload + '" target="_blank">Firefox</a>, ' + '<a href="' + edgeDownload + '" target="_blank">Edge</a> or Android.'; } } return warning; } function getPlaybackWarning() { var warning = getRecommendation(); if (!warning) { warning = '<a href="' + browseHappyLink + '" target="_blank">Upgrading your browser</a> might help.'; } return warning; } function canPlayType(video, type) { var canPlayType; if (video && video.canPlayType) { canPlayType = video.canPlayType('video/' + type); } return canPlayType; } // just temporary this.canRecord = function () { var hasNavigator = typeof navigator !== 'undefined'; var canRecord = false; if (hasNavigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { canRecord = true; } else { var getUserMediaType = hasNavigator && _typeof(navigator.getUserMedia_); canRecord = getUserMediaType === 'function'; } return canRecord; }; this.checkRecordingCapabilities = function () { var err; if (!okBrowser || !this.canRecord()) { var classList = []; if (isBadIOS) { classList.push(_videomailError2.default.IOS_PROBLEM); } else { classList.push(_videomailError2.default.BROWSER_PROBLEM); } err = _videomailError2.default.create({ message: 'Sorry, your browser is unable to use webcams' }, getUserMediaWarning(), options, { classList: classList }); } return err; }; this.checkPlaybackCapabilities = function (video) { options.debug('Browser: checkPlaybackCapabilities()'); var err; var message; if (!video) { message = 'No HTML5 support for video tag!'; } else if (!this.getVideoType(video)) { message = 'Your old browser cannot support modern video codecs'; } else if (!video.setAttribute) { // fixes "Not implemented" error on older browsers message = 'Unable to set video attributes in your old browser'; } if (message) { err = _videomailError2.default.create(message, getPlaybackWarning(), options); } return err; }; this.checkBufferTypes = function () { var err; if (typeof window === 'undefined' || typeof window.atob === 'undefined') { err = _videomailError2.default.create('atob is not supported', options); } else if (typeof window.ArrayBuffer === 'undefined') { err = _videomailError2.default.create('ArrayBuffers are not supported', options); } else if (typeof window.Uint8Array === 'undefined') { err = _videomailError2.default.create('Uint8Arrays are not supported', options); } return err; }; this.getVideoType = function (video) { if (!videoType) { // there is a bug in canPlayType within chrome for mp4 if (canPlayType(video, 'mp4') && !chromeBased) { videoType = 'mp4'; } else if (canPlayType(video, 'webm')) { videoType = 'webm'; } } return videoType; }; this.getNoAccessIssue = function () { var message = 'Unable to access webcam'; var explanation; if (this.isChromeBased()) { explanation = 'Click on the allow button to grant access to your webcam.'; } else if (this.isFirefox()) { explanation = 'Please grant Firefox access to your webcam.'; } else { explanation = 'Your system does not let your browser access your webcam.'; } return _videomailError2.default.create(message, explanation, options); }; this.isChromeBased = function () { return chromeBased; }; this.isFirefox = function () { return firefox; }; this.isEdge = function () { return isEdge; }; this.isAndroid = function () { return isAndroid; }; this.isMobile = function () { return uaParser.device.type === 'mobile'; }; this.isOkSafari = function () { return isOkSafari; }; this.getUsefulData = function () { return { browser: uaParser.browser, device: uaParser.device, os: uaParser.os, engine: uaParser.engine, userAgent: ua }; }; }; exports.default = Browser; // so that we also can require() it from videomailError.js within module.exports = Browser; },{"./videomailError":100,"defined":17,"ua-parser-js":76}],94:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { var localOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var browser = new _browser2.default(localOptions); var logger = localOptions.logger || console; var containerId = localOptions.selectors && localOptions.selectors.containerId || 'undefined container id'; var stack = []; function lifo(level, parameters) { var line = _util2.default.format.apply(_util2.default, parameters); if (stack.length > localOptions.logStackSize) { stack.pop(); } stack.push('[' + level + '] ' + line); return line; } function addContainerId(firstArgument) { return '#' + containerId + ' [' + new Date().toLocaleTimeString() + '] > ' + firstArgument; } // workaround: since we cannot overwrite console.log without having the correct file and line number // we'll use groupCollapsed() and trace() instead to get these. this.debug = function () { // always add it for better client error reports var args = [].slice.call(arguments, 0); args[0] = addContainerId(args[0]); var output = lifo('debug', args); if (localOptions.verbose) { if (browser.isFirefox()) { logger.debug(output); } else if (logger.groupCollapsed) { logger.groupCollapsed(output); logger.trace('Trace'); logger.groupEnd(); } else if (logger.debug) { logger.debug(output); } else { // last resort if everything else fails for any weird reasons console.log(output); } } }; this.error = function () { var args = [].slice.call(arguments, 0); args[0] = addContainerId(args[0]); logger.error(lifo('error', args)); }; this.warn = function () { var args = [].slice.call(arguments, 0); args[0] = addContainerId(args[0]); logger.warn(lifo('warn', args)); }; this.getLines = function () { return stack; }; }; var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _browser = _dereq_('./browser'); var _browser2 = _interopRequireDefault(_browser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"./browser":93,"util":80}],95:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (options, name) { this.emit = function (event) { var args = Array.prototype.slice.call(arguments, 0); if (!event) { throw _videomailError2.default.create('You cannot emit without an event.', options); } // Automatically convert errors to videomail errors if (event === _events2.default.ERROR) { var err = args[1]; err = _videomailError2.default.create(err, options); args[1] = err; } if (options.debug) { if (event !== 'removeListener' && event !== 'newListener') { var moreArguments; if (args[1]) { moreArguments = args.slice(1); } if (moreArguments) { options.debug('%s emits: %s', name, event, moreArguments); } else { options.debug('%s emits: %s', name, event); } } } var result = _despot2.default.emit.apply(_despot2.default, args); // Todo: have this emitted through a configuration because it is pretty noisy // if (event !== Events.EVENT_EMITTED) // this.emit(Events.EVENT_EMITTED, event) return result; }; this.on = function (eventName, cb) { return _despot2.default.on(eventName, cb); }; this.once = function (eventName, cb) { return _despot2.default.once(eventName, cb); }; this.listeners = function (eventName) { return _despot2.default.listeners(eventName); }; this.removeListener = function (eventName, cb) { return _despot2.default.removeListener(eventName, cb); }; this.removeAllListeners = function () { _despot2.default.removeAllListeners(); }; }; var _despot = _dereq_('despot'); var _despot2 = _interopRequireDefault(_despot); var _videomailError = _dereq_('./videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); var _events = _dereq_('./../events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"./../events":88,"./videomailError":100,"despot":18}],96:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _filesize2 = _dereq_('filesize'); var _filesize3 = _interopRequireDefault(_filesize2); var _humanizeDuration = _dereq_('humanize-duration'); var _humanizeDuration2 = _interopRequireDefault(_humanizeDuration); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // todo get rid of this class and use those imports directly exports.default = { filesize: function filesize(bytes, round) { return (0, _filesize3.default)(bytes, { round: round }); }, toTime: function toTime(t) { return (0, _humanizeDuration2.default)(t); } }; },{"filesize":26,"humanize-duration":33}],97:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // taken from // https://bbc.github.io/tal/jsdoc/events_mediaevent.js.html exports.default = [ // The user agent begins looking for media data, as part of // the resource selection algorithm. 'loadstart', // The user agent is intentionally not currently fetching media data, // but does not have the entire media resource downloaded. networkState equals NETWORK_IDLE 'suspend', // Playback has begun. Fired after the play() method has returned, // or when the autoplay attribute has caused playback to begin. // paused is newly false. // 'play', commented out since it has special treatment // The user agent has just determined the duration and dimensions of the // media resource and the timed tracks are ready. // readyState is newly equal to HAVE_METADATA or greater for the first time. // 'loadedmetadata', commented out since it has special treatment // The user agent is fetching media data. 'progress', // The user agent is intentionally not currently fetching media data, // but does not have the entire media resource downloaded. // 'suspend', // commented out, we are already listening to it in code // Event The user agent stops fetching the media data before it is completely downloaded, // but not due to an error. error is an object with the code MEDIA_ERR_ABORTED. 'abort', // A media element whose networkState was previously not in the NETWORK_EMPTY // state has just switched to that state (either because of a fatal error // during load that's about to be reported, or because the load() method was // invoked while the resource selection algorithm was already running). 'emptied', // The user agent is trying to fetch media data, but data is // unexpectedly not forthcoming 'stalled', // Playback has been paused. Fired after the pause() method has returned. // paused is newly true. 'pause', // The user agent can render the media data at the current playback position // for the first time. // readyState newly increased to HAVE_CURRENT_DATA or greater for the first time. 'loadeddata', // Playback has stopped because the next frame is not available, but the user // agent expects that frame to become available in due course. // readyState is newly equal to or less than HAVE_CURRENT_DATA, // and paused is false. Either seeking is true, or the current playback // position is not contained in any of the ranges in buffered. // It is possible for playback to stop for two other reasons without // paused being false, but those two reasons do not fire this event: // maybe playback ended, or playback stopped due to errors. 'waiting', // Playback has started. readyState is newly equal to or greater than // HAVE_FUTURE_DATA, paused is false, seeking is false, // or the current playback position is contained in one of the ranges in buffered. 'playing', // The user agent can resume playback of the media data, // but estimates that if playback were to be started now, the media resource // could not be rendered at the current playback rate up to its end without // having to stop for further buffering of content. // readyState newly increased to HAVE_FUTURE_DATA or greater. 'canplay', // The user agent estimates that if playback were to be started now, // the media resource could be rendered at the current playback rate // all the way to its end without having to stop for further buffering. // readyState is newly equal to HAVE_ENOUGH_DATA. 'canplaythrough', // The seeking IDL attribute changed to true and the seek operation is // taking long enough that the user agent has time to fire the event. 'seeking', // The seeking IDL attribute changed to false. 'seeked', // Playback has stopped because the end of the media resource was reached. // currentTime equals the end of the media resource; ended is true. 'ended', // Either the defaultPlaybackRate or the playbackRate attribute // has just been updated. 'ratechange', // The duration attribute has just been updated. 'durationchange', // Either the volume attribute or the muted attribute has changed. // Fired after the relevant attribute's setter has returned. 'volumechange' // commented out, happen too often // The current playback position changed as part of normal playback or in // an especially interesting way, for example discontinuously. // 'timeupdate' ]; },{}],98:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = function (anything, options) { if (anything === null) { return 'null'; } else if (typeof anything === 'undefined') { return 'undefined'; } else if (typeof anything === 'string') { return anything; } else if (Array.isArray(anything)) { return arrayToString(anything); } else if ((typeof anything === 'undefined' ? 'undefined' : _typeof(anything)) === 'object') { return objectToString(anything, options); } else { return anything.toString(); } }; var _fastSafeStringify = _dereq_('fast-safe-stringify'); var _fastSafeStringify2 = _interopRequireDefault(_fastSafeStringify); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DASH = '- '; var SEPARATOR = '<br/>' + DASH; function arrayToString(array) { if (array.length > 0) { var lines = []; array.forEach(function (element) { if (element) { lines.push((0, _fastSafeStringify2.default)(element)); } }); return DASH + lines.join(SEPARATOR); } } function objectToString(object, options) { var propertyNames = Object.getOwnPropertyNames(object); var excludes = options && options.excludes || []; var lines = []; var sLines; // always ignore these excludes.push('stack'); if (propertyNames.length > 0) { var exclude = false; propertyNames.forEach(function (name) { if (excludes) { exclude = excludes.indexOf(name) >= 0; } if (!exclude) { // this to cover this problem: // https://github.com/binarykitchen/videomail-client/issues/157 lines.push((0, _fastSafeStringify2.default)(object[name])); } }); } if (lines.length === 1) { sLines = lines.join(); } else if (lines.length > 1) { sLines = DASH + lines.join(SEPARATOR); } return sLines; } },{"fast-safe-stringify":25}],99:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var navigator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // https://github.com/julienetie/request-frame/issues/6 if (!window.screen) { window.screen = {}; } (0, _requestFrame2.default)('native'); // avoids warning "navigator.mozGetUserMedia has been replaced by navigator.mediaDevices.getUserMedia", // see https://github.com/binarykitchen/videomail-client/issues/79 if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { // do not shim } else { navigator.getUserMedia_ = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; } if (!window.AudioContext && window.webkitAudioContext) { window.AudioContext = window.webkitAudioContext; } if (!window.URL) { window.URL = window.webkitURL || window.mozURL || window.msURL; } var methods = ['debug', 'groupCollapsed', 'groupEnd', 'error', 'exception', 'info', 'log', 'trace', 'warn']; var console = {}; if (window.console) { console = window.console; } else { window.console = function () {}; } var method; var length = methods.length; while (length--) { method = methods[length]; if (!console[method]) { console[method] = function () {}; } } }; _dereq_('classlist.js'); _dereq_('element-closest'); var _requestFrame = _dereq_('request-frame'); var _requestFrame2 = _interopRequireDefault(_requestFrame); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"classlist.js":11,"element-closest":22,"request-frame":66}],100:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // https://github.com/tgriesser/create-error var _createError = _dereq_('create-error'); var _createError2 = _interopRequireDefault(_createError); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _pretty = _dereq_('./pretty'); var _pretty2 = _interopRequireDefault(_pretty); var _resource = _dereq_('./../resource'); var _resource2 = _interopRequireDefault(_resource); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var VIDEOMAIL_ERR_NAME = 'Videomail Error'; var VideomailError = (0, _createError2.default)(Error, VIDEOMAIL_ERR_NAME, { 'explanation': undefined, 'logLines': undefined, 'useragent': undefined, 'url': undefined, 'stack': undefined }); // shim pretty to exclude stack always var pretty = function pretty(anything) { return (0, _pretty2.default)(anything, { excludes: ['stack'] }); }; // static and public attribute of this class VideomailError.PERMISSION_DENIED = 'PERMISSION_DENIED'; VideomailError.NOT_ALLOWED_ERROR = 'NotAllowedError'; VideomailError.NOT_CONNECTED = 'Not connected'; VideomailError.DOM_EXCEPTION = 'DOMException'; VideomailError.STARTING_FAILED = 'Starting video failed'; VideomailError.MEDIA_DEVICE_NOT_SUPPORTED = 'MediaDeviceNotSupported'; VideomailError.BROWSER_PROBLEM = 'browser-problem'; VideomailError.WEBCAM_PROBLEM = 'webcam-problem'; VideomailError.IOS_PROBLEM = 'ios-problem'; VideomailError.OVERCONSTRAINED = 'OverconstrainedError'; VideomailError.NOT_FOUND_ERROR = 'NotFoundError'; VideomailError.NOT_READABLE_ERROR = 'NotReadableError'; VideomailError.SECURITY_ERROR = 'SecurityError'; VideomailError.TRACK_START_ERROR = 'TrackStartError'; // static function to convert an error into a videomail error VideomailError.create = function (err, explanation, options, parameters) { if (err && err.name === VIDEOMAIL_ERR_NAME) { return err; } if (!options && explanation) { options = explanation; explanation = undefined; } options = options || {}; parameters = parameters || {}; // be super robust var debug = options && options.debug || console.log; var audioEnabled = options && options.isAudioEnabled && options.isAudioEnabled(); debug('VideomailError: create()', err, explanation); var classList = parameters.classList || []; // Require Browser here, not at the top of the file to avoid // recursion. Because the Browser class is requiring this file as well. var Browser = _dereq_('./browser'); var browser = new Browser(options); var errType; var message; var stack; // whole code is ugly because all browsers behave so differently :( if ((typeof err === 'undefined' ? 'undefined' : _typeof(err)) === 'object') { if (err.name === VideomailError.TRACK_START_ERROR) { errType = VideomailError.TRACK_START_ERROR; } else if (err.name === VideomailError.SECURITY_ERROR) { errType = VideomailError.SECURITY_ERROR; } else if (err.code === 8 && err.name === VideomailError.NotFoundError) { errType = VideomailError.NotFoundError; } else if (err.code === 35 || err.name === VideomailError.NOT_ALLOWED_ERROR) { // https://github.com/binarykitchen/videomail.io/issues/411 errType = VideomailError.NOT_ALLOWED_ERROR; } else if (err.code === 1 && err.PERMISSION_DENIED === 1) { errType = VideomailError.PERMISSION_DENIED; } else if (err.constructor && err.constructor.name === VideomailError.DOM_EXCEPTION) { if (err.name === VideomailError.NOT_READABLE_ERROR) { errType = VideomailError.NOT_READABLE_ERROR; } else { errType = VideomailError.DOM_EXCEPTION; } } else if (err.constructor && err.constructor.name === VideomailError.OVERCONSTRAINED) { errType = VideomailError.OVERCONSTRAINED; } else if (err.message === VideomailError.STARTING_FAILED) { errType = err.message; } else if (err.name) { errType = err.name; } else if (err.type === 'error' && err.target.bufferedAmount === 0) { errType = VideomailError.NOT_CONNECTED; } } else if (err === VideomailError.NOT_CONNECTED) { errType = VideomailError.NOT_CONNECTED; } else { errType = err; } if (err && err.stack) { stack = err.stack; } else { stack = new Error().stack; } switch (errType) { case VideomailError.SECURITY_ERROR: message = 'The operation was insecure'; explanation = 'Probably you have disallowed Cookies for this page?'; classList.push(VideomailError.BROWSER_PROBLEM); break; case VideomailError.OVERCONSTRAINED: message = 'Invalid webcam constraints'; if (err.constraint) { if (err.constraint === 'width') { explanation = 'Your webcam does not meet the width requirement.'; } else { explanation = 'Unmet constraint: ' + err.constraint; } } else { explanation = ' Details: ' + err.toString(); } break; case 'MediaDeviceFailedDueToShutdown': message = 'Webcam is shutting down'; explanation = 'This happens your webcam is already switching off and not giving you permission to use it.'; break; case 'SourceUnavailableError': message = 'Source of your webcam cannot be accessed'; explanation = 'Probably it is locked from another process or has a hardware error.'; if (err.message) { err.message += ' Details: ' + err.message; } break; case VideomailError.NOT_FOUND_ERROR: case 'NO_DEVICES_FOUND': if (audioEnabled) { message = 'No webcam nor microphone found'; explanation = 'Your browser cannot find a webcam with microphone attached to your machine.'; } else { message = 'No webcam found'; explanation = 'Your browser cannot find a webcam attached to your machine.'; } classList.push(VideomailError.WEBCAM_PROBLEM); break; case 'PermissionDismissedError': message = 'Ooops, you didn\'t give me any permissions?'; explanation = 'Looks like you skipped the webcam permission dialogue.<br/>' + 'Please grant access next time the dialogue appears.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case VideomailError.NOT_ALLOWED_ERROR: case VideomailError.PERMISSION_DENIED: case 'PermissionDeniedError': message = 'Permission denied'; explanation = 'Cannot access your webcam. This can have two reasons:<br/>' + 'a) you blocked access to webcam; or<br/>' + 'b) your webcam is already in use.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case 'HARDWARE_UNAVAILABLE': message = 'Webcam is unavailable'; explanation = 'Maybe it is already busy in another window?'; if (browser.isChromeBased()) { explanation += ' Or you have to allow access above?'; } classList.push(VideomailError.WEBCAM_PROBLEM); break; case VideomailError.NOT_CONNECTED: message = 'Unable to connect'; explanation = 'Either the videomail server or your connection is down. ' + 'Trying to reconnect every few seconds …'; break; case 'NO_VIDEO_FEED': message = 'No video feed found!'; explanation = 'Your webcam is already used in another browser.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case VideomailError.STARTING_FAILED: message = 'Starting video failed'; explanation = 'Most likely this happens when the webam is already active in another browser.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case 'DevicesNotFoundError': message = 'No available webcam could be found'; explanation = 'Looks like you do not have any webcam attached to your machine; or ' + 'the one you plugged in is already used.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case VideomailError.NOT_READABLE_ERROR: case VideomailError.TRACK_START_ERROR: message = 'No access to webcam'; explanation = 'A hardware error occurred which prevented access to your webcam.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case VideomailError.DOM_EXCEPTION: switch (err.code) { case 8: message = 'Requested webcam not found'; explanation = 'A webcam is needed but could not be found.'; classList.push(VideomailError.WEBCAM_PROBLEM); break; case 9: var newUrl = 'https:' + window.location.href.substring(window.location.protocol.length); message = 'Security upgrade needed'; explanation = 'Click <a href="' + newUrl + '">here</a> to switch to HTTPs which is more safe ' + ' and enables encrypted videomail transfers.'; classList.push(VideomailError.BROWSER_PROBLEM); break; case 11: message = 'Invalid State'; explanation = 'The object is in an invalid, unusable state.'; classList.push(VideomailError.BROWSER_PROBLEM); break; default: message = 'DOM Exception'; explanation = pretty(err); classList.push(VideomailError.BROWSER_PROBLEM); break; } break; // Chrome has a weird problem where if you try to do a getUserMedia request too early, it // can return a MediaDeviceNotSupported error (even though nothing is wrong and permission // has been granted). Look at userMediaErrorCallback() in recorder, there we do not // emit those kind of errors further and just retry. // // but for whatever reasons, if it happens to reach this code, then investigate this further. case VideomailError.MEDIA_DEVICE_NOT_SUPPORTED: message = 'Media device not supported'; explanation = pretty(err); break; default: var originalExplanation = explanation; if (explanation && (typeof explanation === 'undefined' ? 'undefined' : _typeof(explanation)) === 'object') { explanation = pretty(explanation); } // it can be that explanation itself is an error object // error objects can be prettified to undefined sometimes if (!explanation && originalExplanation) { if (originalExplanation.message) { explanation = originalExplanation.message; } else { // tried toString before but nah explanation = 'Inspected: ' + _util2.default.inspect(originalExplanation, { showHidden: true }); } } if (err && typeof err === 'string') { message = err; } else { if (err) { if (err.message) { message = pretty(err.message); } } if (err && err.explanation) { if (!explanation) { explanation = pretty(err.explanation); } else { explanation += ';<br/>' + pretty(err.explanation); } } if (err && err.details) { var details = pretty(err.details); if (!explanation) { explanation = details; } else { explanation += ';<br/>' + details; } } } // for weird, undefined cases if (!message) { if (errType) { message = errType; } if (!explanation && err) { explanation = pretty(err, { excludes: ['stack'] }); } // avoid dupes if (pretty(message) === explanation) { explanation = undefined; } } break; } var logLines = null; if (options.logger && options.logger.getLines) { logLines = options.logger.getLines(); } if (stack) { message = new Error(message); message.stack = stack; } var errCode = 'none'; if (err) { errCode = 'code=' + (err.code ? err.code : 'undefined'); errCode += ', type=' + (err.type ? err.type : 'undefined'); errCode += ', name=' + (err.name ? err.name : 'undefined'); errCode += ', message=' + (err.message ? err.message : 'undefined'); } var videomailError = new VideomailError(message, { explanation: explanation, logLines: logLines, client: browser.getUsefulData(), url: window.location.href, siteName: options.siteName, code: errCode, stack: stack // have to assign it manually again because it is kinda protected }); var resource; var reportErrors = false; if (options.reportErrors) { if (typeof options.reportErrors === 'function') { reportErrors = options.reportErrors(videomailError); } else { reportErrors = options.reportErrors; } } if (reportErrors) { resource = new _resource2.default(options); } if (resource) { resource.reportError(videomailError, function (err2) { if (err2) { console.error('Unable to report error', err2); } }); } function hasClass(name) { return classList.indexOf(name) >= 0; } function isBrowserProblem() { return hasClass(VideomailError.BROWSER_PROBLEM) || parameters.browserProblem; } // add some public functions // this one is useful so that the notifier can have different css classes videomailError.getClassList = function () { return classList; }; videomailError.removeDimensions = function () { return hasClass(VideomailError.IOS_PROBLEM) || browser.isMobile(); }; videomailError.hideButtons = function () { return isBrowserProblem() || hasClass(VideomailError.IOS_PROBLEM); }; videomailError.hideForm = function () { return hasClass(VideomailError.IOS_PROBLEM); }; return videomailError; }; exports.default = VideomailError; },{"./../resource":90,"./browser":93,"./pretty":98,"create-error":15,"util":80}],101:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _contains = _dereq_('contains'); var _contains2 = _interopRequireDefault(_contains); var _events = _dereq_('./../events'); var _events2 = _interopRequireDefault(_events); var _eventEmitter = _dereq_('./../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Buttons = function Buttons(container, options) { _eventEmitter2.default.call(this, options, 'Buttons'); var self = this; var debug = options.debug; var buttonsElement; var recordButton; var pauseButton; var resumeButton; var previewButton; var recordAgainButton; var submitButton; var audioOnRadioPair; var audioOffRadioPair; var built; function hide(elements) { if (elements && !Array.isArray(elements)) { elements = [elements]; } elements && elements.forEach(function (element) { (0, _hidden2.default)(element, true); }); } function show(elements) { if (elements && !Array.isArray(elements)) { elements = [elements]; } elements && elements.forEach(function (element) { (0, _hidden2.default)(element, false); }); } function isShown(elements) { var isShown = elements && true; if (elements && !Array.isArray(elements)) { elements = [elements]; } elements && elements.forEach(function (element) { isShown = isShown && element && !(0, _hidden2.default)(element); }); return isShown; } function disable(elements) { if (elements && !Array.isArray(elements)) { elements = [elements]; } elements && elements.forEach(function (element) { // https://github.com/binarykitchen/videomail-client/issues/148 if (element) { if (element.tagName === 'INPUT' || element.tagName === 'BUTTON') { element.disabled = true; } else { element.classList.add('disabled'); } } }); } function enable(elements) { if (elements && !Array.isArray(elements)) { elements = [elements]; } elements && elements.forEach(function (element) { // https://github.com/binarykitchen/videomail-client/issues/148 if (element) { if (element.tagName === 'INPUT' || element.tagName === 'BUTTON') { element.disabled = false; } else { element.classList.remove('disabled'); } } }); } function adjustButton(buttonElement, show, type, disabled) { if (disabled) { disable(buttonElement); } if (type) { buttonElement.type = type; } else if (!buttonElement.type) { buttonElement.type = 'button'; } !show && hide(buttonElement); return buttonElement; } function replaceClickHandler(element, clickHandler) { var wrappedClickHandler = function wrappedClickHandler(e) { e && e.preventDefault(); try { clickHandler({ event: e }); } catch (exc) { self.emit(_events2.default.ERROR, exc); } }; element.onclick = wrappedClickHandler; } function makeRadioButtonPair(options) { var radioButtonElement; var radioButtonGroup; if (options.id) { radioButtonElement = document.getElementById(options.id); } if (!radioButtonElement) { radioButtonElement = (0, _hyperscript2.default)('input#' + options.id, { type: 'radio', name: options.name, value: options.value, checked: options.checked }); radioButtonGroup = (0, _hyperscript2.default)('span.radioGroup', radioButtonElement, (0, _hyperscript2.default)('label', { 'htmlFor': options.id }, options.label)); // double check that submit button is already in the buttonsElement container as a child? if (submitButton && (0, _contains2.default)(buttonsElement, submitButton)) { buttonsElement.insertBefore(radioButtonGroup, submitButton); } else { buttonsElement.appendChild(radioButtonGroup); } } if (options.changeHandler) { radioButtonElement.onchange = options.changeHandler; } disable(radioButtonElement); return [radioButtonElement, radioButtonGroup]; } function makeButton(buttonClass, text, clickHandler, show, id, type, selector) { var disabled = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : true; var buttonElement; if (id) { buttonElement = document.getElementById(id); } else if (selector) { buttonElement = document.querySelector(selector); } else { buttonElement = buttonsElement.querySelector('.' + buttonClass); } if (!buttonElement) { if (options.selectors.buttonClass) { buttonClass += '.' + options.selectors.buttonClass; } buttonElement = (0, _hyperscript2.default)('button.' + buttonClass); buttonElement = adjustButton(buttonElement, show, type, disabled); buttonElement.innerHTML = text; // double check that submit button is already in the buttonsElement container if (submitButton && (0, _contains2.default)(buttonsElement, submitButton)) { buttonsElement.insertBefore(buttonElement, submitButton); } else { buttonsElement.appendChild(buttonElement); } } else { buttonElement = adjustButton(buttonElement, show, type, disabled); } if (clickHandler) { replaceClickHandler(buttonElement, clickHandler); } return buttonElement; } function buildButtons() { if (!options.disableSubmit) { if (!submitButton) { submitButton = makeButton(options.selectors.submitButtonClass, 'Submit', null, true, options.selectors.submitButtonId, 'submit', options.selectors.submitButtonSelector, options.enableAutoValidation); } else { disable(submitButton); } // no need to listen to the submit event when it's already listened // within the form element class if (!container.hasForm() && submitButton) { replaceClickHandler(submitButton, submit); } } recordButton = makeButton(options.selectors.recordButtonClass, options.text.buttons.record, record, false); if (options.enablePause) { pauseButton = makeButton(options.selectors.pauseButtonClass, options.text.buttons.pause, container.pause, false); } if (options.enablePause) { resumeButton = makeButton(options.selectors.resumeButtonClass, options.text.buttons.resume, container.resume, false); } // show stop only when pause is enabled - looks better that way otherwise button // move left and right between record and stop (preview) previewButton = makeButton(options.selectors.previewButtonClass, options.text.buttons.preview, container.stop, false); recordAgainButton = makeButton(options.selectors.recordAgainButtonClass, options.text.buttons.recordAgain, recordAgain, false); if (options.audio && options.audio.switch) { audioOffRadioPair = makeRadioButtonPair({ id: 'audioOffOption', name: 'audio', value: 'off', label: 'Audio Off', checked: !options.isAudioEnabled(), changeHandler: function changeHandler() { container.disableAudio(); } }); audioOnRadioPair = makeRadioButtonPair({ id: 'audioOnOption', name: 'audio', value: 'on', label: 'Audio On (Beta)', checked: options.isAudioEnabled(), changeHandler: function changeHandler() { container.enableAudio(); } }); } } function onFormReady(params) { // no need to show record button when doing a record again if (!isShown(recordAgainButton)) { if (!params.paused) { show(recordButton); } } if (!params.paused) { disable(previewButton); hide(previewButton); } if (!options.enableAutoValidation) { enable(submitButton); } } function onGoingBack() { hide(recordAgainButton); show(recordButton); show(submitButton); } function onReplayShown() { self.hide(); } function onUserMediaReady(options) { onFormReady(options); if (isShown(recordButton)) { enable(recordButton); } if (isShown(audioOnRadioPair)) { enable(audioOnRadioPair); } if (isShown(audioOffRadioPair)) { enable(audioOffRadioPair); } if (options.enableAutoValidation) { disable(submitButton); } } function onResetting() { disable(submitButton); self.reset(); } function onPreview() { hide(recordButton); hide(previewButton); disable(audioOnRadioPair); disable(audioOffRadioPair); show(recordAgainButton); enable(recordAgainButton); if (!options.enableAutoValidation) { enable(submitButton); } } this.enableSubmit = function () { enable(submitButton); }; this.adjustButtonsForPause = function () { if (!self.isCountingDown()) { pauseButton && hide(pauseButton); show(resumeButton); enable(resumeButton); hide(recordButton); show(previewButton); enable(previewButton); } }; function onFirstFrameSent() { hide(recordButton); hide(recordAgainButton); if (pauseButton) { show(pauseButton); enable(pauseButton); } enable(previewButton); show(previewButton); } function onRecording(framesCount) { // it is possible to hide while recording, hence // check framesCount first (coming from recorder) if (framesCount > 1) { onFirstFrameSent(); } else { disable(audioOffRadioPair); disable(audioOnRadioPair); disable(recordAgainButton); disable(recordButton); } } function onResuming() { hide(resumeButton); hide(recordButton); if (pauseButton) { enable(pauseButton); show(pauseButton); } } function onStopping() { disable(previewButton); hide(pauseButton); hide(resumeButton); } function onCountdown() { disable(recordButton); disable(audioOffRadioPair); disable(audioOnRadioPair); } function onSubmitting() { disable(submitButton); disable(recordAgainButton); } function onSubmitted() { disable(previewButton); disable(recordAgainButton); disable(recordButton); disable(submitButton); } function onInvalid() { if (options.enableAutoValidation) { disable(submitButton); } } function onValid() { if (options.enableAutoValidation) { enable(submitButton); } } function onHidden() { hide(recordButton); hide(previewButton); hide(recordAgainButton); hide(resumeButton); } function onEnablingAudio() { disable(recordButton); disable(audioOnRadioPair); disable(audioOffRadioPair); } function onDisablingAudio() { disable(recordButton); disable(audioOnRadioPair); disable(audioOffRadioPair); } function recordAgain() { disable(recordAgainButton); container.beginWaiting(); container.recordAgain(); } function onStartingOver() { show(submitButton); } function submit() { container.submit(); } function record(params) { disable(recordButton); container.record(params); } function initEvents() { debug('Buttons: initEvents()'); self.on(_events2.default.USER_MEDIA_READY, function (options) { onUserMediaReady(options); }).on(_events2.default.PREVIEW, function () { onPreview(); }).on(_events2.default.PAUSED, function () { self.adjustButtonsForPause(); }).on(_events2.default.RECORDING, function (framesCount) { onRecording(framesCount); }).on(_events2.default.FIRST_FRAME_SENT, function () { onFirstFrameSent(); }).on(_events2.default.RESUMING, function () { onResuming(); }).on(_events2.default.STOPPING, function () { onStopping(); }).on(_events2.default.COUNTDOWN, function () { onCountdown(); }).on(_events2.default.SUBMITTING, function () { onSubmitting(); }).on(_events2.default.RESETTING, function () { onResetting(); }).on(_events2.default.INVALID, function () { onInvalid(); }).on(_events2.default.VALID, function () { onValid(); }).on(_events2.default.SUBMITTED, function () { onSubmitted(); }).on(_events2.default.HIDE, function () { onHidden(); }).on(_events2.default.FORM_READY, function (options) { onFormReady(options); }).on(_events2.default.REPLAY_SHOWN, function () { onReplayShown(); }).on(_events2.default.GOING_BACK, function () { onGoingBack(); }).on(_events2.default.ENABLING_AUDIO, function () { onEnablingAudio(); }).on(_events2.default.DISABLING_AUDIO, function () { onDisablingAudio(); }).on(_events2.default.STARTING_OVER, function () { onStartingOver(); }).on(_events2.default.ERROR, function (err) { // since https://github.com/binarykitchen/videomail-client/issues/60 // we hide areas to make it easier for the user if (err.hideButtons && err.hideButtons() && options.adjustFormOnBrowserError) { self.hide(); } }); } this.reset = function () { options.debug('Buttons: reset()'); disable(pauseButton); disable(resumeButton); disable(recordButton); disable(previewButton); disable(recordAgainButton); }; this.isRecordAgainButtonEnabled = function () { return !recordAgainButton.disabled; }; this.isRecordButtonEnabled = function () { return !recordButton.disabled; }; this.setSubmitButton = function (newSubmitButton) { submitButton = newSubmitButton; }; this.getSubmitButton = function () { return submitButton; }; this.build = function () { buttonsElement = container.querySelector('.' + options.selectors.buttonsClass); if (!buttonsElement) { buttonsElement = (0, _hyperscript2.default)('div.' + options.selectors.buttonsClass); container.appendChild(buttonsElement); } buildButtons(); !built && initEvents(); built = true; }; this.unload = function () { built = false; }; this.hide = function (params) { hide(buttonsElement); if (params && params.deep) { hide(recordButton); hide(pauseButton); hide(resumeButton); hide(previewButton); hide(recordAgainButton); hide(submitButton); } }; this.show = function () { show(buttonsElement); }; this.isCountingDown = function () { return container.isCountingDown(); }; }; _util2.default.inherits(Buttons, _eventEmitter2.default); exports.default = Buttons; },{"./../events":88,"./../util/eventEmitter":95,"contains":13,"hidden":32,"hyperscript":34,"util":80}],102:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _insertCss = _dereq_('insert-css'); var _insertCss2 = _interopRequireDefault(_insertCss); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _documentVisibility = _dereq_('document-visibility'); var _documentVisibility2 = _interopRequireDefault(_documentVisibility); var _dimension = _dereq_('./dimension'); var _dimension2 = _interopRequireDefault(_dimension); var _visuals = _dereq_('./visuals'); var _visuals2 = _interopRequireDefault(_visuals); var _buttons = _dereq_('./buttons'); var _buttons2 = _interopRequireDefault(_buttons); var _form = _dereq_('./form'); var _form2 = _interopRequireDefault(_form); var _optionsWrapper = _dereq_('./optionsWrapper'); var _optionsWrapper2 = _interopRequireDefault(_optionsWrapper); var _resource = _dereq_('./../resource'); var _resource2 = _interopRequireDefault(_resource); var _events = _dereq_('./../events'); var _events2 = _interopRequireDefault(_events); var _eventEmitter = _dereq_('./../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _videomailError = _dereq_('./../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); var _mainMinCss = _dereq_('./../styles/css/main.min.css.js'); var _mainMinCss2 = _interopRequireDefault(_mainMinCss); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Container = function Container(options) { _eventEmitter2.default.call(this, options, 'Container'); var self = this; var visibility = (0, _documentVisibility2.default)(); var visuals = new _visuals2.default(this, options); var buttons = new _buttons2.default(this, options); var resource = new _resource2.default(options); var htmlElement = document && document.querySelector && document.querySelector('html'); var debug = options.debug; var hasError = false; var submitted = false; var lastValidation = false; var containerElement; var built; var form; function prependDefaultCss() { (0, _insertCss2.default)(_mainMinCss2.default, { prepend: true }); } // since https://github.com/binarykitchen/videomail-client/issues/87 function findParentFormElement() { return containerElement.closest('form'); } function getFormElement() { var formElement; if (containerElement.tagName === 'FORM') { formElement = containerElement; } else if (options.selectors.formId) { formElement = document.getElementById(options.selectors.formId); } else { formElement = findParentFormElement(); } return formElement; } function buildForm() { var formElement = getFormElement(); if (formElement) { debug('Container: buildForm()'); form = new _form2.default(self, formElement, options); var submitButton = form.findSubmitButton(); submitButton && buttons.setSubmitButton(submitButton); form.build(); } } function buildChildren() { debug('Container: buildChildren()'); if (!containerElement.classList) { self.emit(_events2.default.ERROR, _videomailError2.default.create('Sorry, your browser is too old!', options)); } else { containerElement.classList.add('videomail'); if (!options.playerOnly) { buttons.build(); } visuals.build(); } } function processError(err) { hasError = true; if (err.stack) { options.logger.error(err.stack); } else { options.logger.error(err); } if (options.displayErrors) { visuals.error(err); } else { visuals.reset(); } } function initEvents() { debug('Container: initEvents()'); window.addEventListener('beforeunload', function (e) { self.unload(e); }); if (!options.playerOnly) { visibility.onChange(function (visible) { // built? see https://github.com/binarykitchen/videomail.io/issues/326 if (built) { if (visible) { if (options.isAutoPauseEnabled() && self.isCountingDown()) { self.resume(); } self.emit(_events2.default.VISIBLE); } else { if (options.isAutoPauseEnabled() && (self.isCountingDown() || self.isRecording())) { self.pause('document invisible'); } self.emit(_events2.default.INVISIBLE); } } }); } if (options.enableSpace) { if (!options.playerOnly) { window.addEventListener('keypress', function (e) { var tagName = e.target.tagName; var isEditable = e.target.isContentEditable || e.target.contentEditable === 'true' || e.target.contentEditable === true; // beware of rich text editors, hence the isEditable check (wordpress plugin issue) if (!isEditable && tagName !== 'INPUT' && tagName !== 'TEXTAREA') { var code = e.keyCode ? e.keyCode : e.which; if (code === 32) { e.preventDefault(); if (options.enablePause) { visuals.pauseOrResume(); } else { visuals.recordOrStop(); } } } }); } } // better to keep the one and only error listeners // at one spot, here, because unload() will do a removeAllListeners() self.on(_events2.default.ERROR, function (err) { processError(err); unloadChildren(err); if (err.removeDimensions && err.removeDimensions()) { removeDimensions(); } }); if (!options.playerOnly) { self.on(_events2.default.LOADED_META_DATA, function () { correctDimensions(); }); } } function validateOptions() { if (options.hasDefinedWidth() && options.video.width % 2 !== 0) { throw _videomailError2.default.create('Width must be divisible by two.', options); } if (options.hasDefinedHeight() && options.video.height % 2 !== 0) { throw _videomailError2.default.create('Height must be divisible by two.', options); } } // this will just set the width but not the height because // it can be a form with more inputs elements function correctDimensions() { var width = visuals.getRecorderWidth(true); if (width < 1) { throw _videomailError2.default.create('Recorder width cannot be less than 1!', options); } else { containerElement.style.width = width + 'px'; } } function removeDimensions() { containerElement.style.width = 'auto'; } function unloadChildren(e) { visuals.unload(e); buttons.unload(); self.endWaiting(); } function hideMySelf() { (0, _hidden2.default)(containerElement, true); } // fixes https://github.com/binarykitchen/videomail-client/issues/71 function trimEmail(email) { return email.replace(/(^[,\s]+)|([,\s]+$)/g, ''); } function submitVideomail(formData, method, cb) { var FORM_FIELDS = { 'subject': options.selectors.subjectInputName, 'from': options.selectors.fromInputName, 'to': options.selectors.toInputName, 'body': options.selectors.bodyInputName, 'key': options.selectors.keyInputName, 'parentKey': options.selectors.parentKeyInputName, 'sendCopy': options.selectors.sendCopyInputName }; var videomailFormData = {}; Object.keys(FORM_FIELDS).forEach(function (key) { if (formData.hasOwnProperty(FORM_FIELDS[key])) { videomailFormData[key] = formData[FORM_FIELDS[key]]; } }); if (videomailFormData.from) { videomailFormData.from = trimEmail(videomailFormData.from); } if (videomailFormData.to) { videomailFormData.to = trimEmail(videomailFormData.to); } // when method is undefined, treat it as a post if (isPost(method) || !method) { videomailFormData.recordingStats = visuals.getRecordingStats(); videomailFormData.width = visuals.getRecorderWidth(true); videomailFormData.height = visuals.getRecorderHeight(true); resource.post(videomailFormData, cb); } else if (isPut(method)) { resource.put(videomailFormData, cb); } } function submitForm(formData, videomailResponse, url, cb) { // for now, accept POSTs only which have an URL unlike null and // treat all other submissions as direct submissions if (!url || url === '') { // figure out URL automatically then url = document.baseURI; } // can be missing when no videomail was recorded and is not required if (videomailResponse) { formData[options.selectors.aliasInputName] = videomailResponse.videomail.alias; } resource.form(formData, url, cb); } function finalizeSubmissions(err, method, videomail, response, formResponse) { self.endWaiting(); if (err) { self.emit(_events2.default.ERROR, err); } else { submitted = true; // merge two json response bodies to fake as if it were only one request if (response && formResponse && formResponse.body) { Object.keys(formResponse.body).forEach(function (key) { response[key] = formResponse.body[key]; }); } self.emit(_events2.default.SUBMITTED, videomail, response || formResponse); if (formResponse && formResponse.type === 'text/html' && formResponse.text) { // server replied with HTML contents - display these document.body.innerHTML = formResponse.text; // todo: figure out how to fire dom's onload event again // todo: or how to run all the scripts over again } } } this.addPlayerDimensions = function (videomail, element) { try { videomail.playerHeight = this.calculateHeight({ responsive: true, videoWidth: videomail.width, ratio: videomail.height / videomail.width }, element); videomail.playerWidth = this.calculateWidth({ responsive: true, videoHeight: videomail.playerHeight, ratio: videomail.height / videomail.width }); return videomail; } catch (exc) { self.emit(_events2.default.ERROR, exc); } }; this.limitWidth = function (width) { return _dimension2.default.limitWidth(containerElement, width, options); }; this.limitHeight = function (height) { return _dimension2.default.limitHeight(height, options); }; this.calculateWidth = function (fnOptions) { return _dimension2.default.calculateWidth(_optionsWrapper2.default.merge(options, fnOptions, true)); }; this.calculateHeight = function (fnOptions, element) { if (!element) { if (containerElement) { element = containerElement; } else { // better than nothing element = document.body; } } return _dimension2.default.calculateHeight(element, _optionsWrapper2.default.merge(options, fnOptions, true)); }; this.areVisualsHidden = function () { return visuals.isHidden(); }; this.hasElement = function () { return !!containerElement; }; this.build = function () { try { containerElement = document.getElementById(options.selectors.containerId); // only build when a container element hast been found, otherwise // be silent and do nothing if (containerElement) { options.insertCss && prependDefaultCss(); !built && initEvents(); validateOptions(); correctDimensions(); if (!options.playerOnly) { buildForm(); } buildChildren(); if (!hasError) { debug('Container: built.'); built = true; self.emit(_events2.default.BUILT); } else { debug('Container: building failed due to an error.'); } } else { // commented out since it does too much noise on videomail's view page which is fine // debug('Container: no container element with ID ' + options.selectors.containerId + ' found. Do nothing.') } } catch (exc) { if (visuals.isNotifierBuilt()) { self.emit(_events2.default.ERROR, exc); } else { throw exc; } } }; this.getSubmitButton = function () { return buttons.getSubmitButton(); }; this.querySelector = function (selector) { return containerElement.querySelector(selector); }; this.beginWaiting = function () { htmlElement.classList && htmlElement.classList.add('wait'); }; this.endWaiting = function () { htmlElement.classList && htmlElement.classList.remove('wait'); }; this.appendChild = function (child) { containerElement.appendChild(child); }; this.insertBefore = function (child, reference) { containerElement.insertBefore(child, reference); }; this.unload = function (e) { debug('Container: unload()', e); try { unloadChildren(e); this.removeAllListeners(); built = submitted = false; } catch (exc) { self.emit(_events2.default.ERROR, exc); } }; this.show = function () { if (containerElement) { (0, _hidden2.default)(containerElement, false); visuals.show(); if (!hasError) { var paused = self.isPaused(); if (paused) { buttons.adjustButtonsForPause(); } // since https://github.com/binarykitchen/videomail-client/issues/60 // we hide areas to make it easier for the user buttons.show(); if (self.isReplayShown()) { self.emit(_events2.default.PREVIEW); } else { self.emit(_events2.default.FORM_READY, { paused: paused }); } } } }; this.hide = function () { debug('Container: hide()'); hasError = false; this.isRecording() && this.pause(); visuals.hide(); if (submitted) { buttons.hide(); hideMySelf(); } }; this.startOver = function (params) { try { self.emit(_events2.default.STARTING_OVER); submitted = false; form.show(); visuals.back(params, function () { if (params.keepHidden) { // just enable form, do nothing else. // see example contact_form.html when you submit without videomil // and go back self.enableForm(); } else { self.show(params); } }); } catch (exc) { self.emit(_events2.default.ERROR, exc); } }; this.showReplayOnly = function () { hasError = false; this.isRecording() && this.pause(); visuals.showReplayOnly(); submitted && buttons.hide(); }; this.isNotifying = function () { return visuals.isNotifying(); }; this.isPaused = function () { return visuals.isPaused(); }; this.pause = function (params) { visuals.pause(params); }; // this code needs a good rewrite :( this.validate = function (force) { var runValidation = true; var valid; if (!options.enableAutoValidation) { runValidation = false; lastValidation = true; // needed so that it can be submitted anyway, see submit() } else if (force) { runValidation = force; } else if (self.isNotifying()) { runValidation = false; } else if (visuals.isConnected()) { runValidation = visuals.isUserMediaLoaded() || visuals.isReplayShown(); } else if (visuals.isConnecting()) { runValidation = false; } if (runValidation) { this.emit(_events2.default.VALIDATING); var visualsValid = visuals.validate() && buttons.isRecordAgainButtonEnabled(); var whyInvalid; if (form) { valid = form.validate(); if (valid) { if (!this.areVisualsHidden() && !visualsValid) { if (submitted || this.isReady() || this.isRecording() || this.isPaused() || this.isCountingDown()) { valid = false; } if (!valid) { whyInvalid = 'Video is not recorded'; } } } else { var invalidInput = form.getInvalidElement(); if (invalidInput) { whyInvalid = 'Form input named ' + invalidInput.name + ' is invalid'; } else { whyInvalid = 'Form input(s() are invalid'; } } } else { valid = visualsValid; } if (valid) { this.emit(_events2.default.VALID); } else { this.emit(_events2.default.INVALID, whyInvalid); } lastValidation = valid; } return valid; }; this.disableForm = function (buttonsToo) { form && form.disable(buttonsToo); }; this.enableForm = function (buttonsToo) { form && form.enable(buttonsToo); }; this.hasForm = function () { return !!form; }; this.isReady = function () { return buttons.isRecordButtonEnabled(); }; function isPost(method) { return method && method.toUpperCase() === 'POST'; } function isPut(method) { return method && method.toUpperCase() === 'PUT'; } this.submitAll = function (formData, method, url) { var post = isPost(method); var hasVideomailKey = !!formData[options.selectors.keyInputName]; function startSubmission() { self.beginWaiting(); self.disableForm(true); self.emit(_events2.default.SUBMITTING); } // a closure so that we can access method var submitVideomailCallback = function submitVideomailCallback(err1, videomail, videomailResponse) { if (err1) { finalizeSubmissions(err1, method, videomail, videomailResponse); } else if (post) { submitForm(formData, videomailResponse, url, function (err2, formResponse) { finalizeSubmissions(err2, method, videomail, videomailResponse, formResponse); }); } else { // it's a direct submission finalizeSubmissions(null, method, videomail, videomailResponse); } }; // !hasVideomailKey makes it possible to submit form when videomail itself // is not optional. if (!hasVideomailKey) { if (options.enableAutoSubmission) { startSubmission(); submitForm(formData, null, url, function (err2, formResponse) { finalizeSubmissions(err2, method, null, null, formResponse); }); } // ... and when the enableAutoSubmission option is false, // then that can mean, leave it to the framework to process with the form // validation/handling/submission itself. for example the ninja form // will want to highlight which one input are wrong. } else { startSubmission(); submitVideomail(formData, method, submitVideomailCallback); } }; this.isBuilt = function () { return built; }; this.isReplayShown = function () { return visuals.isReplayShown(); }; this.isDirty = function () { var isDirty = false; if (form) { if (visuals.isRecorderUnloaded()) { isDirty = false; } else if (this.isReplayShown() || this.isPaused()) { isDirty = true; } } return isDirty; }; this.getReplay = function () { return visuals.getReplay(); }; this.isOutsideElementOf = function (element) { return element.parentNode !== containerElement && element !== containerElement; }; this.hideForm = function (params) { // form check needed, see https://github.com/binarykitchen/videomail-client/issues/127 form && form.hide(); buttons && buttons.hide(params); }; this.loadForm = function (videomail) { if (form) { form.loadVideomail(videomail); this.validate(); } }; this.enableAudio = function () { options.setAudioEnabled(true); this.emit(_events2.default.ENABLING_AUDIO); }; this.disableAudio = function () { options.setAudioEnabled(false); this.emit(_events2.default.DISABLING_AUDIO); }; this.submit = function () { lastValidation && form && form.doTheSubmit(); }; this.isCountingDown = visuals.isCountingDown.bind(visuals); this.isRecording = visuals.isRecording.bind(visuals); this.record = visuals.record.bind(visuals); this.resume = visuals.resume.bind(visuals); this.stop = visuals.stop.bind(visuals); this.recordAgain = visuals.recordAgain.bind(visuals); }; _util2.default.inherits(Container, _eventEmitter2.default); exports.default = Container; },{"./../events":88,"./../resource":90,"./../styles/css/main.min.css.js":91,"./../util/eventEmitter":95,"./../util/videomailError":100,"./buttons":101,"./dimension":103,"./form":104,"./optionsWrapper":105,"./visuals":106,"document-visibility":19,"hidden":32,"insert-css":38,"util":80}],103:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _numberIsInteger = _dereq_('number-is-integer'); var _numberIsInteger2 = _interopRequireDefault(_numberIsInteger); var _videomailError = _dereq_('./../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getOuterWidth(element) { var outerWidth = 0; var rect = element.getBoundingClientRect(); if (rect) { outerWidth = rect.right - rect.left; } if (outerWidth < 1) { // last effort, can happen when replaying only rect = document.body.getBoundingClientRect(); outerWidth = rect.right - rect.left; } return outerWidth; } function figureMinHeight(height, options) { if (options.hasDefinedHeight()) { if (!height) { height = options.video.height; } else { height = Math.min(options.video.height, height); } } if ((0, _numberIsInteger2.default)(height) && height < 1) { throw _videomailError2.default.create('Got a video height less than 1 (' + height + ') while figuring out the minimum!', options); } // just return it, can be "auto" return height; } exports.default = { limitWidth: function limitWidth(element, width, options) { var limitedWidth; var outerWidth = getOuterWidth(element); if (width) { // only when that element has a defined width, apply this logic limitedWidth = outerWidth > 0 && outerWidth < width ? outerWidth : width; } else { // else apply the outer width when the element has no defined width yet limitedWidth = outerWidth; } if ((0, _numberIsInteger2.default)(limitedWidth) && limitedWidth < 1) { throw _videomailError2.default.create('Limited width cannot be less than 1!', options); } else { return limitedWidth; } }, // this is difficult to compute and is not entirely correct. // but good enough for now to ensure some stability. limitHeight: function limitHeight(height, options) { if ((0, _numberIsInteger2.default)(height) && height < 1) { throw _videomailError2.default.create('Passed limit-height argument cannot be less than 1!', options); } else { var limitedHeight = Math.min(height, // document.body.scrollHeight, document.documentElement.clientHeight); if (limitedHeight < 1) { throw _videomailError2.default.create('Limited height cannot be less than 1!', options); } else { return limitedHeight; } } }, calculateWidth: function calculateWidth(options) { var height = options.videoHeight || null; var ratio = options.ratio || options.getRatio(); height = figureMinHeight(height, options); if (options.responsive) { height = this.limitHeight(height, options); } if ((0, _numberIsInteger2.default)(height) && height < 1) { throw _videomailError2.default.create('Height cannot be smaller than 1 when calculating width.', options); } else { var calculatedWidth = parseInt(height / ratio); if (calculatedWidth < 1) { throw _videomailError2.default.create('Calculated width cannot be smaller than 1!', options); } else { return calculatedWidth; } } }, calculateHeight: function calculateHeight(element, options) { var width = options.videoWidth || null; var height; var ratio = options.ratio || options.getRatio(); if (options.hasDefinedWidth()) { width = options.video.width; } if ((0, _numberIsInteger2.default)(width) && width < 1) { throw _videomailError2.default.create('Unable to calculate height when width is less than 1.', options); } else if (options.responsive) { width = this.limitWidth(element, width, options); } if (width) { height = parseInt(width * ratio); } if ((0, _numberIsInteger2.default)(height) && height < 1) { throw _videomailError2.default.create('Just calculated a height less than 1 which is wrong.', options); } else { return figureMinHeight(height, options); } } }; },{"./../util/videomailError":100,"number-is-integer":47}],104:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _getFormData = _dereq_('get-form-data'); var _getFormData2 = _interopRequireDefault(_getFormData); var _events = _dereq_('./../events'); var _events2 = _interopRequireDefault(_events); var _eventEmitter = _dereq_('./../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _videomailError = _dereq_('./../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Form = function Form(container, formElement, options) { _eventEmitter2.default.call(this, options, 'Form'); var self = this; var disableContainerValidation; var keyInput; function getData() { return (0, _getFormData2.default)(formElement); } this.loadVideomail = function (videomail) { var limit = formElement.elements.length; var input; var name; for (var i = 0; i < limit; i++) { input = formElement.elements[i]; name = input.name; if (videomail[name]) { input.value = videomail[name]; } if (name === options.selectors.subjectInputName || name === options.selectors.bodyInputName) { input.disabled = true; } } formElement.setAttribute('method', 'put'); }; function isNotButton(element) { return element.tagName !== 'BUTTON' && element.type !== 'submit'; } function setDisabled(disabled, buttonsToo) { var limit = formElement.elements.length; for (var i = 0; i < limit; i++) { if (buttonsToo || !buttonsToo && isNotButton(formElement.elements[i])) { formElement.elements[i].disabled = disabled; } } } function hideAll() { var limit = formElement.elements.length; for (var i = 0; i < limit; i++) { (0, _hidden2.default)(formElement.elements[i], true); } (0, _hidden2.default)(formElement, true); } function getInputElements() { return formElement.querySelectorAll('input, textarea'); } function getSelectElements() { return formElement.querySelectorAll('select'); } this.disable = function (buttonsToo) { setDisabled(true, buttonsToo); }; this.enable = function (buttonsToo) { setDisabled(false, buttonsToo); }; this.build = function () { if (options.enableAutoValidation) { var inputElements = getInputElements(); var inputElement; for (var i = 0, len = inputElements.length; i < len; i++) { inputElement = inputElements[i]; if (inputElement.type === 'radio') { inputElement.addEventListener('change', function () { container.validate(); }); } else { inputElement.addEventListener('input', function () { container.validate(); }); } // because of angular's digest cycle, validate again when it became invalid inputElement.addEventListener('invalid', function () { if (!disableContainerValidation) { container.validate(); } }); } var selectElements = getSelectElements(); for (var j = 0, len2 = selectElements.length; j < len2; j++) { selectElements[j].addEventListener('change', function () { container.validate(); }); } } keyInput = formElement.querySelector('input[name="' + options.selectors.keyInputName + '"]'); if (!keyInput) { keyInput = (0, _hyperscript2.default)('input', { name: options.selectors.keyInputName, type: 'hidden' }); formElement.appendChild(keyInput); } this.on(_events2.default.PREVIEW, function (videomailKey) { // beware that preview doesn't always come with a key, i.E. // container.show() can emit PREVIEW without a key when a replay already exists // (can happen when showing - hiding - showing videomail over again) // only emit error if key is missing AND the input has no key (value) yet if (!videomailKey && !keyInput.value) { self.emit(_events2.default.ERROR, _videomailError2.default.create('Videomail key for preview is missing!', options)); } else if (videomailKey) { keyInput.value = videomailKey; } // else // leave as it and use existing keyInput.value }); // fixes https://github.com/binarykitchen/videomail-client/issues/91 this.on(_events2.default.GOING_BACK, function () { keyInput.value = null; }); this.on(_events2.default.ERROR, function (err) { // since https://github.com/binarykitchen/videomail-client/issues/60 // we hide areas to make it easier for the user to process an error // (= less distractions) if (err.hideForm && err.hideForm() && options.adjustFormOnBrowserError) { hideAll(); } else if (err.hideButtons && err.hideButtons() && options.adjustFormOnBrowserError) { hideSubmitButton(); } }); this.on(_events2.default.BUILT, function () { startListeningToSubmitEvents(); }); }; function hideSubmitButton() { var submitButton = self.findSubmitButton(); (0, _hidden2.default)(submitButton, true); } function startListeningToSubmitEvents() { var submitButton = container.getSubmitButton(); submitButton.addEventListener('click', self.doTheSubmit.bind(self)); } this.doTheSubmit = function (e) { if (e) { e.preventDefault(); } // only submit when there is a container, // otherwise do nothing and leave as it if (container.hasElement()) { container.submitAll(getData(), formElement.getAttribute('method'), formElement.getAttribute('action')); } return false; // important to stop submission }; this.getInvalidElement = function () { var inputElements = getInputElements(); for (var i = 0, len = inputElements.length; i < len; i++) { if (!inputElements[i].validity.valid) { return inputElements[i]; } } var selectElements = getSelectElements(); for (var j = 0, len2 = selectElements.length; j < len2; j++) { if (!selectElements[i].validity.valid) { return selectElements[j]; } } return null; }; this.validate = function () { // prevents endless validation loop disableContainerValidation = true; var formIsValid = formElement.checkValidity(); disableContainerValidation = false; return formIsValid; }; this.findSubmitButton = function () { return formElement.querySelector("[type='submit']"); }; this.hide = function () { formElement && (0, _hidden2.default)(formElement, true); }; this.show = function () { formElement && (0, _hidden2.default)(formElement, false); }; }; _util2.default.inherits(Form, _eventEmitter2.default); exports.default = Form; },{"./../events":88,"./../util/eventEmitter":95,"./../util/videomailError":100,"get-form-data":27,"hidden":32,"hyperscript":34,"util":80}],105:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _deepmerge = _dereq_('deepmerge'); var _deepmerge2 = _interopRequireDefault(_deepmerge); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { addFunctions: function addFunctions(options) { var audioEnabled = options.audio && options.audio.enabled; options.hasDefinedHeight = function () { return this.video.height && this.video.height !== 'auto'; }; options.hasDefinedWidth = function () { return this.video.width && this.video.width !== 'auto'; }; options.hasDefinedDimension = function () { return this.hasDefinedWidth() || this.hasDefinedHeight(); }; options.hasDefinedDimensions = function () { return this.hasDefinedWidth() && this.hasDefinedHeight(); }; options.getRatio = function () { var ratio = 1; // just a default one when no computations are possible // todo fix this, it's not really an option var hasVideoDimensions = this.videoHeight && this.videoWidth; if (this.hasDefinedDimensions()) { if (hasVideoDimensions) { // figure out first which one to pick if (this.videoHeight < this.video.height || this.videoWidth < this.video.width) { ratio = this.videoHeight / this.videoWidth; } else { ratio = this.video.height / this.video.width; } } else { ratio = this.video.height / this.video.width; } } else if (hasVideoDimensions) { ratio = this.videoHeight / this.videoWidth; } return ratio; }; options.isAudioEnabled = function () { return audioEnabled; }; options.setAudioEnabled = function (enabled) { audioEnabled = enabled; }; options.isAutoPauseEnabled = function () { return this.enableAutoPause && this.enablePause; }; }, // not very elegant but works! and if you here are reading this, and // start to doubt, rest assured, it's solid and run thousand times over // and over again each day. and other large sites out there have their own // tech debts. hope i have shattered your illusion on perfection? merge: function merge(defaultOptions, newOptions) { var options = (0, _deepmerge2.default)(defaultOptions, newOptions, { arrayMerge: function arrayMerge(destination, source) { return source; } }); this.addFunctions(options); return options; } }; // enhances options with useful functions we can reuse everywhere },{"deepmerge":16}],106:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _replay = _dereq_('./visuals/replay'); var _replay2 = _interopRequireDefault(_replay); var _recorder = _dereq_('./visuals/recorder'); var _recorder2 = _interopRequireDefault(_recorder); var _notifier = _dereq_('./visuals/notifier'); var _notifier2 = _interopRequireDefault(_notifier); var _recorderInsides = _dereq_('./visuals/inside/recorderInsides'); var _recorderInsides2 = _interopRequireDefault(_recorderInsides); var _eventEmitter = _dereq_('./../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _events = _dereq_('./../events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Visuals = function Visuals(container, options) { _eventEmitter2.default.call(this, options, 'Visuals'); var self = this; // can be overwritten with setter fn var replay = new _replay2.default(this, options); var recorder = new _recorder2.default(this, replay, options); var recorderInsides = new _recorderInsides2.default(this, options); var notifier = new _notifier2.default(this, options); var debug = options.debug; var visualsElement; var built; function buildNoScriptTag() { var noScriptElement = container.querySelector('noscript'); if (!noScriptElement) { noScriptElement = (0, _hyperscript2.default)('noscript'); noScriptElement.innerHTML = 'Please enable Javascript'; visualsElement.appendChild(noScriptElement); } } function buildChildren() { debug('Visuals: buildChildren()'); buildNoScriptTag(); if (!options.playerOnly) { notifier.build(); recorderInsides.build(); } replay.build(); debug('Visuals: built.'); } function initEvents() { if (!options.playerOnly) { debug('Visuals: initEvents()'); self.on(_events2.default.USER_MEDIA_READY, function () { built = true; self.endWaiting(); container.enableForm(false); }).on(_events2.default.PREVIEW, function () { self.endWaiting(); }).on(_events2.default.BLOCKING, function (blockingOptions) { if (!blockingOptions.hideForm && !options.adjustFormOnBrowserError) { // do nothing, user still can enter form inputs // can be useful when you are on i.E. seeflow's contact page and // still want to tick off the webcam option } else { container.disableForm(true); } }).on(_events2.default.PREVIEW_SHOWN, function () { container.validate(true); }).on(_events2.default.LOADED_META_DATA, function () { correctDimensions(); }).on(_events2.default.ERROR, function (err) { if (err.removeDimensions && err.removeDimensions()) { removeDimensions(); } }); } } function correctDimensions() { visualsElement.style.width = self.getRecorderWidth(true) + 'px'; visualsElement.style.height = self.getRecorderHeight(true) + 'px'; } function removeDimensions() { visualsElement.style.width = 'auto'; visualsElement.style.height = 'auto'; } this.getRatio = function () { if (visualsElement.clientWidth) { // special case for safari, see getRatio() in recorder return visualsElement.clientHeight / visualsElement.clientWidth; } else { return 0; } }; function isRecordable() { return !self.isNotifying() && !replay.isShown() && !self.isCountingDown(); } this.isCountingDown = function () { return recorderInsides.isCountingDown(); }; this.build = function () { visualsElement = container.querySelector('.' + options.selectors.visualsClass); if (!visualsElement) { visualsElement = (0, _hyperscript2.default)('div.' + options.selectors.visualsClass); var buttonsElement = container.querySelector('.' + options.selectors.buttonsClass); // make sure it's placed before the buttons, but only if it's a child // element of the container = inside the container if (buttonsElement && !container.isOutsideElementOf(buttonsElement)) { container.insertBefore(visualsElement, buttonsElement); } else { container.appendChild(visualsElement); } } // do not hide visuals element so that apps can give it a predefined // width or height through css but hide all children visualsElement.classList.add('visuals'); correctDimensions(); !built && initEvents(); buildChildren(); // needed for replay handling and container.isOutsideElementOf() self.parentNode = visualsElement.parentNode; built = true; }; this.querySelector = function (selector) { return visualsElement && visualsElement.querySelector(selector); }; this.appendChild = function (child) { visualsElement && visualsElement.appendChild(child); }; this.removeChild = function (child) { visualsElement.removeChild(child); }; this.reset = function () { this.endWaiting(); recorder.reset(); }; this.beginWaiting = function () { container.beginWaiting(); }; this.endWaiting = function () { container.endWaiting(); }; this.stop = function (params) { recorder.stop(params); recorderInsides.hidePause(); }; this.back = function (params, cb) { if (!cb && params) { cb = params; params = {}; } replay.hide(); notifier.hide(); if (params.keepHidden) { recorder.hide(); cb && cb(); } else { recorder.back(cb); } }; this.recordAgain = function () { this.back(function () { self.once(_events2.default.USER_MEDIA_READY, function () { self.record(); }); }); }; this.unload = function (e) { try { recorder.unload(e); recorderInsides.unload(e); replay.unload(e); built = false; } catch (exc) { this.emit(_events2.default.ERROR, exc); } }; this.isNotifying = function () { return notifier.isVisible(); }; this.isReplayShown = function () { return replay.isShown(); }; this.pause = function (params) { recorder.pause(params); recorderInsides.showPause(); }; this.resume = function () { if (recorderInsides.isCountingDown()) { recorderInsides.resumeCountdown(); } else { recorder.resume(); } recorderInsides.hidePause(); }; this.pauseOrResume = function () { if (isRecordable.call(this)) { if (this.isRecording()) { this.pause(); } else if (recorder.isPaused()) { this.resume(); } else if (recorder.isReady()) { this.record(); } } }; this.recordOrStop = function () { if (isRecordable()) { if (this.isRecording()) { this.stop(); } else if (recorder.isReady()) { this.record(); } } }; this.record = function () { if (options.video.countdown) { this.emit(_events2.default.COUNTDOWN); recorderInsides.startCountdown(recorder.record.bind(recorder)); } else { recorder.record(); } }; this.getRecorder = function () { return recorder; }; this.getReplay = function () { return replay; }; this.validate = function () { return recorder.validate() && this.isReplayShown(); }; this.getRecordingStats = function () { return recorder.getRecordingStats(); }; this.getAudioSampleRate = function () { return recorder.getAudioSampleRate(); }; this.isPaused = function () { return recorder.isPaused(); }; this.error = function (err) { notifier.error(err); }; this.hide = function () { if (visualsElement) { (0, _hidden2.default)(visualsElement, true); this.emit(_events2.default.HIDE); } }; this.isHidden = function () { if (!built) { return true; } else if (visualsElement) { return (0, _hidden2.default)(visualsElement); } }; this.showVisuals = function () { visualsElement && (0, _hidden2.default)(visualsElement, false); }; this.show = function () { !this.isReplayShown() && visualsElement && recorder.build(); this.showVisuals(); }; this.showReplayOnly = function () { !this.isReplayShown() && replay.show(); this.show(); recorder.hide(); notifier.hide(); }; this.isRecorderUnloaded = function () { return recorder.isUnloaded(); }; this.isConnecting = function () { return recorder.isConnecting(); }; this.getRecorderWidth = function (responsive) { return recorder.getRecorderWidth(responsive); }; this.getRecorderHeight = function (responsive) { return recorder.getRecorderHeight(responsive); }; this.limitWidth = function (width) { return container.limitWidth(width, options); }; this.limitHeight = function (height) { return container.limitHeight(height); }; this.calculateWidth = function (options) { return container.calculateWidth(options); }; this.calculateHeight = function (options) { return container.calculateHeight(options); }; this.getReplay = function () { return replay; }; this.getBoundingClientRect = function () { // fixes https://github.com/binarykitchen/videomail-client/issues/126 return visualsElement && visualsElement.getBoundingClientRect(); }; this.checkTimer = function (intervalSum) { recorderInsides.checkTimer(intervalSum); }; this.isNotifierBuilt = function () { return notifier && notifier.isBuilt(); }; this.isReplayShown = replay.isShown.bind(replay); this.hideReplay = replay.hide.bind(replay); this.hideRecorder = recorder.hide.bind(recorder); this.isRecording = recorder.isRecording.bind(recorder); this.isUserMediaLoaded = recorder.isUserMediaLoaded.bind(recorder); this.isConnected = recorder.isConnected.bind(recorder); }; _util2.default.inherits(Visuals, _eventEmitter2.default); exports.default = Visuals; },{"./../events":88,"./../util/eventEmitter":95,"./visuals/inside/recorderInsides":111,"./visuals/notifier":112,"./visuals/recorder":113,"./visuals/replay":114,"hidden":32,"hyperscript":34,"util":80}],107:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (visuals, options) { var self = this; var countdownElement; var intervalId; var countdown; var paused; function fire(cb) { self.unload(); self.hide(); // keep all callbacks async setTimeout(function () { cb(); }, 0); } function countBackward(cb) { if (!paused) { options.debug('Countdown', countdown); countdown--; if (countdown < 1) { fire(cb); } else { countdownElement.innerHTML = countdown; } } } this.start = function (cb) { countdownElement.innerHTML = countdown = options.video.countdown; this.show(); intervalId = setInterval(countBackward.bind(this, cb), 950); }; this.pause = function () { paused = true; }; this.resume = function () { paused = false; }; this.build = function () { countdownElement = visuals.querySelector('.countdown'); if (!countdownElement) { countdownElement = (0, _hyperscript2.default)('p.countdown'); this.hide(); visuals.appendChild(countdownElement); } else { this.hide(); } }; this.show = function () { (0, _hidden2.default)(countdownElement, false); }; this.isCountingDown = function () { return !!intervalId; }; this.unload = function () { clearInterval(intervalId); paused = false; intervalId = null; }; this.hide = function () { (0, _hidden2.default)(countdownElement, true); this.unload(); }; }; var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"hidden":32,"hyperscript":34}],108:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (visuals, options) { if (!options.text.pausedHeader) { throw _videomailError2.default.create('Paused header cannot be empty', options); } var pausedBlockElement; var pausedHeaderElement; var pausedHintElement; function hasPausedHint() { return options.text.pausedHint; } this.build = function () { pausedBlockElement = visuals.querySelector('.paused'); pausedHeaderElement = visuals.querySelector('.pausedHeader'); if (!pausedHeaderElement) { pausedBlockElement = (0, _hyperscript2.default)('div.paused'); pausedHeaderElement = (0, _hyperscript2.default)('p.pausedHeader'); this.hide(); pausedHeaderElement.innerHTML = options.text.pausedHeader; pausedBlockElement.appendChild(pausedHeaderElement); if (hasPausedHint()) { pausedHintElement = visuals.querySelector('.pausedHint'); pausedHintElement = (0, _hyperscript2.default)('p.pausedHint'); pausedHintElement.innerHTML = options.text.pausedHint; pausedBlockElement.appendChild(pausedHintElement); } visuals.appendChild(pausedBlockElement); } else { this.hide(); pausedHeaderElement.innerHTML = options.text.pausedHeader; if (hasPausedHint()) { pausedHintElement.innerHTML = options.text.pausedHint; } } }; this.hide = function () { (0, _hidden2.default)(pausedBlockElement, true); }; this.show = function () { (0, _hidden2.default)(pausedBlockElement, false); }; }; var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _videomailError = _dereq_('./../../../../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"./../../../../util/videomailError":100,"hidden":32,"hyperscript":34}],109:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (visuals) { var recordNoteElement; this.build = function () { recordNoteElement = visuals.querySelector('.recordNote'); if (!recordNoteElement) { recordNoteElement = (0, _hyperscript2.default)('p.recordNote'); this.hide(); visuals.appendChild(recordNoteElement); } else { this.hide(); } }; this.stop = function () { this.hide(); recordNoteElement.classList.remove('near'); recordNoteElement.classList.remove('nigh'); }; this.setNear = function () { recordNoteElement.classList.add('near'); }; this.setNigh = function () { recordNoteElement.classList.add('nigh'); }; this.hide = function () { (0, _hidden2.default)(recordNoteElement, true); }; this.show = function () { (0, _hidden2.default)(recordNoteElement, false); }; }; var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"hidden":32,"hyperscript":34}],110:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (visuals, recordNote, options) { var recordTimerElement; var nearComputed = false; var endNighComputed = false; var started; var countdown; function pad(n) { return n < 10 ? '0' + n : n; } function thresholdReached(secs, threshold) { return secs >= options.video.limitSeconds * threshold; } function isNear(secs) { if (!nearComputed && thresholdReached(secs, 0.6)) { nearComputed = true; return true; } else { return false; } } function endIsNigh(secs) { if (!endNighComputed && thresholdReached(secs, 0.8)) { endNighComputed = true; return true; } else { return false; } } function setNear() { recordTimerElement.classList.add('near'); } function setNigh() { recordTimerElement.classList.add('nigh'); } this.check = function (opts) { var newCountdown = getStartSeconds() - Math.floor(opts.intervalSum / 1e3); // performance optimisation (another reason we need react here!) if (newCountdown !== countdown) { countdown = newCountdown; update(); countdown < 1 && visuals.stop(true); } }; function update() { var mins = parseInt(countdown / 60, 10); var secs = countdown - mins * 60; if (!nearComputed || !endNighComputed) { var remainingSeconds = options.video.limitSeconds - countdown; if (isNear(remainingSeconds)) { recordNote.setNear(); setNear(); options.debug('End is near, ' + countdown + ' seconds to go'); } else if (endIsNigh(remainingSeconds)) { recordNote.setNigh(); setNigh(); options.debug('End is nigh, ' + countdown + ' seconds to go'); } } recordTimerElement.innerHTML = mins + ':' + pad(secs); } function hide() { (0, _hidden2.default)(recordTimerElement, true); } function show() { recordTimerElement.classList.remove('near'); recordTimerElement.classList.remove('nigh'); (0, _hidden2.default)(recordTimerElement, false); } function getSecondsRecorded() { return getStartSeconds() - countdown; } function getStartSeconds() { return options.video.limitSeconds; } this.start = function () { countdown = getStartSeconds(); nearComputed = endNighComputed = false; started = true; update(); show(); }; this.pause = function () { recordNote.hide(); }; this.resume = function () { recordNote.show(); }; function isStopped() { return countdown === null; } this.stop = function () { if (!isStopped() && started) { options.debug('Stopping record timer. Was recording for about ~' + getSecondsRecorded() + ' seconds.'); hide(); recordNote.stop(); countdown = null; started = false; } }; this.build = function () { recordTimerElement = visuals.querySelector('.recordTimer'); if (!recordTimerElement) { recordTimerElement = (0, _hyperscript2.default)('p.recordTimer'); hide(); visuals.appendChild(recordTimerElement); } else { hide(); } }; }; var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } },{"hidden":32,"hyperscript":34}],111:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _events = _dereq_('./../../../events'); var _events2 = _interopRequireDefault(_events); var _eventEmitter = _dereq_('./../../../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _countdown = _dereq_('./recorder/countdown'); var _countdown2 = _interopRequireDefault(_countdown); var _pausedNote = _dereq_('./recorder/pausedNote'); var _pausedNote2 = _interopRequireDefault(_pausedNote); var _recordNote = _dereq_('./recorder/recordNote'); var _recordNote2 = _interopRequireDefault(_recordNote); var _recordTimer = _dereq_('./recorder/recordTimer'); var _recordTimer2 = _interopRequireDefault(_recordTimer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var RecorderInsides = function RecorderInsides(visuals, options) { _eventEmitter2.default.call(this, options, 'RecorderInsides'); var self = this; var debug = options.debug; var recordNote = new _recordNote2.default(visuals); var recordTimer = new _recordTimer2.default(visuals, recordNote, options); var countdown; var pausedNote; var built; if (options.video.countdown) { countdown = new _countdown2.default(visuals, options); } if (options.enablePause) { pausedNote = new _pausedNote2.default(visuals, options); } function startRecording() { recordTimer.start(); } function resumeRecording() { recordTimer.resume(); } function stopRecording() { recordTimer.stop(); } function pauseRecording() { if (self.isCountingDown()) { countdown.pause(); } else { recordTimer.pause(); } } function onResetting() { self.hidePause(); self.hideCountdown(); recordTimer.stop(); } function initEvents() { debug('RecorderInsides: initEvents()'); self.on(_events2.default.RECORDING, function () { startRecording(); }).on(_events2.default.RESUMING, function () { resumeRecording(); }).on(_events2.default.STOPPING, function () { stopRecording(); }).on(_events2.default.PAUSED, function () { pauseRecording(); }).on(_events2.default.RESETTING, onResetting).on(_events2.default.HIDE, function () { self.hideCountdown(); }); } this.build = function () { debug('RecorderInsides: build()'); countdown && countdown.build(); pausedNote && pausedNote.build(); recordNote.build(); recordTimer.build(); !built && initEvents(); built = true; }; this.unload = function () { countdown && countdown.unload(); built = false; }; this.showPause = function () { pausedNote && pausedNote.show(); }; this.hidePause = function () { pausedNote && pausedNote.hide(); }; this.hideCountdown = function () { countdown && countdown.hide(); }; this.startCountdown = function (cb) { countdown && countdown.start(cb); }; this.resumeCountdown = function () { countdown && countdown.resume(); }; this.isCountingDown = function () { return countdown && countdown.isCountingDown(); }; this.checkTimer = function (intervalSum) { recordTimer.check(intervalSum); }; }; _util2.default.inherits(RecorderInsides, _eventEmitter2.default); exports.default = RecorderInsides; },{"./../../../events":88,"./../../../util/eventEmitter":95,"./recorder/countdown":107,"./recorder/pausedNote":108,"./recorder/recordNote":109,"./recorder/recordTimer":110,"util":80}],112:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _eventEmitter = _dereq_('./../../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _events = _dereq_('./../../events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Notifier = function Notifier(visuals, options) { _eventEmitter2.default.call(this, options, 'Notifier'); var self = this; var debug = options && options.debug; var notifyElement; var messageElement; var explanationElement; var entertainTimeoutId; var entertaining; var built; function onStopping(limitReached) { var lead = ''; visuals.beginWaiting(); if (limitReached) { debug('Limit reached'); lead += options.text.limitReached + '.<br/>'; } lead += options.text.sending + ' …'; self.notify(lead, null, { stillWait: true, entertain: options.notifier.entertain }); } function onConnecting() { self.notify('Connecting …'); } function onLoadingUserMedia() { self.notify('Loading webcam …'); } function onProgress(frameProgress, sampleProgress) { var overallProgress; if (options.isAudioEnabled()) { overallProgress = 'Video: ' + frameProgress; if (sampleProgress) { overallProgress += ', Audio: ' + sampleProgress; } } else { overallProgress = frameProgress; } self.setExplanation(overallProgress); } function onBeginVideoEncoding() { visuals.beginWaiting(); var lead = options.text.encoding + ' …'; self.notify(lead, null, { stillWait: true, entertain: options.notifier.entertain }); hideExplanation(); } function initEvents() { debug('Notifier: initEvents()'); self.on(_events2.default.CONNECTING, function () { onConnecting(); }).on(_events2.default.LOADING_USER_MEDIA, function () { onLoadingUserMedia(); }).on(_events2.default.USER_MEDIA_READY, function () { self.hide(); }).on(_events2.default.LOADED_META_DATA, function () { correctDimensions(); }).on(_events2.default.PREVIEW, function () { self.hide(); }).on(_events2.default.STOPPING, function (limitReached) { onStopping(limitReached); }).on(_events2.default.PROGRESS, function (frameProgress, sampleProgress) { onProgress(frameProgress, sampleProgress); }).on(_events2.default.BEGIN_VIDEO_ENCODING, function () { onBeginVideoEncoding(); }); } function correctDimensions() { notifyElement.style.width = visuals.getRecorderWidth(true) + 'px'; notifyElement.style.height = visuals.getRecorderHeight(true) + 'px'; } function show() { notifyElement && (0, _hidden2.default)(notifyElement, false); } function runEntertainment() { if (options.notifier.entertain) { if (!entertaining) { var randomBackgroundClass = Math.floor(Math.random() * options.notifier.entertainLimit + 1); notifyElement.className = 'notifier entertain ' + options.notifier.entertainClass + randomBackgroundClass; entertainTimeoutId = setTimeout(runEntertainment, options.notifier.entertainInterval); entertaining = true; } } else { cancelEntertainment(); } } function cancelEntertainment() { if (notifyElement) { notifyElement.classList.remove('entertain'); } clearTimeout(entertainTimeoutId); entertainTimeoutId = null; entertaining = false; } function setMessage(message, messageOptions) { var problem = messageOptions.problem ? messageOptions.problem : false; if (messageElement) { messageElement.innerHTML = (problem ? '&#x2639; ' : '') + message; } else { options.logger.warn('Unable to show following because messageElement is empty:', message); } } this.error = function (err) { var message = err.message ? err.message.toString() : err.toString(); var explanation = err.explanation ? err.explanation.toString() : null; if (!message) { options.debug('Weird empty message generated for error', err); } self.notify(message, explanation, { blocking: true, problem: true, hideForm: err.hideForm && err.hideForm(), classList: err.getClassList && err.getClassList(), removeDimensions: err.removeDimensions && err.removeDimensions() }); }; this.setExplanation = function (explanation) { if (!explanationElement) { explanationElement = (0, _hyperscript2.default)('p'); if (notifyElement) { notifyElement.appendChild(explanationElement); } else { options.logger.warn('Unable to show explanation because notifyElement is empty:', explanation); } } explanationElement.innerHTML = explanation; (0, _hidden2.default)(explanationElement, false); }; this.build = function () { options.debug('Notifier: build()'); notifyElement = visuals.querySelector('.notifier'); if (!notifyElement) { notifyElement = (0, _hyperscript2.default)('.notifier'); // defaults to div this.hide(); visuals.appendChild(notifyElement); } else { this.hide(); } !built && initEvents(); built = true; }; function hideExplanation() { if (explanationElement) { explanationElement.innerHTML = null; (0, _hidden2.default)(explanationElement, true); } } this.hide = function () { cancelEntertainment(); if (notifyElement) { (0, _hidden2.default)(notifyElement, true); notifyElement.classList.remove('blocking'); } if (messageElement) { messageElement.innerHTML = null; } hideExplanation(); }; this.isVisible = function () { if (!built) { return false; } else { return notifyElement && !(0, _hidden2.default)(notifyElement); } }; this.isBuilt = function () { return built; }; this.notify = function (message, explanation, notifyOptions) { options.debug('Notifier: notify()'); if (!notifyOptions) { notifyOptions = {}; } var stillWait = notifyOptions.stillWait ? notifyOptions.stillWait : false; var entertain = notifyOptions.entertain ? notifyOptions.entertain : false; var blocking = notifyOptions.blocking ? notifyOptions.blocking : false; var hideForm = notifyOptions.hideForm ? notifyOptions.hideForm : false; var classList = notifyOptions.classList ? notifyOptions.classList : false; var removeDimensions = notifyOptions.removeDimensions ? notifyOptions.removeDimensions : false; if (!messageElement && notifyElement) { messageElement = (0, _hyperscript2.default)('h2'); if (explanationElement) { notifyElement.insertBefore(messageElement, explanationElement); } else { notifyElement.appendChild(messageElement); } } if (notifyElement) { // reset if (!entertain) { notifyElement.className = 'notifier'; } if (classList) { classList.forEach(function (className) { notifyElement.classList.add(className); }); } if (removeDimensions) { notifyElement.style.width = 'auto'; notifyElement.style.height = 'auto'; } } if (blocking) { notifyElement && notifyElement.classList.add('blocking'); this.emit(_events2.default.BLOCKING, { hideForm: hideForm }); } else { this.emit(_events2.default.NOTIFYING); } visuals.hideReplay(); visuals.hideRecorder(); setMessage(message, notifyOptions); if (explanation && explanation.length > 0) { this.setExplanation(explanation); } if (entertain) { runEntertainment(); } else { cancelEntertainment(); } // just as a safety in case if an error is thrown in the middle of the build process // and visuals aren't built/shown yet. visuals.showVisuals(); show(); !stillWait && visuals.endWaiting(); }; }; _util2.default.inherits(Notifier, _eventEmitter2.default); exports.default = Notifier; },{"./../../events":88,"./../../util/eventEmitter":95,"hidden":32,"hyperscript":34,"util":80}],113:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _websocketStream = _dereq_('websocket-stream'); var _websocketStream2 = _interopRequireDefault(_websocketStream); var _canvasToBuffer = _dereq_('canvas-to-buffer'); var _canvasToBuffer2 = _interopRequireDefault(_canvasToBuffer); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _animitter = _dereq_('animitter'); var _animitter2 = _interopRequireDefault(_animitter); var _fastSafeStringify = _dereq_('fast-safe-stringify'); var _fastSafeStringify2 = _interopRequireDefault(_fastSafeStringify); var _userMedia = _dereq_('./userMedia'); var _userMedia2 = _interopRequireDefault(_userMedia); var _events = _dereq_('./../../events'); var _events2 = _interopRequireDefault(_events); var _constants = _dereq_('./../../constants'); var _constants2 = _interopRequireDefault(_constants); var _eventEmitter = _dereq_('./../../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _browser = _dereq_('./../../util/browser'); var _browser2 = _interopRequireDefault(_browser); var _humanize = _dereq_('./../../util/humanize'); var _humanize2 = _interopRequireDefault(_humanize); var _pretty = _dereq_('./../../util/pretty'); var _pretty2 = _interopRequireDefault(_pretty); var _videomailError = _dereq_('./../../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // credits http://1lineart.kulaone.com/#/ var PIPE_SYMBOL = '°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸ '; var Recorder = function Recorder(visuals, replay, options) { _eventEmitter2.default.call(this, options, 'Recorder'); // validate some options this class needs if (!options || !options.video || !options.video.fps) { throw _videomailError2.default.create('FPS must be defined', options); } var self = this; var browser = new _browser2.default(options); var debug = options.debug; var loop = null; var originalAnimationFrameObject; var samplesCount = 0; var framesCount = 0; var recordingStats = {}; var confirmedFrameNumber = 0; var confirmedSampleNumber = 0; var recorderElement; var userMedia; var userMediaTimeout; var retryTimeout; var bytesSum; var frameProgress; var sampleProgress; var canvas; var ctx; var userMediaLoaded; var userMediaLoading; var submitting; var unloaded; var stopTime; var stream; var connecting; var connected; var blocking; var built; var key; var waitingTime; var pingInterval; var frame; var recordingBufferLength; var recordingBuffer; function writeStream(buffer, opts) { if (stream) { if (stream.destroyed) { // prevents https://github.com/binarykitchen/videomail.io/issues/393 stopPings(); self.emit(_events2.default.ERROR, _videomailError2.default.create('Already disconnected', 'Sorry, connection to the server has been destroyed. Please reload.', options)); } else { var onFlushedCallback = opts && opts.onFlushedCallback; try { stream.write(buffer, function () { onFlushedCallback && onFlushedCallback(opts); }); } catch (exc) { self.emit(_events2.default.ERROR, _videomailError2.default.create('Failed writing to server', 'stream.write() failed because of ' + (0, _pretty2.default)(exc), options)); } } } } function sendPings() { pingInterval = window.setInterval(function () { debug('Recorder: pinging...'); writeStream(Buffer.from('')); }, options.timeouts.pingInterval); } function stopPings() { clearInterval(pingInterval); } function onAudioSample(audioSample) { samplesCount++; var audioBuffer = audioSample.toBuffer(); // if (options.verbose) { // debug( // 'Sample #' + samplesCount + ' (' + audioBuffer.length + ' bytes):' // ) // } writeStream(audioBuffer); } function show() { recorderElement && (0, _hidden2.default)(recorderElement, false); } function onUserMediaReady() { try { debug('Recorder: onUserMediaReady()'); userMediaLoading = blocking = unloaded = submitting = false; userMediaLoaded = true; loop = createLoop(); show(); self.emit(_events2.default.USER_MEDIA_READY, { paused: self.isPaused() }); } catch (exc) { self.emit(_events2.default.ERROR, exc); } } function clearRetryTimeout() { debug('Recorder: clearRetryTimeout()'); retryTimeout && clearTimeout(retryTimeout); retryTimeout = null; } function clearUserMediaTimeout() { if (userMediaTimeout) { debug('Recorder: clearUserMediaTimeout()'); userMediaTimeout && clearTimeout(userMediaTimeout); userMediaTimeout = null; } } function calculateFrameProgress() { return (confirmedFrameNumber / (framesCount || 1) * 100).toFixed(2) + '%'; } function calculateSampleProgress() { return (confirmedSampleNumber / (samplesCount || 1) * 100).toFixed(2) + '%'; } function updateOverallProgress() { // when progresses aren't initialized, // then do a first calculation to avoid `infinite` or `null` displays if (!frameProgress) { frameProgress = calculateFrameProgress(); } if (!sampleProgress) { sampleProgress = calculateSampleProgress(); } self.emit(_events2.default.PROGRESS, frameProgress, sampleProgress); } function updateFrameProgress(args) { confirmedFrameNumber = args.frame ? args.frame : confirmedFrameNumber; frameProgress = calculateFrameProgress(); updateOverallProgress(); } function updateSampleProgress(args) { confirmedSampleNumber = args.sample ? args.sample : confirmedSampleNumber; sampleProgress = calculateSampleProgress(); updateOverallProgress(); } function preview(args) { confirmedFrameNumber = confirmedSampleNumber = samplesCount = framesCount = 0; sampleProgress = frameProgress = null; key = args.key; if (args.mp4) { replay.setMp4Source(args.mp4 + _constants2.default.SITE_NAME_LABEL + '/' + options.siteName + '/videomail.mp4', true); } if (args.webm) { replay.setWebMSource(args.webm + _constants2.default.SITE_NAME_LABEL + '/' + options.siteName + '/videomail.webm', true); } self.hide(); var width = self.getRecorderWidth(true); var height = self.getRecorderHeight(true); self.emit(_events2.default.PREVIEW, key, width, height); // keep it for recording stats waitingTime = Date.now() - stopTime; recordingStats.waitingTime = waitingTime; if (options.debug) { debug('While recording, %s have been transferred and waiting time was %s', _humanize2.default.filesize(bytesSum, 2), _humanize2.default.toTime(waitingTime)); } } function initSocket(cb) { if (!connected) { connecting = true; debug('Recorder: initialising web socket to %s', options.socketUrl); self.emit(_events2.default.CONNECTING); // https://github.com/maxogden/websocket-stream#binary-sockets // we use query parameters here because we cannot set custom headers in web sockets, // see https://github.com/websockets/ws/issues/467 var url2Connect = options.socketUrl + '?' + encodeURIComponent(_constants2.default.SITE_NAME_LABEL) + '=' + encodeURIComponent(options.siteName); try { // websocket options cannot be set on client side, only on server, see // https://github.com/maxogden/websocket-stream/issues/116#issuecomment-296421077 stream = (0, _websocketStream2.default)(url2Connect, { perMessageDeflate: false, // see https://github.com/maxogden/websocket-stream/issues/117#issuecomment-298826011 objectMode: true }); } catch (exc) { connecting = connected = false; var err; if (typeof _websocketStream2.default === 'undefined') { err = _videomailError2.default.create('There is no websocket', 'Cause: ' + (0, _pretty2.default)(exc), options); } else { err = _videomailError2.default.create('Failed to connect to server', 'Please upgrade your browser. Your current version does not seem to support websockets.', options, { browserProblem: true }); } self.emit(_events2.default.ERROR, err); } if (stream) { // // useful for debugging streams // // if (!stream.originalEmit) { // stream.originalEmit = stream.emit // } // // stream.emit = function (type) { // if (stream) { // debug(PIPE_SYMBOL + 'Debugging stream event:', type) // var args = Array.prototype.slice.call(arguments, 0) // return stream.originalEmit.apply(stream, args) // } // } stream.on('close', function (err) { debug(PIPE_SYMBOL + 'Stream has closed'); connecting = connected = false; if (err) { self.emit(_events2.default.ERROR, err || 'Unhandled websocket error'); } else { self.emit(_events2.default.DISCONNECTED); // prevents from https://github.com/binarykitchen/videomail.io/issues/297 happening cancelAnimationFrame(); } }); stream.on('connect', function () { debug(PIPE_SYMBOL + 'Stream *connect* event emitted'); if (!connected) { connected = true; connecting = unloaded = false; self.emit(_events2.default.CONNECTED); debug('Going to ask for webcam permissons now ...'); cb && cb(); } }); stream.on('data', function (data) { debug(PIPE_SYMBOL + 'Stream *data* event emitted'); var command; try { command = JSON.parse(data.toString()); } catch (exc) { debug('Failed to parse command:', exc); self.emit(_events2.default.ERROR, _videomailError2.default.create('Invalid server command', // toString() since https://github.com/binarykitchen/videomail.io/issues/288 'Contact us asap. Bad commmand was ' + data.toString() + '. ', options)); } finally { executeCommand.call(self, command); } }); stream.on('error', function (err) { debug(PIPE_SYMBOL + 'Stream *error* event emitted', err); connecting = connected = false; // setting custom text since that err object isn't really an error // on iphones when locked, and unlocked, this err is actually // an event object with stuff we can't use at all (an external bug) self.emit(_events2.default.ERROR, _videomailError2.default.create('Connection error', 'Data exchange has been interrupted. Please reload.', options)); }); // just experimental stream.on('drain', function () { debug(PIPE_SYMBOL + 'Stream *drain* event emitted (should not happen!)'); }); stream.on('preend', function () { debug(PIPE_SYMBOL + 'Stream *preend* event emitted'); }); stream.on('end', function () { debug(PIPE_SYMBOL + 'Stream *end* event emitted'); }); stream.on('drain', function () { debug(PIPE_SYMBOL + 'Stream *drain* event emitted'); }); stream.on('pipe', function () { debug(PIPE_SYMBOL + 'Stream *pipe* event emitted'); }); stream.on('unpipe', function () { debug(PIPE_SYMBOL + 'Stream *unpipe* event emitted'); }); stream.on('resume', function () { debug(PIPE_SYMBOL + 'Stream *resume* event emitted'); }); stream.on('uncork', function () { debug(PIPE_SYMBOL + 'Stream *uncork* event emitted'); }); stream.on('readable', function () { debug(PIPE_SYMBOL + 'Stream *preend* event emitted'); }); stream.on('prefinish', function () { debug(PIPE_SYMBOL + 'Stream *preend* event emitted'); }); stream.on('finish', function () { debug(PIPE_SYMBOL + 'Stream *preend* event emitted'); }); } } } function showUserMedia() { // use connected flag to prevent this from happening // https://github.com/binarykitchen/videomail.io/issues/323 return connected && (isNotifying() || !isHidden() || blocking); } function userMediaErrorCallback(err) { userMediaLoading = false; clearUserMediaTimeout(); debug('Recorder: userMediaErrorCallback()', ', Webcam characteristics:', userMedia.getCharacteristics()); var errorListeners = self.listeners(_events2.default.ERROR); if (errorListeners.length) { if (err.name !== _videomailError2.default.MEDIA_DEVICE_NOT_SUPPORTED) { self.emit(_events2.default.ERROR, _videomailError2.default.create(err, options)); } else { // do not emit but retry since MEDIA_DEVICE_NOT_SUPPORTED can be a race condition debug('Recorder: ignore user media error', err); } // retry after a while retryTimeout = setTimeout(initSocket, options.timeouts.userMedia); } else { if (unloaded) { // can happen that container is unloaded but some user media related callbacks // are still in process. in that case ignore error. debug('Recorder: already unloaded. Not going to throw error', err); } else { debug('Recorder: no error listeners attached but throwing error', err); // weird situation, throw it instead of emitting since there are no error listeners throw _videomailError2.default.create(err, 'Unable to process this error since there are no error listeners anymore.', options); } } } function getUserMediaCallback(localStream) { debug('Recorder: getUserMediaCallback()'); if (showUserMedia()) { try { clearUserMediaTimeout(); userMedia.init(localStream, onUserMediaReady.bind(self), onAudioSample.bind(self), function (err) { self.emit(_events2.default.ERROR, err); }); } catch (exc) { self.emit(_events2.default.ERROR, exc); } } } function loadGenuineUserMedia() { if (!navigator) { throw new Error('Navigator is missing!'); } debug('Recorder: loadGenuineUserMedia()'); self.emit(_events2.default.ASKING_WEBCAM_PERMISSION); // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { // prefer the front camera (if one is available) over the rear one var constraints = { video: { facingMode: 'user', frameRate: { ideal: options.video.fps } }, audio: options.isAudioEnabled() }; if (browser.isOkSafari()) { // do not use those width/height constraints yet, // current safari would throw an error // todo in https://github.com/binarykitchen/videomail-client/issues/142 } else { if (options.hasDefinedWidth()) { constraints.video.width = { ideal: options.video.width }; } else { // otherwise try to apply the same width as the element is having // but there is no 100% guarantee that this will happen. not // all webcam drivers behave the same way constraints.video.width = { ideal: self.limitWidth() }; } if (options.hasDefinedHeight()) { constraints.video.height = { ideal: options.video.height }; } } debug('Recorder: navigator.mediaDevices.getUserMedia()', constraints); navigator.mediaDevices.getUserMedia(constraints).then(getUserMediaCallback).catch(userMediaErrorCallback); } else { debug('Recorder: navigator.getUserMedia()'); navigator.getUserMedia_({ video: true, audio: options.isAudioEnabled() }, getUserMediaCallback, userMediaErrorCallback); } } function loadUserMedia() { if (userMediaLoaded) { debug('Recorder: skipping loadUserMedia() because it is already loaded'); onUserMediaReady(); return false; } else if (userMediaLoading) { debug('Recorder: skipping loadUserMedia() because it is already asking for permission'); return false; } debug('Recorder: loadUserMedia()'); self.emit(_events2.default.LOADING_USER_MEDIA); try { userMediaTimeout = setTimeout(function () { if (!self.isReady()) { self.emit(_events2.default.ERROR, browser.getNoAccessIssue()); } }, options.timeouts.userMedia); userMediaLoading = true; loadGenuineUserMedia(); } catch (exc) { debug('Recorder: failed to load genuine user media'); userMediaLoading = false; var errorListeners = self.listeners(_events2.default.ERROR); if (errorListeners.length) { self.emit(_events2.default.ERROR, exc); } else { debug('Recorder: no error listeners attached but throwing exception', exc); throw exc; // throw it further } } } function executeCommand(command) { try { debug('Server commanded: %s', command.command, command.args ? ', ' + (0, _fastSafeStringify2.default)(command.args) : ''); switch (command.command) { case 'ready': if (!userMediaTimeout) { loadUserMedia(); } break; case 'preview': preview(command.args); break; case 'error': this.emit(_events2.default.ERROR, _videomailError2.default.create('Oh no, server error!', command.args.err.toString() || '(No explanation given)', options)); break; case 'confirmFrame': updateFrameProgress(command.args); break; case 'confirmSample': updateSampleProgress(command.args); break; case 'beginAudioEncoding': this.emit(_events2.default.BEGIN_AUDIO_ENCODING); break; case 'beginVideoEncoding': this.emit(_events2.default.BEGIN_VIDEO_ENCODING); break; default: this.emit(_events2.default.ERROR, 'Unknown server command: ' + command.command); break; } } catch (exc) { self.emit(_events2.default.ERROR, exc); } } function isNotifying() { return visuals.isNotifying(); } function isHidden() { return !recorderElement || (0, _hidden2.default)(recorderElement); } function writeCommand(command, args, cb) { if (!cb && args && args.constructor === Function) { cb = args; args = null; } if (!connected) { debug('Reconnecting for the command', command, '…'); initSocket(function () { writeCommand(command, args); cb && cb(); }); } else if (stream) { debug('$ %s', command, args ? (0, _fastSafeStringify2.default)(args) : ''); var commandObj = { command: command, args: args // todo commented out because for some reasons server does not accept such a long // array of many log lines. to examine later. // // add some useful debug info to examine weird stuff like this one // UnprocessableError: Unable to encode a video with FPS near zero. // todo consider removing this later or have it for debug=1 only? // // if (options.logger && options.logger.getLines) { // commandObj.logLines = options.logger.getLines() // } };writeStream(Buffer.from((0, _fastSafeStringify2.default)(commandObj))); if (cb) { // keep all callbacks async setTimeout(function () { cb(); }, 0); } } } function disconnect() { if (connected) { debug('Recorder: disconnect()'); if (userMedia) { // prevents https://github.com/binarykitchen/videomail-client/issues/114 userMedia.unloadRemainingEventListeners(); } if (submitting) { // server will disconnect socket automatically after submitting connecting = connected = false; } else if (stream) { // force to disconnect socket right now to clean temp files on server // event listeners will do the rest stream.end(); stream = undefined; } } } function cancelAnimationFrame() { loop && loop.dispose(); } function getIntervalSum() { return loop.getElapsedTime(); } function getAvgInterval() { return getIntervalSum() / framesCount; } this.getRecordingStats = function () { return recordingStats; }; this.getAudioSampleRate = function () { return userMedia.getAudioSampleRate(); }; this.stop = function (params) { debug('stop()', params); var limitReached = params.limitReached; this.emit(_events2.default.STOPPING, limitReached); loop.complete(); stopTime = Date.now(); recordingStats = { avgFps: loop.getFPS(), wantedFps: options.video.fps, avgInterval: getAvgInterval(), wantedInterval: 1e3 / options.video.fps, intervalSum: getIntervalSum(), framesCount: framesCount, videoType: replay.getVideoType() }; if (options.isAudioEnabled()) { recordingStats.samplesCount = samplesCount; recordingStats.sampleRate = userMedia.getAudioSampleRate(); } writeCommand('stop', recordingStats); // beware, resetting will set framesCount to zero, so leave this here this.reset(); }; this.back = function (cb) { this.emit(_events2.default.GOING_BACK); show(); this.reset(); writeCommand('back', cb); }; function reInitialiseAudio() { debug('Recorder: reInitialiseAudio()'); clearUserMediaTimeout(); // important to free memory userMedia && userMedia.stop(); userMediaLoaded = key = canvas = ctx = null; loadUserMedia(); } this.unload = function (e) { if (!unloaded) { var cause; if (e) { cause = e.name || e.statusText || e.toString(); } debug('Recorder: unload()' + (cause ? ', cause: ' + cause : '')); this.reset(); clearUserMediaTimeout(); disconnect(); unloaded = true; built = false; } }; this.reset = function () { // no need to reset when already unloaded if (!unloaded) { debug('Recorder: reset()'); this.emit(_events2.default.RESETTING); cancelAnimationFrame(); // important to free memory userMedia && userMedia.stop(); replay.reset(); userMediaLoaded = key = canvas = ctx = waitingTime = null; } }; this.validate = function () { return connected && framesCount > 0 && canvas === null; }; this.isReady = function () { return userMedia.isReady(); }; this.pause = function (params) { var e = params && params.event; if (e instanceof window.Event) { params.eventType = e.type; } debug('pause()', params); userMedia.pause(); loop.stop(); this.emit(_events2.default.PAUSED); sendPings(); }; this.isPaused = function () { return userMedia && userMedia.isPaused(); }; this.resume = function () { debug('Recorder: resume()'); stopPings(); this.emit(_events2.default.RESUMING); userMedia.resume(); loop.start(); }; function onFlushed(opts) { var frameNumber = opts && opts.frameNumber; if (frameNumber === 1) { self.emit(_events2.default.FIRST_FRAME_SENT); } } function createLoop() { var newLoop = (0, _animitter2.default)({ fps: options.video.fps }, draw); // remember it first originalAnimationFrameObject = newLoop.getRequestAnimationFrameObject(); return newLoop; } function draw(deltaTime, elapsedTime) { try { // ctx and stream might become null while unloading if (!self.isPaused() && stream && ctx) { if (framesCount === 0) { self.emit(_events2.default.SENDING_FIRST_FRAME); } framesCount++; ctx.drawImage(userMedia.getRawVisuals(), 0, 0, canvas.width, canvas.height); recordingBuffer = frame.toBuffer(); recordingBufferLength = recordingBuffer.length; if (recordingBufferLength < 1) { throw _videomailError2.default.create('Failed to extract webcam data.', options); } bytesSum += recordingBufferLength; writeStream(recordingBuffer, { frameNumber: framesCount, onFlushedCallback: onFlushed }); // if (options.verbose) { // debug( // 'Frame #' + framesCount + ' (' + recordingBufferLength + ' bytes):', // ' delta=' + deltaTime + 'ms, ' + // ' elapsed=' + elapsedTime + 'ms' // ) // } visuals.checkTimer({ intervalSum: elapsedTime }); } } catch (exc) { self.emit(_events2.default.ERROR, exc); } } this.record = function () { if (unloaded) { return false; } // reconnect when needed if (!connected) { debug('Recorder: reconnecting before recording ...'); initSocket(function () { self.once(_events2.default.USER_MEDIA_READY, self.record); }); return false; } try { canvas = userMedia.createCanvas(); } catch (exc) { self.emit(_events2.default.ERROR, _videomailError2.default.create('Failed to create canvas.', exc, options)); return false; } ctx = canvas.getContext('2d'); if (!canvas.width) { self.emit(_events2.default.ERROR, _videomailError2.default.create('Canvas has an invalid width.', options)); return false; } if (!canvas.height) { self.emit(_events2.default.ERROR, _videomailError2.default.create('Canvas has an invalid height.', options)); return false; } bytesSum = 0; frame = new _canvasToBuffer2.default(canvas, options); debug('Recorder: record()'); userMedia.record(); self.emit(_events2.default.RECORDING, framesCount); loop.start(); }; function setAnimationFrameObject(newObj) { // must stop and then start to make it become effective, see // https://github.com/hapticdata/animitter/issues/5#issuecomment-292019168 if (loop) { var isRecording = self.isRecording(); loop.stop(); loop.setRequestAnimationFrameObject(newObj); if (isRecording) { loop.start(); } } } function restoreAnimationFrameObject() { debug('Recorder: restoreAnimationFrameObject()'); setAnimationFrameObject(originalAnimationFrameObject); } function loopWithTimeouts() { debug('Recorder: loopWithTimeouts()'); var wantedInterval = 1e3 / options.video.fps; var processingTime = 0; var start; function raf(fn) { return setTimeout(function () { start = Date.now(); fn(); processingTime = Date.now() - start; }, // reducing wanted interval by respecting the time it takes to // compute internally since this is not multi-threaded like // requestAnimationFrame wantedInterval - processingTime); } function cancel(id) { clearTimeout(id); } setAnimationFrameObject({ requestAnimationFrame: raf, cancelAnimationFrame: cancel }); } function buildElement() { recorderElement = (0, _hyperscript2.default)('video.' + options.selectors.userMediaClass); visuals.appendChild(recorderElement); } function correctDimensions() { if (options.hasDefinedWidth()) { recorderElement.width = self.getRecorderWidth(true); } if (options.hasDefinedHeight()) { recorderElement.height = self.getRecorderHeight(true); } } function initEvents() { debug('Recorder: initEvents()'); self.on(_events2.default.SUBMITTING, function () { submitting = true; }).on(_events2.default.SUBMITTED, function () { submitting = false; self.unload(); }).on(_events2.default.BLOCKING, function () { blocking = true; clearUserMediaTimeout(); }).on(_events2.default.HIDE, function () { self.hide(); }).on(_events2.default.LOADED_META_DATA, function () { correctDimensions(); }).on(_events2.default.DISABLING_AUDIO, function () { reInitialiseAudio(); }).on(_events2.default.ENABLING_AUDIO, function () { reInitialiseAudio(); }).on(_events2.default.INVISIBLE, function () { loopWithTimeouts(); }).on(_events2.default.VISIBLE, function () { restoreAnimationFrameObject(); }); } this.build = function () { var err = browser.checkRecordingCapabilities(); if (!err) { err = browser.checkBufferTypes(); } if (err) { this.emit(_events2.default.ERROR, err); } else { recorderElement = visuals.querySelector('video.' + options.selectors.userMediaClass); if (!recorderElement) { buildElement(); } correctDimensions(); // prevent audio feedback, see // https://github.com/binarykitchen/videomail-client/issues/35 recorderElement.muted = true; // for iphones, see https://github.com/webrtc/samples/issues/929 recorderElement.setAttribute('playsinline', true); recorderElement.setAttribute('webkit-playsinline', 'webkit-playsinline'); if (!userMedia) { userMedia = new _userMedia2.default(this, options); } show(); if (!built) { initEvents(); if (!connected) { initSocket(); } else { loadUserMedia(); } } else { loadUserMedia(); } built = true; } }; this.isPaused = function () { return userMedia && userMedia.isPaused() && !loop.isRunning(); }; this.isRecording = function () { // checking for stream.destroyed needed since // https://github.com/binarykitchen/videomail.io/issues/296 return loop && loop.isRunning() && !this.isPaused() && !isNotifying() && stream && !stream.destroyed; }; this.hide = function () { if (!isHidden()) { recorderElement && (0, _hidden2.default)(recorderElement, true); clearUserMediaTimeout(); clearRetryTimeout(); } }; this.isUnloaded = function () { return unloaded; }; // these two return the true dimensions of the webcam area. // needed because on mobiles they might be different. this.getRecorderWidth = function (responsive) { if (userMedia && userMedia.hasVideoWidth()) { return userMedia.getRawWidth(responsive); } else if (responsive && options.hasDefinedWidth()) { return this.limitWidth(options.video.width); } }; this.getRecorderHeight = function (responsive) { if (userMedia) { return userMedia.getRawHeight(responsive); } else if (responsive && options.hasDefinedHeight()) { return this.calculateHeight(responsive); } }; function getRatio() { var ratio; if (userMedia) { var userMediaVideoWidth = userMedia.getVideoWidth(); // avoid division by zero if (userMediaVideoWidth < 1) { // use as a last resort fallback computation (needed for safari 11) ratio = visuals.getRatio(); } else { ratio = userMedia.getVideoHeight() / userMediaVideoWidth; } } else { ratio = options.getRatio(); } return ratio; } this.calculateWidth = function (responsive) { var videoHeight; if (userMedia) { videoHeight = userMedia.getVideoHeight(); } else if (recorderElement) { videoHeight = recorderElement.videoHeight || recorderElement.height; } return visuals.calculateWidth({ responsive: responsive, ratio: getRatio(), videoHeight: videoHeight }); }; this.calculateHeight = function (responsive) { var videoWidth; if (userMedia) { videoWidth = userMedia.getVideoWidth(); } else if (recorderElement) { videoWidth = recorderElement.videoWidth || recorderElement.width; } return visuals.calculateHeight({ responsive: responsive, ratio: getRatio(), videoWidth: videoWidth }); }; this.getRawVisualUserMedia = function () { return recorderElement; }; this.isConnected = function () { return connected; }; this.isConnecting = function () { return connecting; }; this.limitWidth = function (width) { return visuals.limitWidth(width); }; this.limitHeight = function (height) { return visuals.limitHeight(height); }; this.isUserMediaLoaded = function () { return userMediaLoaded; }; }; _util2.default.inherits(Recorder, _eventEmitter2.default); exports.default = Recorder; }).call(this,_dereq_("buffer").Buffer) },{"./../../constants":87,"./../../events":88,"./../../util/browser":93,"./../../util/eventEmitter":95,"./../../util/humanize":96,"./../../util/pretty":98,"./../../util/videomailError":100,"./userMedia":115,"animitter":2,"buffer":8,"canvas-to-buffer":9,"fast-safe-stringify":25,"hidden":32,"hyperscript":34,"util":80,"websocket-stream":82}],114:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = _dereq_('util'); var _util2 = _interopRequireDefault(_util); var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _hidden = _dereq_('hidden'); var _hidden2 = _interopRequireDefault(_hidden); var _addEventlistenerWithOptions = _dereq_('add-eventlistener-with-options'); var _addEventlistenerWithOptions2 = _interopRequireDefault(_addEventlistenerWithOptions); var _events = _dereq_('./../../events'); var _events2 = _interopRequireDefault(_events); var _browser = _dereq_('./../../util/browser'); var _browser2 = _interopRequireDefault(_browser); var _eventEmitter = _dereq_('./../../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _videomailError = _dereq_('./../../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); var _iphoneInlineVideo = _dereq_('iphone-inline-video'); var _iphoneInlineVideo2 = _interopRequireDefault(_iphoneInlineVideo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Replay = function Replay(parentElement, options) { _eventEmitter2.default.call(this, options, 'Replay'); var self = this; var browser = new _browser2.default(options); var debug = options.debug; var built; var replayElement; var videomail; function buildElement() { debug('Replay: buildElement()'); replayElement = (0, _hyperscript2.default)('video.' + options.selectors.replayClass); if (!replayElement.setAttribute) { throw _videomailError2.default.create('Please upgrade browser', options); } parentElement.appendChild(replayElement); } function isStandalone() { return parentElement.constructor.name === 'HTMLDivElement'; } function copyAttributes(newVideomail) { var attributeContainer; Object.keys(newVideomail).forEach(function (attribute) { attributeContainer = parentElement.querySelector('.' + attribute); if (attributeContainer) { attributeContainer.innerHTML = newVideomail[attribute]; } }); } function correctDimensions(options) { var width, height; if (videomail && videomail.playerWidth) { width = videomail.playerWidth; } else if (parentElement.calculateWidth) { width = parentElement.calculateWidth(options); } if (videomail && videomail.playerHeight) { height = videomail.playerHeight; } else if (parentElement.calculateHeight) { height = parentElement.calculateHeight(options); } if (width > 0) { replayElement.style.width = width + 'px'; } else { replayElement.style.width = 'auto'; } if (height > 0) { replayElement.style.height = height + 'px'; } else { replayElement.style.height = 'auto'; } } this.setVideomail = function (newVideomail) { videomail = newVideomail; if (videomail) { if (videomail.webm) { this.setWebMSource(videomail.webm); } if (videomail.mp4) { this.setMp4Source(videomail.mp4); } if (videomail.poster) { replayElement.setAttribute('poster', videomail.poster); } copyAttributes(videomail); } var hasAudio = videomail && videomail.recordingStats && videomail.recordingStats.sampleRate > 0; this.show(videomail && videomail.width, videomail && videomail.height, hasAudio); }; this.show = function (recorderWidth, recorderHeight, hasAudio) { if (videomail) { correctDimensions({ responsive: true, // beware that recorderWidth and recorderHeight can be null sometimes videoWidth: recorderWidth || replayElement.videoWidth, videoHeight: recorderHeight || replayElement.videoHeight }); } (0, _hidden2.default)(replayElement, false); // parent element can be any object, be careful! if (parentElement) { if (parentElement.style) { (0, _hidden2.default)(parentElement, false); } else if (parentElement.show) { parentElement.show(); } } if (hasAudio) { // https://github.com/binarykitchen/videomail-client/issues/115 // do not set mute to false as this will mess up. just do not mention this attribute at all replayElement.setAttribute('volume', 1); } else if (!options.isAudioEnabled()) { replayElement.setAttribute('muted', true); } // this must be called after setting the sources and when becoming visible // see https://github.com/bfred-it/iphone-inline-video/issues/16 _iphoneInlineVideo2.default && (0, _iphoneInlineVideo2.default)(replayElement, { iPad: true }); // this forces to actually fetch the videos from the server replayElement.load(); if (!videomail) { self.emit(_events2.default.PREVIEW_SHOWN); } else { self.emit(_events2.default.REPLAY_SHOWN); } }; this.build = function () { debug('Replay: build()'); replayElement = parentElement.querySelector('video.' + options.selectors.replayClass); if (!replayElement) { buildElement(); } this.hide(); replayElement.setAttribute('autoplay', true); replayElement.setAttribute('autostart', true); replayElement.setAttribute('autobuffer', true); replayElement.setAttribute('playsinline', true); replayElement.setAttribute('webkit-playsinline', 'webkit-playsinline'); replayElement.setAttribute('controls', 'controls'); replayElement.setAttribute('preload', 'auto'); if (!built) { if (!isStandalone()) { this.on(_events2.default.PREVIEW, function (key, recorderWidth, recorderHeight) { self.show(recorderWidth, recorderHeight); }); } // makes use of passive option automatically for better performance // https://www.npmjs.com/package/add-eventlistener-with-options (0, _addEventlistenerWithOptions2.default)(replayElement, 'touchstart', function (e) { try { e && e.preventDefault(); } catch (exc) { // ignore errors like // Unable to preventDefault inside passive event listener invocation. } if (this.paused) { play(); } else { pause(); } }); replayElement.onclick = function (e) { e && e.preventDefault(); if (this.paused) { play(); } else { pause(); } }; } built = true; debug('Replay: built.'); }; this.unload = function () { built = false; }; this.getVideoSource = function (type) { var sources = replayElement.getElementsByTagName('source'); var l = sources.length; var videoType = 'video/' + type; var source; if (l) { var i; for (i = 0; i < l && !source; i++) { if (sources[i].getAttribute('type') === videoType) { source = sources[i]; } } } return source; }; function setVideoSource(type, src, bustCache) { var source = self.getVideoSource(type); if (src && bustCache) { src += '?' + Date.now(); } if (!source) { if (src) { source = (0, _hyperscript2.default)('source', { src: src, type: 'video/' + type }); replayElement.appendChild(source); } } else { if (src) { source.setAttribute('src', src); } else { replayElement.removeChild(source); } } } this.setMp4Source = function (src, bustCache) { setVideoSource('mp4', src, bustCache); }; this.setWebMSource = function (src, bustCache) { setVideoSource('webm', src, bustCache); }; this.getVideoType = function () { return browser.getVideoType(replayElement); }; function pause(cb) { // avoids race condition, inspired by // http://stackoverflow.com/questions/36803176/how-to-prevent-the-play-request-was-interrupted-by-a-call-to-pause-error setTimeout(function () { try { replayElement.pause(); } catch (exc) { // just ignore, see https://github.com/binarykitchen/videomail.io/issues/386 options.logger.warn(exc); } cb && cb(); }, 15); } function play() { if (replayElement && replayElement.play) { var p; try { p = replayElement.play(); } catch (exc) { // this in the hope to catch InvalidStateError, see // https://github.com/binarykitchen/videomail-client/issues/149 options.logger.warn('Caught replay exception:', exc); } if (p && typeof Promise !== 'undefined' && p instanceof Promise) { p.catch(function (reason) { options.logger.warn('Caught pending replay promise exception: %s', reason); }); } } } this.reset = function (cb) { // pause video to make sure it won't consume any memory pause(function () { if (replayElement) { self.setMp4Source(null); self.setWebMSource(null); } cb && cb(); }); }; this.hide = function () { if (isStandalone()) { (0, _hidden2.default)(parentElement, true); } else { replayElement && (0, _hidden2.default)(replayElement, true); } }; this.isShown = function () { return replayElement && !(0, _hidden2.default)(replayElement); }; this.getParentElement = function () { return parentElement; }; }; _util2.default.inherits(Replay, _eventEmitter2.default); exports.default = Replay; },{"./../../events":88,"./../../util/browser":93,"./../../util/eventEmitter":95,"./../../util/videomailError":100,"add-eventlistener-with-options":1,"hidden":32,"hyperscript":34,"iphone-inline-video":40,"util":80}],115:[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (recorder, options) { _eventEmitter2.default.call(this, options, 'UserMedia'); var rawVisualUserMedia = recorder && recorder.getRawVisualUserMedia(); var browser = new _browser2.default(options); var self = this; var paused = false; var record = false; var audioRecorder; var currentVisualStream; function attachMediaStream(stream) { currentVisualStream = stream; if (typeof rawVisualUserMedia.srcObject !== 'undefined') { rawVisualUserMedia.srcObject = stream; } else if (typeof rawVisualUserMedia.src !== 'undefined') { var URL = window.URL || window.webkitURL; rawVisualUserMedia.src = URL.createObjectURL(stream) || stream; } else { throw _videomailError2.default.create('Error attaching stream to element.', 'Contact the developer about this', options); } } function setVisualStream(localMediaStream) { if (localMediaStream) { attachMediaStream(localMediaStream); } else { rawVisualUserMedia.removeAttribute('srcObject'); rawVisualUserMedia.removeAttribute('src'); currentVisualStream = null; } } function getVisualStream() { if (rawVisualUserMedia.mozSrcObject) { return rawVisualUserMedia.mozSrcObject; } else if (rawVisualUserMedia.srcObject) { return rawVisualUserMedia.srcObject; } else { return currentVisualStream; } } function hasEnded() { if (rawVisualUserMedia.ended) { return rawVisualUserMedia.ended; } else { var visualStream = getVisualStream(); return visualStream && visualStream.ended; } } function hasInvalidDimensions() { if (rawVisualUserMedia.videoWidth && rawVisualUserMedia.videoWidth < 3 || rawVisualUserMedia.height && rawVisualUserMedia.height < 3) { return true; } } function getTracks(localMediaStream) { var tracks; if (localMediaStream && localMediaStream.getTracks) { tracks = localMediaStream.getTracks(); } return tracks; } function getVideoTracks(localMediaStream) { var videoTracks; if (localMediaStream && localMediaStream.getVideoTracks) { videoTracks = localMediaStream.getVideoTracks(); } return videoTracks; } function getFirstVideoTrack(localMediaStream) { var videoTracks = getVideoTracks(localMediaStream); var videoTrack; if (videoTracks && videoTracks[0]) { videoTrack = videoTracks[0]; } return videoTrack; } function logEvent(event, params) { options.debug('UserMedia: ...', EVENT_ASCII, 'event', event, (0, _fastSafeStringify2.default)(params)); } function isPromise(anything) { return anything && typeof Promise !== 'undefined' && anything instanceof Promise; } function outputEvent(e) { logEvent(e.type, { readyState: rawVisualUserMedia.readyState }); // remove myself rawVisualUserMedia.removeEventListener && rawVisualUserMedia.removeEventListener(e.type, outputEvent); } this.unloadRemainingEventListeners = function () { options.debug('UserMedia: unloadRemainingEventListeners()'); _mediaEvents2.default.forEach(function (eventName) { rawVisualUserMedia.removeEventListener(eventName, outputEvent); }); }; this.init = function (localMediaStream, videoCallback, audioCallback, endedEarlyCallback) { this.stop(localMediaStream, true); var onPlayReached = false; var onLoadedMetaDataReached = false; var playingPromiseReached = false; if (options && options.isAudioEnabled()) { audioRecorder = audioRecorder || new _audioRecorder2.default(this, options); } function audioRecord() { self.removeListener(_events2.default.SENDING_FIRST_FRAME, audioRecord); audioRecorder && audioRecorder.record(audioCallback); } function unloadAllEventListeners() { options.debug('UserMedia: unloadAllEventListeners()'); self.removeListener(_events2.default.SENDING_FIRST_FRAME, audioRecord); rawVisualUserMedia.removeEventListener && rawVisualUserMedia.removeEventListener('play', onPlay); rawVisualUserMedia.removeEventListener && rawVisualUserMedia.removeEventListener('loadedmetadata', onLoadedMetaData); self.unloadRemainingEventListeners(); } function play() { // Resets the media element and restarts the media resource. Any pending events are discarded. try { rawVisualUserMedia.load(); // fixes https://github.com/binarykitchen/videomail.io/issues/401 // see https://github.com/MicrosoftEdge/Demos/blob/master/photocapture/scripts/demo.js#L27 if (rawVisualUserMedia.paused) { options.debug('UserMedia: play()', 'media.readyState=' + rawVisualUserMedia.readyState, 'media.paused=' + rawVisualUserMedia.paused, 'media.ended=' + rawVisualUserMedia.ended, 'media.played=' + (0, _pretty2.default)(rawVisualUserMedia.played)); var p; try { p = rawVisualUserMedia.play(); } catch (exc) { // this in the hope to catch InvalidStateError, see // https://github.com/binarykitchen/videomail-client/issues/149 options.logger.warn('Caught raw usermedia play exception:', exc); } // using the promise here just experimental for now // and this to catch any weird errors early if possible if (isPromise(p)) { p.then(function () { if (!playingPromiseReached) { options.debug('UserMedia: play promise successful. Playing now.'); playingPromiseReached = true; } }).catch(function (reason) { // promise can be interrupted, i.E. when switching tabs // and promise can get resumed when switching back to tab, hence // do not treat this like an error options.logger.warn('Caught pending usermedia promise exception: %s', reason.toString()); }); } } } catch (exc) { unloadAllEventListeners(); endedEarlyCallback(exc); } } function fireCallbacks() { var readyState = rawVisualUserMedia.readyState; // ready state, see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState options.debug('UserMedia: fireCallbacks(' + 'readyState=' + readyState + ', ' + 'onPlayReached=' + onPlayReached + ', ' + 'onLoadedMetaDataReached=' + onLoadedMetaDataReached + ')'); if (onPlayReached && onLoadedMetaDataReached) { videoCallback(); if (audioRecorder && audioCallback) { try { audioRecorder.init(localMediaStream); self.on(_events2.default.SENDING_FIRST_FRAME, audioRecord); } catch (exc) { unloadAllEventListeners(); endedEarlyCallback(exc); } } } } function onPlay() { try { logEvent('play', { readyState: rawVisualUserMedia.readyState, audio: options.isAudioEnabled(), width: rawVisualUserMedia.width, height: rawVisualUserMedia.height, videoWidth: rawVisualUserMedia.videoWidth, videoHeight: rawVisualUserMedia.videoHeight }); rawVisualUserMedia.removeEventListener && rawVisualUserMedia.removeEventListener('play', onPlay); if (hasEnded() || hasInvalidDimensions()) { endedEarlyCallback(_videomailError2.default.create('Already busy', 'Probably another browser window is using your webcam?', options)); } else { onPlayReached = true; fireCallbacks(); } } catch (exc) { unloadAllEventListeners(); endedEarlyCallback(exc); } } // player modifications to perform that must wait until `loadedmetadata` has been triggered function onLoadedMetaData() { logEvent('loadedmetadata', { readyState: rawVisualUserMedia.readyState, paused: rawVisualUserMedia.paused, width: rawVisualUserMedia.width, height: rawVisualUserMedia.height, videoWidth: rawVisualUserMedia.videoWidth, videoHeight: rawVisualUserMedia.videoHeight }); rawVisualUserMedia.removeEventListener && rawVisualUserMedia.removeEventListener('loadedmetadata', onLoadedMetaData); if (!hasEnded() && !hasInvalidDimensions()) { self.emit(_events2.default.LOADED_META_DATA); // for android devices, we cannot call play() unless meta data has been loaded! // todo consider removing that if it's not the case anymore (for better performance) if (browser.isAndroid()) { play(); } onLoadedMetaDataReached = true; fireCallbacks(); } } try { var videoTrack = getFirstVideoTrack(localMediaStream); if (!videoTrack) { options.debug('UserMedia: detected (but no video tracks exist'); } else if (!videoTrack.enabled) { throw _videomailError2.default.create('Webcam is disabled', 'The video track seems to be disabled. Enable it in your system.', options); } else { var description; if (videoTrack.label && videoTrack.label.length > 0) { description = videoTrack.label; } description += ' with enabled=' + videoTrack.enabled; description += ', muted=' + videoTrack.muted; description += ', remote=' + videoTrack.remote; description += ', readyState=' + videoTrack.readyState; description += ', error=' + videoTrack.error; options.debug('UserMedia: ' + videoTrack.kind + ' detected.', description || ''); } // very useful i think, so leave this and just use options.debug() var heavyDebugging = true; if (heavyDebugging) { _mediaEvents2.default.forEach(function (eventName) { rawVisualUserMedia.addEventListener(eventName, outputEvent, false); }); } rawVisualUserMedia.addEventListener('loadedmetadata', onLoadedMetaData); rawVisualUserMedia.addEventListener('play', onPlay); // experimental, not sure if this is ever needed/called? since 2 apr 2017 // An error occurs while fetching the media data. // Error can be an object with the code MEDIA_ERR_NETWORK or higher. // networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted. rawVisualUserMedia.addEventListener('error', function (err) { options.logger.warn('Caught video element error event: %s', (0, _pretty2.default)(err)); }); setVisualStream(localMediaStream); play(); } catch (exc) { self.emit(_events2.default.ERROR, exc); } }; this.isReady = function () { return !!rawVisualUserMedia.src; }; this.stop = function (visualStream, aboutToInitialize) { try { // do not stop "too much" when going to initialize anyway if (!aboutToInitialize) { if (!visualStream) { visualStream = getVisualStream(); } var tracks = getTracks(visualStream); var newStopApiFound = false; if (tracks) { tracks.forEach(function (track) { if (track.stop) { newStopApiFound = true; track.stop(); } }); } // will probably become obsolete in one year (after june 2017) !newStopApiFound && visualStream && visualStream.stop && visualStream.stop(); setVisualStream(null); audioRecorder && audioRecorder.stop(); audioRecorder = null; } paused = record = false; } catch (exc) { self.emit(_events2.default.ERROR, exc); } }; this.createCanvas = function () { return (0, _hyperscript2.default)('canvas', { width: this.getRawWidth(true), height: this.getRawHeight(true) }); }; this.getVideoHeight = function () { return rawVisualUserMedia.videoHeight; }; this.getVideoWidth = function () { return rawVisualUserMedia.videoWidth; }; this.hasVideoWidth = function () { return this.getVideoWidth() > 0; }; this.getRawWidth = function (responsive) { var rawWidth = this.getVideoWidth(); var widthDefined = options.hasDefinedWidth(); if (widthDefined || options.hasDefinedHeight()) { if (!responsive && widthDefined) { rawWidth = options.video.width; } else { rawWidth = recorder.calculateWidth(responsive); } } if (responsive) { rawWidth = recorder.limitWidth(rawWidth); } return rawWidth; }; this.getRawHeight = function (responsive) { var rawHeight; if (options.hasDefinedDimension()) { rawHeight = recorder.calculateHeight(responsive); if (rawHeight < 1) { throw _videomailError2.default.create('Bad dimensions', 'Calculated raw height cannot be less than 1!', options); } } else { rawHeight = this.getVideoHeight(); if (rawHeight < 1) { throw _videomailError2.default.create('Bad dimensions', 'Raw video height from DOM element cannot be less than 1!', options); } } if (responsive) { rawHeight = recorder.limitHeight(rawHeight); } return rawHeight; }; this.getRawVisuals = function () { return rawVisualUserMedia; }; this.pause = function () { paused = true; }; this.isPaused = function () { return paused; }; this.resume = function () { paused = false; }; this.record = function () { record = true; }; this.isRecording = function () { return record; }; this.getAudioSampleRate = function () { if (audioRecorder) { return audioRecorder.getSampleRate(); } else { return -1; } }; this.getCharacteristics = function () { return { audioSampleRate: this.getAudioSampleRate(), muted: rawVisualUserMedia && rawVisualUserMedia.muted, width: rawVisualUserMedia && rawVisualUserMedia.width, height: rawVisualUserMedia && rawVisualUserMedia.height, videoWidth: rawVisualUserMedia && rawVisualUserMedia.videoWidth, videoHeight: rawVisualUserMedia && rawVisualUserMedia.videoHeight }; }; }; var _hyperscript = _dereq_('hyperscript'); var _hyperscript2 = _interopRequireDefault(_hyperscript); var _fastSafeStringify = _dereq_('fast-safe-stringify'); var _fastSafeStringify2 = _interopRequireDefault(_fastSafeStringify); var _audioRecorder = _dereq_('./../../util/audioRecorder'); var _audioRecorder2 = _interopRequireDefault(_audioRecorder); var _videomailError = _dereq_('./../../util/videomailError'); var _videomailError2 = _interopRequireDefault(_videomailError); var _eventEmitter = _dereq_('./../../util/eventEmitter'); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); var _mediaEvents = _dereq_('./../../util/mediaEvents'); var _mediaEvents2 = _interopRequireDefault(_mediaEvents); var _pretty = _dereq_('./../../util/pretty'); var _pretty2 = _interopRequireDefault(_pretty); var _browser = _dereq_('./../../util/browser'); var _browser2 = _interopRequireDefault(_browser); var _events = _dereq_('./../../events'); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EVENT_ASCII = '|—O—|'; },{"./../../events":88,"./../../util/audioRecorder":92,"./../../util/browser":93,"./../../util/eventEmitter":95,"./../../util/mediaEvents":97,"./../../util/pretty":98,"./../../util/videomailError":100,"fast-safe-stringify":25,"hyperscript":34}],"videomail-client":[function(_dereq_,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _standardize = _dereq_('./util/standardize'); var _standardize2 = _interopRequireDefault(_standardize); var _client = _dereq_('./client'); var _client2 = _interopRequireDefault(_client); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } if (!navigator) { throw new Error('Navigator is missing!'); } else { // Ensures Videomail functionality is not broken on exotic browsers with shims. (0, _standardize2.default)(window, navigator); } exports.default = _client2.default; // also add that so that we can require() it the normal ES5 way module.exports = _client2.default; },{"./client":86,"./util/standardize":99}]},{},["videomail-client"])("videomail-client") });
ajax/libs/js-data/1.6.2/js-data-debug.js
joeylakay/cdnjs
/*! * js-data * @version 1.6.2 - Homepage <http://www.js-data.io/> * @author Jason Dobry <[email protected]> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else if(typeof define === 'function' && define.amd) define(["bluebird", "js-data-schema"], factory); else if(typeof exports === 'object') exports["JSData"] = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else root["JSData"] = factory(root["bluebird"], root["Schemator"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var DS = _interopRequire(__webpack_require__(3)); module.exports = { DS: DS, createStore: function createStore(options) { return new DS(options); }, DSUtils: DSUtils, DSErrors: DSErrors, version: { full: "1.6.2", major: parseInt("1", 10), minor: parseInt("6", 10), patch: parseInt("2", 10), alpha: true ? "false" : false, beta: true ? "false" : false } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; /* jshint eqeqeq:false */ var DSErrors = _interopRequire(__webpack_require__(2)); var forEach = _interopRequire(__webpack_require__(9)); var slice = _interopRequire(__webpack_require__(10)); var forOwn = _interopRequire(__webpack_require__(14)); var contains = _interopRequire(__webpack_require__(11)); var deepMixIn = _interopRequire(__webpack_require__(15)); var pascalCase = _interopRequire(__webpack_require__(19)); var remove = _interopRequire(__webpack_require__(12)); var pick = _interopRequire(__webpack_require__(16)); var sort = _interopRequire(__webpack_require__(13)); var upperCase = _interopRequire(__webpack_require__(20)); var observe = _interopRequire(__webpack_require__(6)); var es6Promise = _interopRequire(__webpack_require__(21)); var BinaryHeap = _interopRequire(__webpack_require__(22)); var w = undefined, _Promise = undefined; var DSUtils = undefined; var objectProto = Object.prototype; var toString = objectProto.toString; es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == "[object Array]" || false; }; var isRegExp = function (value) { return toString.call(value) == "[object RegExp]" || false; }; // adapted from lodash.isBoolean var isBoolean = function (value) { return value === true || value === false || value && typeof value == "object" && toString.call(value) == "[object Boolean]" || false; }; // adapted from lodash.isString var isString = function (value) { return typeof value == "string" || value && typeof value == "object" && toString.call(value) == "[object String]" || false; }; var isObject = function (value) { return toString.call(value) == "[object Object]" || false; }; // adapted from lodash.isDate var isDate = function (value) { return value && typeof value == "object" && toString.call(value) == "[object Date]" || false; }; // adapted from lodash.isNumber var isNumber = function (value) { var type = typeof value; return type == "number" || value && type == "object" && toString.call(value) == "[object Number]" || false; }; // adapted from lodash.isFunction var isFunction = function (value) { return typeof value == "function" || value && toString.call(value) === "[object Function]" || false; }; // shorthand argument checking functions, using these shaves 1.18 kb off of the minified build var isStringOrNumber = function (value) { return isString(value) || isNumber(value); }; var isStringOrNumberErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be a string or a number!"); }; var isObjectErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an object!"); }; var isArrayErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an array!"); }; // adapted from mout.isEmpty var isEmpty = function (val) { if (val == null) { // jshint ignore:line // typeof null == 'object' so we check it first return true; } else if (typeof val === "string" || isArray(val)) { return !val.length; } else if (typeof val === "object") { var _ret = (function () { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return { v: result }; })(); if (typeof _ret === "object") return _ret.v; } else { return true; } }; var intersection = function (array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item = undefined; for (var i = 0, _length = array1.length; i < _length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; }; var filter = function (array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; }; function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype["finally"]) { w.Promise.prototype["finally"] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = __webpack_require__(4); } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } var toPromisify = ["beforeValidate", "validate", "afterValidate", "beforeCreate", "afterCreate", "beforeUpdate", "afterUpdate", "beforeDestroy", "afterDestroy"]; var isBlacklisted = function (prop, bl) { var i = undefined; if (!bl || !bl.length) { return false; } for (i = 0; i < bl.length; i++) { if (bl[i] === prop) { return true; } } return false; }; // adapted from angular.copy var copy = function (source, destination, stackSource, stackDest, blacklist) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest, blacklist); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest, blacklist); } } } else { if (source === destination) { throw new Error("Cannot copy! Source and destination are identical."); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) { return stackDest[index]; } stackSource.push(source); stackDest.push(destination); } var result = undefined; if (isArray(source)) { var i = undefined; destination.length = 0; for (i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest, blacklist); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { if (isBlacklisted(key, blacklist)) { continue; } result = copy(source[key], null, stackSource, stackDest, blacklist); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; }; // adapted from angular.equals var equals = function (o1, o2) { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == "object") { if (isArray(o1)) { if (!isArray(o2)) { return false; } if ((length = o1.length) == o2.length) { // jshint ignore:line for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) { return false; } } return true; } } else if (isDate(o1)) { if (!isDate(o2)) { return false; } return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) { return false; } keySet = {}; for (key in o1) { if (key.charAt(0) === "$" || isFunction(o1[key])) { continue; } if (!equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== "$" && o2[key] !== undefined && !isFunction(o2[key])) { return false; } } return true; } } } return false; }; var resolveId = function (definition, idOrInstance) { if (isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }; var resolveItem = function (resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }; var isValidString = function (val) { return val != null && val !== ""; // jshint ignore:line }; var join = function (items, separator) { separator = separator || ""; return filter(items, isValidString).join(separator); }; var makePath = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var result = join(args, "/"); return result.replace(/([^:\/]|^)\/{2,}/g, "$1/"); }; DSUtils = { // Options that inherit from defaults _: function _(parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA("\"options\" must be an object!"); } forEach(toPromisify, function (name) { if (typeof options[name] === "function" && options[name].toString().indexOf("for (var _len = arg") === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; O.prototype.orig = function () { var orig = {}; forOwn(this, function (value, key) { orig[key] = value; }); return orig; }; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function compute(fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: contains, copy: copy, deepMixIn: deepMixIn, diffObjectFromOldObject: observe.diffObjectFromOldObject, BinaryHeap: BinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function fromJson(json) { return isString(json) ? JSON.parse(json) : json; }, get: __webpack_require__(17), intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: pascalCase, pick: pick, Promise: _Promise, promisify: function promisify(fn, target) { var _this = this; if (!fn) { return; } else if (typeof fn !== "function") { throw new Error("Can only promisify functions!"); } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new _this.Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: remove, set: __webpack_require__(18), slice: slice, sort: sort, toJson: JSON.stringify, updateTimestamp: function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === "function" ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, upperCase: upperCase, removeCircular: function removeCircular(object) { var objects = []; return (function rmCirc(value) { var i = undefined; var nu = undefined; if (typeof value === "object" && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return undefined; } } objects.push(value); if (DSUtils.isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i]); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k]); }); } return nu; } return value; })(object); }, resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (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) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var IllegalArgumentError = (function (_Error) { function IllegalArgumentError(message) { _classCallCheck(this, IllegalArgumentError); _get(Object.getPrototypeOf(IllegalArgumentError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "Illegal Argument!"; } _inherits(IllegalArgumentError, _Error); return IllegalArgumentError; })(Error); var RuntimeError = (function (_Error2) { function RuntimeError(message) { _classCallCheck(this, RuntimeError); _get(Object.getPrototypeOf(RuntimeError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "RuntimeError Error!"; } _inherits(RuntimeError, _Error2); return RuntimeError; })(Error); var NonexistentResourceError = (function (_Error3) { function NonexistentResourceError(resourceName) { _classCallCheck(this, NonexistentResourceError); _get(Object.getPrototypeOf(NonexistentResourceError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = "" + resourceName + " is not a registered resource!"; } _inherits(NonexistentResourceError, _Error3); return NonexistentResourceError; })(Error); module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /* jshint eqeqeq:false */ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var syncMethods = _interopRequire(__webpack_require__(7)); var asyncMethods = _interopRequire(__webpack_require__(8)); var Schemator = undefined; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(_x, _x2, _x3, _x4) { var _again = true; _function: while (_again) { _again = false; var orderBy = _x, index = _x2, a = _x3, b = _x4; def = cA = cB = undefined; var def = orderBy[index]; var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]); if (DSUtils._s(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils._s(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === "DESC") { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } } } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, { errorFn: { value: function errorFn(a, b) { if (this.error && typeof this.error === "function") { try { if (typeof a === "string") { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } } } }); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ""; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.defaultAdapter = "http"; defaultsPrototype.debug = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ""; defaultsPrototype.error = console ? function (a, b, c) { return console[typeof console.error === "function" ? "error" : "log"](a, b, c); } : false; defaultsPrototype.fallbackAdapters = ["http"]; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.findInverseLinks = true; defaultsPrototype.idAttribute = "id"; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.loadFromServer = false; defaultsPrototype.log = console ? function (a, b, c, d, e) { return console[typeof console.info === "function" ? "info" : "log"](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { var _this = this; if (_this.debug && _this.log && typeof _this.log === "function") { _this.log(_this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.reapAction = !!DSUtils.w ? "inject" : "none"; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = "single"; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var filtered = collection; var where = null; var reserved = { skip: "", offset: "", where: "", limit: "", orderBy: "", sort: "" }; params = params || {}; options = options || {}; if (DSUtils._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { "==": value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils._s(clause)) { clause = { "===": clause }; } else if (DSUtils._n(clause) || DSUtils.isBoolean(clause)) { clause = { "==": clause }; } if (DSUtils._o(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr = undefined; var isOr = op[0] === "|"; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === "==") { expr = val == term; } else if (op === "===") { expr = val === term; } else if (op === "!=") { expr = val != term; } else if (op === "!==") { expr = val !== term; } else if (op === ">") { expr = val > term; } else if (op === ">=") { expr = val >= term; } else if (op === "<") { expr = val < term; } else if (op === "<=") { expr = val <= term; } else if (op === "isectEmpty") { expr = !DSUtils.intersection(val || [], term || []).length; } else if (op === "isectNotEmpty") { expr = DSUtils.intersection(val || [], term || []).length; } else if (op === "in") { if (DSUtils._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === "notIn") { if (DSUtils._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === "contains") { if (DSUtils._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === "notContains") { if (DSUtils._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : isOr ? keep || expr : keep && expr; } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils._s(params.orderBy)) { orderBy = [[params.orderBy, "ASC"]]; } else if (DSUtils._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils._s(params.sort)) { orderBy = [[params.sort, "ASC"]]; } else if (!orderBy && DSUtils._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { (function () { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils._s(def)) { orderBy[i] = [def, "ASC"]; } else if (!DSUtils._a(def)) { throw new DSErrors.IA("DS.filter(\"" + resourceName + "\"[, params][, options]): " + DSUtils.toJson(def) + ": Must be a string or an array!", { params: { "orderBy[i]": { actual: typeof def, expected: "string|array" } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); })(); } var limit = DSUtils._n(params.limit) ? params.limit : null; var skip = null; if (DSUtils._n(params.skip)) { skip = params.skip; } else if (DSUtils._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils._n(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils._n(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; var DS = (function () { function DS(options) { _classCallCheck(this, DS); var _this = this; options = options || {}; try { Schemator = __webpack_require__(5); } catch (e) {} if (!Schemator || typeof Schemator !== "function") { try { Schemator = window.Schemator; } catch (e) {} } Schemator = Schemator || options.schemator; if (typeof Schemator === "function") { _this.schemator = new Schemator(); } _this.store = {}; // alias store, shaves 0.1 kb off the minified build _this.s = _this.store; _this.definitions = {}; // alias definitions, shaves 0.3 kb off the minified build _this.defs = _this.definitions; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = DSUtils.observe; DSUtils.forOwn(options, function (v, k) { _this.defaults[k] = v; }); _this.defaults.logFn("new data store created", _this.defaults); } _createClass(DS, { getAdapter: { value: function getAdapter(options) { var errorIfNotExist = false; options = options || {}; this.defaults.logFn("getAdapter", options); if (DSUtils._s(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error("" + options.adapter + " is not a registered adapter!"); } else { return this.adapters[options.defaultAdapter]; } } }, registerAdapter: { value: function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; _this.defaults.logFn("registerAdapter", name, Adapter, options); if (DSUtils.isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options["default"]) { _this.defaults.defaultAdapter = name; } _this.defaults.logFn("default adapter is " + _this.defaults.defaultAdapter); } }, is: { value: function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } return instance instanceof definition[definition["class"]]; } } }); return DS; })(); var dsPrototype = DS.prototype; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter.shorthand = false; dsPrototype.errors = DSErrors; dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { if(typeof __WEBPACK_EXTERNAL_MODULE_5__ === 'undefined') {var e = new Error("Cannot find module \"undefined\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { var testingExposeCycleCount = global.testingExposeCycleCount; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ return function(fn) { return Promise.resolve().then(fn); } })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } // Export the observe-js object for **Node.js**, with backwards-compatibility // for the old `require()` API. Also ensure `exports` is not a DOM Element. // If we're in the browser, export as a global object. global.Observer = Observer; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.diffObjectFromOldObject = diffObjectFromOldObject; global.ObjectObserver = ObjectObserver; })(exports); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var defineResource = _interopRequire(__webpack_require__(31)); var eject = _interopRequire(__webpack_require__(32)); var ejectAll = _interopRequire(__webpack_require__(33)); var filter = _interopRequire(__webpack_require__(34)); var inject = _interopRequire(__webpack_require__(35)); var link = _interopRequire(__webpack_require__(36)); var linkAll = _interopRequire(__webpack_require__(37)); var linkInverse = _interopRequire(__webpack_require__(38)); var unlinkInverse = _interopRequire(__webpack_require__(39)); var NER = DSErrors.NER; var IA = DSErrors.IA; var R = DSErrors.R; function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } module.exports = { changes: function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("changes", id, options); var item = _this.get(resourceName, id); if (item) { var _ret = (function () { if (DSUtils.w) { _this.s[resourceName].observers[id].deliver(); } var ignoredChanges = options.ignoredChanges || []; DSUtils.forEach(definition.relationFields, function (field) { return ignoredChanges.push(field); }); var diff = DSUtils.diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], DSUtils.equals, ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return { v: diff }; })(); if (typeof _ret === "object") { return _ret.v; } } }, changeHistory: function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("changeHistory", id); if (!definition.keepChangeHistory) { definition.errorFn("changeHistory is disabled for this resource!"); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } }, compute: function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = DSUtils.resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R("Item not in the store!"); } else if (!DSUtils._o(instance) && !DSUtils._sn(instance)) { throw new IA("\"instance\" must be an object, string or number!"); } definition.logFn("compute", instance); DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; }, createInstance: function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item = undefined; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA("\"attrs\" must be an object!"); } options = DSUtils._(definition, options); options.logFn("createInstance", attrs, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition["class"]]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, item); } return item; }, defineResource: defineResource, digest: function digest() { this.observe.Platform.performMicrotaskCheckpoint(); }, eject: eject, ejectAll: ejectAll, filter: filter, get: function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("get", id, options); // cache miss, request resource from server var item = _this.s[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; }, getAll: function getAll(resourceName, ids) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !DSUtils._a(ids)) { throw DSUtils._aErr("ids"); } definition.logFn("getAll", ids); if (DSUtils._a(ids)) { var _length = ids.length; for (var i = 0; i < _length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; }, hasChanges: function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("hasChanges", id); // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } }, inject: inject, lastModified: function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn("lastModified", id); if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; }, lastSaved: function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn("lastSaved", id); if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; }, link: link, linkAll: linkAll, linkInverse: linkInverse, previous: function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("previous", id); // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; }, unlinkInverse: unlinkInverse }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var create = _interopRequire(__webpack_require__(40)); var destroy = _interopRequire(__webpack_require__(41)); var destroyAll = _interopRequire(__webpack_require__(42)); var find = _interopRequire(__webpack_require__(43)); var findAll = _interopRequire(__webpack_require__(44)); var loadRelations = _interopRequire(__webpack_require__(45)); var reap = _interopRequire(__webpack_require__(46)); var save = _interopRequire(__webpack_require__(47)); var update = _interopRequire(__webpack_require__(48)); var updateAll = _interopRequire(__webpack_require__(49)); module.exports = { create: create, destroy: destroy, destroyAll: destroyAll, find: find, findAll: findAll, loadRelations: loadRelations, reap: reap, refresh: function refresh(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.defs[resourceName]; id = DSUtils.resolveId(_this.defs[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.bypassCache = true; options.logFn("refresh", id, options); resolve(_this.get(resourceName, id)); } }).then(function (item) { return item ? _this.find(resourceName, id, options) : item; }); }, save: save, update: update, updateAll: updateAll }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(23); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(23); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(24); var forIn = __webpack_require__(25); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var forOwn = __webpack_require__(14); var isPlainObject = __webpack_require__(26); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var slice = __webpack_require__(10); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isPrimitive = __webpack_require__(27); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var namespace = __webpack_require__(28); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); var camelCase = __webpack_require__(30); var upperCase = __webpack_require__(20); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(51)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(50), (function() { return this; }()), __webpack_require__(52)(module))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /*! * yabh * @version 1.0.0 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <[email protected]> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["BinaryHeap"] = factory(); else root["BinaryHeap"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var _parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(_parent)) { break; } else { heap[parentN] = element; heap[n] = _parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ var bubbleDown = function (heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } }; var BinaryHeap = (function () { function BinaryHeap(weightFunc, compareFunc) { _classCallCheck(this, BinaryHeap); if (!weightFunc) { weightFunc = function (x) { return x; }; } if (!compareFunc) { compareFunc = function (x, y) { return x === y; }; } if (typeof weightFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"weightFunc\" must be a function!"); } if (typeof compareFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"compareFunc\" must be a function!"); } this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } _createClass(BinaryHeap, { push: { value: function push(node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); } }, peek: { value: function peek() { return this.heap[0]; } }, pop: { value: function pop() { var front = this.heap[0]; var end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; } }, remove: { value: function remove(node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; } }, removeAll: { value: function removeAll() { this.heap = []; } }, size: { value: function size() { return this.heap.length; } } }); return BinaryHeap; })(); module.exports = BinaryHeap; /***/ } /******/ ]) }); ; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(24); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var forEach = __webpack_require__(9); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); var replaceAccents = __webpack_require__(53); var removeNonWord = __webpack_require__(54); var upperCase = __webpack_require__(20); var lowerCase = __webpack_require__(55); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; module.exports = defineResource; /*jshint evil:true, loopfunc:true*/ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var Resource = function Resource(options) { _classCallCheck(this, Resource); DSUtils.deepMixIn(this, options); if ("endpoint" in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } }; var instanceMethods = ["compute", "refresh", "save", "update", "destroy", "loadRelations", "changeHistory", "changes", "hasChanges", "lastModified", "lastSaved", "link", "linkInverse", "previous", "unlinkInverse"]; function defineResource(definition) { var _this = this; var definitions = _this.defs; if (DSUtils._s(definition)) { definition = { name: definition.replace(/\s/gi, "") }; } if (!DSUtils._o(definition)) { throw DSUtils._oErr("definition"); } else if (!DSUtils._s(definition.name)) { throw new DSErrors.IA("\"name\" must be a string!"); } else if (_this.s[definition.name]) { throw new DSErrors.R("" + definition.name + " is already registered!"); } try { var def; var _class; var _ret = (function () { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); def = definitions[definition.name]; // alias name, shaves 0.08 kb off the minified build def.n = def.name; def.logFn("Preparing resource."); if (!DSUtils._s(def.idAttribute)) { throw new DSErrors.IA("\"idAttribute\" must be a string!"); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils._a(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.n; def.relationList.push(d); if (d.localField) { def.relationFields.push(d.localField); } }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === "function") { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.defs[resourceName]; }; def.getEndpoint = function (id, options) { options.params = options.params || {}; var item = undefined; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty("endpoint") ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils._sn(id)) { item = def.get(id); } else if (DSUtils._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { var _ret2 = (function () { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return { v: DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint) }; })(); if (typeof _ret2 === "object") return _ret2.v; } else { return endpoint; } } }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource _class = def["class"] = DSUtils.pascalCase(def.name); try { if (typeof def.useClass === "function") { eval("function " + _class + "() { def.useClass.call(this); }"); def[_class] = eval(_class); def[_class].prototype = (function (proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval("function " + _class + "() {}"); def[_class] = eval(_class); } } catch (e) { def[_class] = function () {}; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[_class].prototype, def.methods); } def[_class].prototype.set = function (key, value) { DSUtils.set(this, key, value); var observer = _this.s[def.n].observers[this[def.idAttribute]]; if (observer && !DSUtils.observe.hasObjectObserve) { observer.deliver(); } else { _this.compute(def.n, this); } return this; }; def[_class].prototype.get = function (key) { return DSUtils.get(this, key); }; // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn("Computed property \"" + field + "\" conflicts with previously defined prototype method!"); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(","); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn("Use the computed property array syntax for compatibility with minified code!"); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.n, definition.schema); if (!definition.hasOwnProperty("validate")) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[_class].prototype["DS" + DSUtils.pascalCase(name)] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this[def.idAttribute] || this); args.unshift(def.n); return _this[name].apply(_this, args); }; }); def[_class].prototype.DSCreate = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this); args.unshift(def.n); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.n] = { collection: [], expiresHeap: new DSUtils.BinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { return _this.reap(def.n, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones var fns = ["registerAdapter", "getAdapter", "is"]; for (key in _this) { if (typeof _this[key] === "function") { fns.push(key); } } DSUtils.forEach(fns, function (key) { var k = key; if (_this[k].shorthand !== false) { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(def.n); return _this[k].apply(_this, args); }; } else { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _this[k].apply(_this, args); }; } }); def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); var defaultAdapter = undefined; if (def.hasOwnProperty("defaultAdapter")) { defaultAdapter = def.defaultAdapter; } DSUtils.forOwn(def.actions, function (action, name) { if (def[name] && !def.actions[name]) { throw new Error("Cannot override existing method \"" + name + "\"!"); } def[name] = function (options) { options = options || {}; var adapter = _this.getAdapter(action.adapter || defaultAdapter || "http"); var config = DSUtils.deepMixIn({}, action); if (!options.hasOwnProperty("endpoint") && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === "function") { config.url = options.getEndpoint(def, options); } else { config.url = DSUtils.makePath(options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(null, options), name); } config.method = config.method || "GET"; DSUtils.deepMixIn(config, options); return adapter.HTTP(config); }; }); // Mix-in events DSUtils.Events(def); def.logFn("Done preparing resource."); return { v: def }; })(); if (typeof _ret === "object") return _ret.v; } catch (err) { delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { module.exports = eject; function eject(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("eject", id, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { // jshint ignore:line item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { var _ret = (function () { if (options.notify) { definition.beforeEject(options, item); definition.emit("DS.beforeEject", definition, item); } _this.unlinkInverse(definition.n, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } if (!items.length) { toRemove.push(queryHash); } }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); definition.emit("DS.afterEject", definition, item); } return { v: item }; })(); if (typeof _ret === "object") { return _ret.v; } } } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { module.exports = ejectAll; function ejectAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr("params"); } definition.logFn("ejectAll", params, options); var resource = _this.s[resourceName]; var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.n, params); var ids = []; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } else { delete resource.completedQueries[queryHash]; } DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.n, id, options); }); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { module.exports = filter; function filter(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; if (!definition) { throw new _this.errors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr("params"); } // Protect against null params = params || {}; options = DSUtils._(definition, options); options.logFn("filter", params, options); var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; module.exports = inject; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); function _getReactFunction(DS, definition, resource) { var name = definition.n; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item = undefined; var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { definition.errorFn("Doh! You just changed the primary key of an object! Your data for the \"" + name + "\" resource is now in an undefined (probably broken) state."); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected = undefined; if (DSUtils._a(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { (function () { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); })(); } if (!(idA in attrs)) { var error = new DSErrors.R("" + definition.n + ".inject: \"attrs\" must contain the property specified by \"idAttribute\"!"); options.errorFn(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.defs[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R("" + definition.n + " relation is defined but the resource is not!"); } if (DSUtils._a(toInject)) { (function () { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName].index[toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options.orig()); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } }); attrs[def.localField] = items; })(); } else { if (toInject !== _this.s[relationName].index[toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options.orig()); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } } } }); var id = attrs[idA]; var item = _this.get(definition.n, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition["class"]]) { item = attrs; } else { item = new definition[definition["class"]](); } } else { item = {}; } DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); resource.previousAttributes[id] = DSUtils.copy(item, null, null, null, definition.relationFields); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(item, null, null, null, definition.relationFields); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); var timestamp = new Date().getTime(); resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === "belongsTo" && injected[definition.idAttribute]) { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } else if (options.findHasMany && def.type === "hasMany" || options.findHasOne && def.type === "hasOne") { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected = undefined; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._o(attrs) && !DSUtils._a(attrs)) { throw new DSErrors.IA("" + resourceName + ".inject: \"attrs\" must be an object or an array!"); } var name = definition.n; options = DSUtils._(definition, options); options.logFn("inject", attrs, options); if (options.notify) { options.beforeInject(options, attrs); definition.emit("DS.beforeInject", definition, attrs); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils._a(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); definition.emit("DS.afterInject", definition, injected); } return injected; } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { module.exports = link; function link(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("link", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName) || !def.localField) { return; } var params = {}; if (def.type === "belongsTo") { var _parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (_parent) { linked[def.localField] = _parent; } } else if (def.type === "hasMany") { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === "hasOne") { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkAll; function linkAll(resourceName, params, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("linkAll", params, relations); var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName) || !def.localField) { return; } if (def.type === "belongsTo") { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === "hasMany") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === "hasOne") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkInverse; function linkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("linkInverse", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.n)) { return; } if (definition.n === relationName) { _this.linkAll(d.n, {}, [definition.n]); } }); }); }); } return linked; } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { module.exports = unlinkInverse; function unlinkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("unlinkInverse", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.n === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.s[def.name].collection, function (item) { if (def.type === "hasMany" && item[def.localField]) { (function () { var index = undefined; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); if (index !== undefined) { item[def.localField].splice(index, 1); } })(); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { module.exports = create; function create(resourceName, attrs, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError = undefined; if (!definition) { rejectionError = new _this.errors.NER(resourceName); } else if (!DSUtils._o(attrs)) { rejectionError = DSUtils._oErr("attrs"); } else { options = DSUtils._(definition, options); if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } options.logFn("create", attrs, options); } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeCreate", definition, attrs); } return _this.getAdapter(options).create(definition, attrs, options); }).then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterCreate", definition, attrs); } if (options.cacheResponse) { var created = _this.inject(definition.n, attrs, options.orig()); var id = created[definition.idAttribute]; var resource = _this.s[resourceName]; resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroy; function destroy(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var item = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); options.logFn("destroy", id, options); resolve(item); } }).then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeDestroy", definition, attrs); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }).then(function () { return options.afterDestroy.call(item, options, item); }).then(function (item) { if (options.notify) { definition.emit("DS.afterDestroy", definition, item); } _this.eject(resourceName, id); return id; })["catch"](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } return DSUtils.Promise.reject(err); }); } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroyAll; function destroyAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var ejected = undefined, toEject = undefined; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("attrs")); } else { options = DSUtils._(definition, options); options.logFn("destroyAll", params, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.beforeDestroy", definition, toEject); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.afterDestroy", definition, toEject); } return ejected || _this.ejectAll(resourceName, params); })["catch"](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } return DSUtils.Promise.reject(err); }); } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /* jshint -W082 */ module.exports = find; function find(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.logFn("find", id, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries && _this.get(resourceName, id)) { resolve(_this.get(resourceName, id)); } else { delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise = undefined; var strategy = options.findStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { var injected = _this.inject(resourceName, data, options.orig()); resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return injected; } else { return _this.createInstance(resourceName, data, options.orig()); } }); } return resource.pendingQueries[id]; } else { return item; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[id]; } return DSUtils.Promise.reject(err); }); } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { module.exports = findAll; /* jshint -W082 */ function processResults(data, resourceName, queryHash, options) { var _this = this; var DSUtils = _this.utils; var resource = _this.s[resourceName]; var idAttribute = _this.defs[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options.orig()); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item) { var id = item[idAttribute]; if (id) { resource.completedQueries[id] = date; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); } } }); } else { options.errorFn("response is expected to be an array!"); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash = undefined; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("params")); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); options.logFn("findAll", params, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { resolve(_this.filter(resourceName, params, options.orig())); } else { resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise = undefined; var strategy = options.findAllStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options.orig()); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } return DSUtils.Promise.reject(err); }); } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { module.exports = loadRelations; function loadRelations(resourceName, instance, relations, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils._s(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(instance)) { reject(new DSErrors.IA("\"instance(id)\" must be a string, number or object!")); } else if (!DSUtils._a(relations)) { reject(new DSErrors.IA("\"relations\" must be a string or an array!")); } else { (function () { var _options = DSUtils._(definition, options); if (!_options.hasOwnProperty("findBelongsTo")) { _options.findBelongsTo = true; } if (!_options.hasOwnProperty("findHasMany")) { _options.findHasMany = true; } _options.logFn("loadRelations", instance, relations, _options); var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); if (DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task = undefined; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { "==": instance[definition.idAttribute] }; } if (def.type === "hasMany" && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()); } else if (def.type === "hasOne") { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], __options.orig()); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField || false); } } }); resolve(tasks); })(); } }).then(function (tasks) { return DSUtils.Promise.all(tasks); }).then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { if (field) { instance[field] = loadedRelations[index]; } }); return instance; }); } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { module.exports = reap; function reap(resourceName, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty("notify")) { options.notify = false; } options.logFn("reap", options); var items = []; var now = new Date().getTime(); var expiredItem = undefined; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); definition.emit("DS.beforeReap", definition, items); } if (options.reapAction === "inject") { (function () { var timestamp = new Date().getTime(); DSUtils.forEach(items, function (item) { resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); }); })(); } else if (options.reapAction === "eject") { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === "refresh") { var _ret2 = (function () { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return { v: DSUtils.Promise.all(tasks) }; })(); if (typeof _ret2 === "object") return _ret2.v; } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); definition.emit("DS.afterReap", definition, items); } return items; }); } /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { module.exports = save; function save(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var item = undefined; var noChanges = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R("id \"" + id + "\" not found in cache!")); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); options.logFn("save", id, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } if (options.changesOnly) { var resource = _this.s[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return options.logFn("save - no changes", id, options); noChanges = true; return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (noChanges) { return attrs; } else if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { module.exports = update; function update(resourceName, id, attrs, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.logFn("update", id, attrs, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected, null, null, null, definition.relationFields); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { module.exports = updateAll; function updateAll(resourceName, attrs, params, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); options.logFn("updateAll", attrs, params, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (data) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } var origOptions = options.orig(); if (options.cacheResponse) { var _ret = (function () { var injected = _this.inject(definition.n, data, origOptions); var resource = _this.s[resourceName]; DSUtils.forEach(injected, function (i) { var id = i[definition.idAttribute]; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(i, null, null, null, definition.relationFields); } }); return { v: injected }; })(); if (typeof _ret === "object") return _ret.v; } else { var _ret2 = (function () { var instances = []; DSUtils.forEach(data, function (item) { instances.push(_this.createInstance(resourceName, item, origOptions)); }); return { v: instances }; })(); if (typeof _ret2 === "object") return _ret2.v; } }); } /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; /***/ } /******/ ]) });
app/app.js
patrykomiotek/seo-monitor-front
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import 'sanitize.css/sanitize.css'; import injectTapEventPlugin from 'react-tap-event-plugin'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; import theme from './theme'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; injectTapEventPlugin(); const render = (messages) => { ReactDOM.render( <MuiThemeProvider muiTheme={theme}> <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider> </MuiThemeProvider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/Parser/Druid/Restoration/Modules/Features/Lifebloom.js
hasseboulen/WoWAnalyzer
import React from 'react'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import ItemLink from 'common/ItemLink'; import Wrapper from 'common/Wrapper'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; class Lifebloom extends Analyzer { static dependencies = { combatants: Combatants, }; hasDta; on_initialized() { this.hasDta = this.combatants.selected.hasWaist(ITEMS.THE_DARK_TITANS_ADVICE.id); } get uptime() { return Object.keys(this.combatants.players) .map(key => this.combatants.players[key]) .reduce((uptime, player) => uptime + player.getBuffUptime(SPELLS.LIFEBLOOM_HOT_HEAL.id), 0); } get uptimePercent() { return this.uptime / this.owner.fightDuration; } // "The Dark Titan's Advice" legendary buffs Lifebloom, making high uptime more important get suggestionThresholds() { if (this.hasDta) { return { actual: this.uptimePercent, isLessThan: { minor: 0.90, average: 0.80, major: 0.70, }, style: 'percentage', }; } else { return { actual: this.uptimePercent, isLessThan: { minor: 0.80, average: 0.60, major: 0.40, }, style: 'percentage', }; } } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your <SpellLink id={SPELLS.LIFEBLOOM_HOT_HEAL.id} /> uptime can be improved. {this.hasDta ? <Wrapper>High uptime is particularly important for taking advantage of your equipped <ItemLink id={ITEMS.THE_DARK_TITANS_ADVICE.id} icon /></Wrapper> : ''}</Wrapper>) .icon(SPELLS.LIFEBLOOM_HOT_HEAL.icon) .actual(`${formatPercentage(this.uptimePercent)}% uptime`) .recommended(`>${Math.round(formatPercentage(recommended))}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.LIFEBLOOM_HOT_HEAL.id} />} value={`${formatPercentage(this.uptimePercent)} %`} label="Lifebloom Uptime" /> ); } statisticOrder = STATISTIC_ORDER.CORE(10); } export default Lifebloom;
client2/src/components/react-burger-menu/test/slide.spec.js
gdomorski/CodeOut
'use strict'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { expect } from 'chai'; import createShallowComponent from './utils/createShallowComponent'; import BurgerMenu from '../lib/BurgerMenu'; const Menu = BurgerMenu.slide; describe('slide', () => { let component; beforeEach(() => { component = TestUtils.renderIntoDocument(<Menu><div>An item</div></Menu>); }); it('has correct menuWrap styles', () => { component = createShallowComponent(<Menu><div>An item</div></Menu>); const menuWrap = component.props.children[1]; expect(menuWrap.props.style.position).to.equal('fixed'); expect(menuWrap.props.style.zIndex).to.equal(2); expect(menuWrap.props.style.width).to.equal(300); expect(menuWrap.props.style.height).to.equal('100%'); }); it('has correct menu styles', () => { const menu = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu'); expect(menu.style.height).to.equal('100%'); expect(menu.style.boxSizing).to.equal('border-box'); }); it('has correct itemList styles', () => { const itemList = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-item-list'); expect(itemList.style.height).to.equal('100%'); }); it('has correct item styles', () => { const firstItem = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-item-list').children[0]; expect(firstItem.style.display).to.equal('block'); expect(firstItem.style.outline).to.equal('none'); }); it('can be positioned on the right', () => { component = TestUtils.renderIntoDocument(<Menu right><div>An item</div></Menu>); const menuWrap = TestUtils.findRenderedDOMComponentWithClass(component, 'bm-menu-wrap'); expect(menuWrap.style.right).to.equal('0px'); }); });
browser/app/js/components/ObjectsList.js
luomeiqin/minio
/* * Minio Cloud Storage (C) 2016 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react' import Moment from 'moment' import humanize from 'humanize' import connect from 'react-redux/lib/components/connect' import Dropdown from 'react-bootstrap/lib/Dropdown' let ObjectsList = ({objects, currentPath, selectPrefix, dataType, showDeleteConfirmation, shareObject, loadPath, checkObject, checkedObjectsArray}) => { const list = objects.map((object, i) => { let size = object.name.endsWith('/') ? '-' : humanize.filesize(object.size) let lastModified = object.name.endsWith('/') ? '-' : Moment(object.lastModified).format('lll') let loadingClass = loadPath === `${currentPath}${object.name}` ? 'fesl-loading' : '' let actionButtons = '' let deleteButton = '' if (web.LoggedIn()) deleteButton = <a href="" className="fiad-action" onClick={ (e) => showDeleteConfirmation(e, `${currentPath}${object.name}`) }><i className="fa fa-trash"></i></a> if (!checkedObjectsArray.length > 0) { if (!object.name.endsWith('/')) { actionButtons = <Dropdown id={ "fia-dropdown-" + object.name.replace('.', '-') }> <Dropdown.Toggle noCaret className="fia-toggle"></Dropdown.Toggle> <Dropdown.Menu> <a href="" className="fiad-action" onClick={ (e) => shareObject(e, `${currentPath}${object.name}`) }><i className="fa fa-copy"></i></a> { deleteButton } </Dropdown.Menu> </Dropdown> } } let activeClass = '' let isChecked = '' if (checkedObjectsArray.indexOf(object.name) > -1) { activeClass = ' fesl-row-selected' isChecked = true } return ( <div key={ i } className={ "fesl-row " + loadingClass + activeClass } data-type={ dataType(object.name, object.contentType) }> <div className="fesl-item fesl-item-icon"> <div className="fi-select"> <input type="checkbox" name={ object.name } checked={ isChecked } onChange={ (e) => checkObject(e, object.name) } /> <i className="fis-icon"></i> <i className="fis-helper"></i> </div> </div> <div className="fesl-item fesl-item-name"> <a href="" onClick={ (e) => selectPrefix(e, `${currentPath}${object.name}`) }> { object.name } </a> </div> <div className="fesl-item fesl-item-size"> { size } </div> <div className="fesl-item fesl-item-modified"> { lastModified } </div> <div className="fesl-item fesl-item-actions"> { actionButtons } </div> </div> ) }) return ( <div> { list } </div> ) } // Subscribe it to state changes. export default connect(state => { return { objects: state.objects, currentPath: state.currentPath, loadPath: state.loadPath } })(ObjectsList)
packages/react-error-overlay/src/containers/StackFrameCodeBlock.js
TryKickoff/create-kickoff-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import CodeBlock from '../components/CodeBlock'; import { applyStyles } from '../utils/dom/css'; import { absolutifyCaret } from '../utils/dom/absolutifyCaret'; import type { ScriptLine } from '../utils/stack-frame'; import { primaryErrorStyle, secondaryErrorStyle } from '../styles'; import generateAnsiHTML from '../utils/generateAnsiHTML'; import codeFrame from 'babel-code-frame'; type StackFrameCodeBlockPropsType = {| lines: ScriptLine[], lineNum: number, columnNum: ?number, contextSize: number, main: boolean, |}; // Exact type workaround for spread operator. // See: https://github.com/facebook/flow/issues/2405 type Exact<T> = $Shape<T>; function StackFrameCodeBlock(props: Exact<StackFrameCodeBlockPropsType>) { const { lines, lineNum, columnNum, contextSize, main } = props; const sourceCode = []; let whiteSpace = Infinity; lines.forEach(function(e) { const { content: text } = e; const m = text.match(/^\s*/); if (text === '') { return; } if (m && m[0]) { whiteSpace = Math.min(whiteSpace, m[0].length); } else { whiteSpace = 0; } }); lines.forEach(function(e) { let { content: text } = e; const { lineNumber: line } = e; if (isFinite(whiteSpace)) { text = text.substring(whiteSpace); } sourceCode[line - 1] = text; }); const ansiHighlight = codeFrame( sourceCode.join('\n'), lineNum, columnNum == null ? 0 : columnNum - (isFinite(whiteSpace) ? whiteSpace : 0), { forceColor: true, linesAbove: contextSize, linesBelow: contextSize, } ); const htmlHighlight = generateAnsiHTML(ansiHighlight); const code = document.createElement('code'); code.innerHTML = htmlHighlight; absolutifyCaret(code); const ccn = code.childNodes; // eslint-disable-next-line oLoop: for (let index = 0; index < ccn.length; ++index) { const node = ccn[index]; const ccn2 = node.childNodes; for (let index2 = 0; index2 < ccn2.length; ++index2) { const lineNode = ccn2[index2]; const text = lineNode.innerText; if (text == null) { continue; } if (text.indexOf(' ' + lineNum + ' |') === -1) { continue; } // $FlowFixMe applyStyles(node, main ? primaryErrorStyle : secondaryErrorStyle); // eslint-disable-next-line break oLoop; } } return <CodeBlock main={main} codeHTML={code.innerHTML} />; } export default StackFrameCodeBlock;
example/examples/BugMarkerWontUpdate.js
amitv87/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, Dimensions, TouchableOpacity, } from 'react-native'; import MapView from 'react-native-maps'; import MyLocationMapMarker from './MyLocationMapMarker'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; class BugMarkerWontUpdate extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, coordinate: { latitude: LATITUDE, longitude: LONGITUDE, }, amount: 0, enableHack: false, }; } increment() { this.setState({ amount: this.state.amount + 10 }); } decrement() { this.setState({ amount: this.state.amount - 10 }); } toggleHack() { this.setState({ enableHack: !this.state.enableHack }); } render() { return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={this.state.region} > <MyLocationMapMarker coordinate={this.state.coordinate} heading={this.state.amount} enableHack={this.state.enableHack} /> </MapView> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => this.toggleHack()} style={[styles.bubble, styles.button, styles.hackButton]} > <Text style={{ fontSize: 12, fontWeight: 'bold' }}> {this.state.enableHack ? 'Disable Hack' : 'Enable Hack'} </Text> </TouchableOpacity> </View> <View style={styles.buttonContainer}> <TouchableOpacity onPress={() => this.decrement()} style={[styles.bubble, styles.button]} > <Text style={{ fontSize: 20, fontWeight: 'bold' }}>-</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.increment()} style={[styles.bubble, styles.button]} > <Text style={{ fontSize: 20, fontWeight: 'bold' }}>+</Text> </TouchableOpacity> </View> </View> ); } } BugMarkerWontUpdate.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, bubble: { backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, latlng: { width: 200, alignItems: 'stretch', }, button: { width: 80, paddingHorizontal: 12, alignItems: 'center', marginHorizontal: 10, }, hackButton: { width: 200, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, }); module.exports = BugMarkerWontUpdate;
definitions/npm/styled-components_v2.x.x/flow_v0.25.x-v0.41.x/test_styled-components_v2.x.x.js
mwalkerwells/flow-typed
// @flow import {renderToString} from 'react-dom/server' import styled, {ThemeProvider, withTheme, keyframes, ServerStyleSheet, StyleSheetManager} from 'styled-components' import React from 'react' import type {Theme} from 'styled-components' const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; const ExtendedTitle = styled(Title)` font-size: 2em; ` const Wrapper = styled.section` padding: 4em; background: ${({theme}) => theme.background}; `; const theme: Theme = { background: "papayawhip" } const Component = () => ( <ThemeProvider theme={theme}> <Wrapper> <Title>Hello World, this is my first styled component!</Title> </Wrapper> </ThemeProvider> ) const ComponentWithTheme = withTheme(Component) const Component2 = () => ( <ThemeProvider theme={outerTheme => outerTheme}> <Wrapper> <Title>Hello World, this is my first styled component!</Title> </Wrapper> </ThemeProvider> ) const OpacityKeyFrame = keyframes` 0% { opacity: 0; } 100% { opacity: 1; } `; // $ExpectError const NoExistingElementWrapper = styled.nonexisting` padding: 4em; background: papayawhip; `; const num = 9 // $ExpectError const NoExistingComponentWrapper = styled()` padding: 4em; background: papayawhip; `; // $ExpectError const NumberWrapper = styled(num)` padding: 4em; background: papayawhip; `; const sheet = new ServerStyleSheet() const html = renderToString(sheet.collectStyles(<Component />)) const css = sheet.getStyleTags() const sheet2 = new ServerStyleSheet() const html2 = renderToString( <StyleSheetManager sheet={sheet}> <Component /> </StyleSheetManager> ) const css2 = sheet.getStyleTags() const css3 = sheet.getStyleElement() class TestReactClass extends React.Component { render() { return <div />; } } const StyledClass = styled(TestReactClass)` color: red; `;
node_modules/react-bootstrap/es/ButtonGroup.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 all from 'react-prop-types/lib/all'; import Button from './Button'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { vertical: React.PropTypes.bool, justified: React.PropTypes.bool, /** * Display block buttons; only useful when used with the "vertical" prop. * @type {bool} */ block: all(React.PropTypes.bool, function (_ref) { var block = _ref.block; var vertical = _ref.vertical; return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null; }) }; var defaultProps = { block: false, justified: false, vertical: false }; var ButtonGroup = function (_React$Component) { _inherits(ButtonGroup, _React$Component); function ButtonGroup() { _classCallCheck(this, ButtonGroup); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ButtonGroup.prototype.render = function render() { var _extends2; var _props = this.props; var block = _props.block; var justified = _props.justified; var vertical = _props.vertical; var className = _props.className; var props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2)); return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return ButtonGroup; }(React.Component); ButtonGroup.propTypes = propTypes; ButtonGroup.defaultProps = defaultProps; export default bsClass('btn-group', ButtonGroup);
ajax/libs/react-chartjs-2/1.0.0/react-chartjs-2.min.js
joeyparrish/cdnjs
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Chart=t()}}(function(){var t;return function e(t,i,s){function a(n,r){if(!i[n]){if(!t[n]){var h="function"==typeof require&&require;if(!r&&h)return h(n,!0);if(o)return o(n,!0);var l=new Error("Cannot find module '"+n+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[n]={exports:{}};t[n][0].call(c.exports,function(e){var i=t[n][1][e];return a(i?i:e)},c,c.exports,e,t,i,s)}return i[n].exports}for(var o="function"==typeof require&&require,n=0;n<s.length;n++)a(s[n]);return a}({1:[function(t,e,i){var s=t("./core/core.js")();t("./core/core.helpers")(s),t("./core/core.element")(s),t("./core/core.animation")(s),t("./core/core.controller")(s),t("./core/core.datasetController")(s),t("./core/core.layoutService")(s),t("./core/core.legend")(s),t("./core/core.plugin.js")(s),t("./core/core.scale")(s),t("./core/core.scaleService")(s),t("./core/core.title")(s),t("./core/core.tooltip")(s),t("./controllers/controller.bar")(s),t("./controllers/controller.bubble")(s),t("./controllers/controller.doughnut")(s),t("./controllers/controller.line")(s),t("./controllers/controller.polarArea")(s),t("./controllers/controller.radar")(s),t("./scales/scale.category")(s),t("./scales/scale.linear")(s),t("./scales/scale.logarithmic")(s),t("./scales/scale.radialLinear")(s),t("./scales/scale.time")(s),t("./elements/element.arc")(s),t("./elements/element.line")(s),t("./elements/element.point")(s),t("./elements/element.rectangle")(s),t("./charts/Chart.Bar")(s),t("./charts/Chart.Bubble")(s),t("./charts/Chart.Doughnut")(s),t("./charts/Chart.Line")(s),t("./charts/Chart.PolarArea")(s),t("./charts/Chart.Radar")(s),t("./charts/Chart.Scatter")(s),window.Chart=e.exports=s},{"./charts/Chart.Bar":2,"./charts/Chart.Bubble":3,"./charts/Chart.Doughnut":4,"./charts/Chart.Line":5,"./charts/Chart.PolarArea":6,"./charts/Chart.Radar":7,"./charts/Chart.Scatter":8,"./controllers/controller.bar":9,"./controllers/controller.bubble":10,"./controllers/controller.doughnut":11,"./controllers/controller.line":12,"./controllers/controller.polarArea":13,"./controllers/controller.radar":14,"./core/core.animation":15,"./core/core.controller":16,"./core/core.datasetController":17,"./core/core.element":18,"./core/core.helpers":19,"./core/core.js":20,"./core/core.layoutService":21,"./core/core.legend":22,"./core/core.plugin.js":23,"./core/core.scale":24,"./core/core.scaleService":25,"./core/core.title":26,"./core/core.tooltip":27,"./elements/element.arc":28,"./elements/element.line":29,"./elements/element.point":30,"./elements/element.rectangle":31,"./scales/scale.category":32,"./scales/scale.linear":33,"./scales/scale.logarithmic":34,"./scales/scale.radialLinear":35,"./scales/scale.time":36}],2:[function(t,e,i){"use strict";e.exports=function(t){t.Bar=function(e,i){return i.type="bar",new t(e,i)}}},{}],3:[function(t,e,i){"use strict";e.exports=function(t){t.Bubble=function(e,i){return i.type="bubble",new t(e,i)}}},{}],4:[function(t,e,i){"use strict";e.exports=function(t){t.Doughnut=function(e,i){return i.type="doughnut",new t(e,i)}}},{}],5:[function(t,e,i){"use strict";e.exports=function(t){t.Line=function(e,i){return i.type="line",new t(e,i)}}},{}],6:[function(t,e,i){"use strict";e.exports=function(t){t.PolarArea=function(e,i){return i.type="polarArea",new t(e,i)}}},{}],7:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers,i={aspectRatio:1};t.Radar=function(s,a){return a.options=e.configMerge(i,a.options),a.type="radar",new t(s,a)}}},{}],8:[function(t,e,i){"use strict";e.exports=function(t){var e={hover:{mode:"single"},scales:{xAxes:[{type:"linear",position:"bottom",id:"x-axis-1"}],yAxes:[{type:"linear",position:"left",id:"y-axis-1"}]},tooltips:{callbacks:{title:function(t,e){return""},label:function(t,e){return"("+t.xLabel+", "+t.yLabel+")"}}}};t.defaults.scatter=e,t.controllers.scatter=t.controllers.line,t.Scatter=function(e,i){return i.type="scatter",new t(e,i)}}},{}],9:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.bar={hover:{mode:"label"},scales:{xAxes:[{type:"category",categoryPercentage:.8,barPercentage:.9,gridLines:{offsetGridLines:!0}}],yAxes:[{type:"linear"}]}},t.controllers.bar=t.DatasetController.extend({initialize:function(e,i){t.DatasetController.prototype.initialize.call(this,e,i),this.getMeta().bar=!0},getBarCount:function(){var t=0;return e.each(this.chart.data.datasets,function(e,i){var s=this.chart.getDatasetMeta(i);s.bar&&this.chart.isDatasetVisible(i)&&++t},this),t},addElements:function(){var i=this.getMeta();e.each(this.getDataset().data,function(e,s){i.data[s]=i.data[s]||new t.elements.Rectangle({_chart:this.chart.chart,_datasetIndex:this.index,_index:s})},this)},addElementAndReset:function(e){var i=new t.elements.Rectangle({_chart:this.chart.chart,_datasetIndex:this.index,_index:e}),s=this.getBarCount();this.getMeta().data.splice(e,0,i),this.updateElement(i,e,!0,s)},update:function(t){var i=this.getBarCount();e.each(this.getMeta().data,function(e,s){this.updateElement(e,s,t,i)},this)},updateElement:function(t,i,s,a){var o,n=this.getMeta(),r=this.getScaleForId(n.xAxisID),h=this.getScaleForId(n.yAxisID);o=h.min<0&&h.max<0?h.getPixelForValue(h.max):h.min>0&&h.max>0?h.getPixelForValue(h.min):h.getPixelForValue(0),e.extend(t,{_chart:this.chart.chart,_xScale:r,_yScale:h,_datasetIndex:this.index,_index:i,_model:{x:this.calculateBarX(i,this.index),y:s?o:this.calculateBarY(i,this.index),label:this.chart.data.labels[i],datasetLabel:this.getDataset().label,base:s?o:this.calculateBarBase(this.index,i),width:this.calculateBarWidth(a),backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.rectangle.backgroundColor),borderSkipped:t.custom&&t.custom.borderSkipped?t.custom.borderSkipped:this.chart.options.elements.rectangle.borderSkipped,borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.rectangle.borderColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.rectangle.borderWidth)}}),t.pivot()},calculateBarBase:function(t,e){var i=this.getMeta(),s=(this.getScaleForId(i.xAxisID),this.getScaleForId(i.yAxisID)),a=0;if(s.options.stacked){var o=this.chart.data.datasets[t].data[e];if(0>o)for(var n=0;t>n;n++){var r=this.chart.data.datasets[n],h=this.chart.getDatasetMeta(n);h.bar&&h.yAxisID===s.id&&this.chart.isDatasetVisible(n)&&(a+=r.data[e]<0?r.data[e]:0)}else for(var l=0;t>l;l++){var c=this.chart.data.datasets[l],d=this.chart.getDatasetMeta(l);d.bar&&d.yAxisID===s.id&&this.chart.isDatasetVisible(l)&&(a+=c.data[e]>0?c.data[e]:0)}return s.getPixelForValue(a)}return a=s.getPixelForValue(s.min),s.beginAtZero||s.min<=0&&s.max>=0||s.min>=0&&s.max<=0?a=s.getPixelForValue(0,0):s.min<0&&s.max<0&&(a=s.getPixelForValue(s.max)),a},getRuler:function(){var t=this.getMeta(),e=this.getScaleForId(t.xAxisID),i=(this.getScaleForId(t.yAxisID),this.getBarCount()),s=function(){for(var t=e.getPixelForTick(1)-e.getPixelForTick(0),i=2;i<this.getDataset().data.length;i++)t=Math.min(e.getPixelForTick(i)-e.getPixelForTick(i-1),t);return t}.call(this),a=s*e.options.categoryPercentage,o=(s-s*e.options.categoryPercentage)/2,n=a/i;if(e.ticks.length!==this.chart.data.labels.length){var r=e.ticks.length/this.chart.data.labels.length;n*=r}var h=n*e.options.barPercentage,l=n-n*e.options.barPercentage;return{datasetCount:i,tickWidth:s,categoryWidth:a,categorySpacing:o,fullBarWidth:n,barWidth:h,barSpacing:l}},calculateBarWidth:function(){var t=this.getScaleForId(this.getMeta().xAxisID),e=this.getRuler();return t.options.stacked?e.categoryWidth:e.barWidth},getBarIndex:function(t){var e,i,s=0;for(i=0;t>i;++i)e=this.chart.getDatasetMeta(i),e.bar&&this.chart.isDatasetVisible(i)&&++s;return s},calculateBarX:function(t,e){var i=this.getMeta(),s=(this.getScaleForId(i.yAxisID),this.getScaleForId(i.xAxisID)),a=this.getBarIndex(e),o=this.getRuler(),n=s.getPixelForValue(null,t,e,this.chart.isCombo);return n-=this.chart.isCombo?o.tickWidth/2:0,s.options.stacked?n+o.categoryWidth/2+o.categorySpacing:n+o.barWidth/2+o.categorySpacing+o.barWidth*a+o.barSpacing/2+o.barSpacing*a},calculateBarY:function(t,e){var i=this.getMeta(),s=(this.getScaleForId(i.xAxisID),this.getScaleForId(i.yAxisID)),a=this.getDataset().data[t];if(s.options.stacked){for(var o=0,n=0,r=0;e>r;r++){var h=this.chart.data.datasets[r],l=this.chart.getDatasetMeta(r);l.bar&&l.yAxisID===s.id&&this.chart.isDatasetVisible(r)&&(h.data[t]<0?n+=h.data[t]||0:o+=h.data[t]||0)}return 0>a?s.getPixelForValue(n+a):s.getPixelForValue(o+a)}return s.getPixelForValue(a)},draw:function(t){var i=t||1;e.each(this.getMeta().data,function(t,e){var s=this.getDataset().data[e];null===s||void 0===s||isNaN(s)||t.transition(i).draw()},this)},setHoverStyle:function(t){var i=this.chart.data.datasets[t._datasetIndex],s=t._index;t._model.backgroundColor=t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(i.hoverBackgroundColor,s,e.color(t._model.backgroundColor).saturate(.5).darken(.1).rgbString()),t._model.borderColor=t.custom&&t.custom.hoverBorderColor?t.custom.hoverBorderColor:e.getValueAtIndexOrDefault(i.hoverBorderColor,s,e.color(t._model.borderColor).saturate(.5).darken(.1).rgbString()),t._model.borderWidth=t.custom&&t.custom.hoverBorderWidth?t.custom.hoverBorderWidth:e.getValueAtIndexOrDefault(i.hoverBorderWidth,s,t._model.borderWidth)},removeHoverStyle:function(t){var i=(this.chart.data.datasets[t._datasetIndex],t._index);t._model.backgroundColor=t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.rectangle.backgroundColor),t._model.borderColor=t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.rectangle.borderColor),t._model.borderWidth=t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.rectangle.borderWidth)}}),t.defaults.horizontalBar={hover:{mode:"label"},scales:{xAxes:[{type:"linear",position:"bottom"}],yAxes:[{position:"left",type:"category",categoryPercentage:.8,barPercentage:.9,gridLines:{offsetGridLines:!0}}]}},t.controllers.horizontalBar=t.controllers.bar.extend({updateElement:function(t,i,s,a){var o,n=this.getMeta(),r=this.getScaleForId(n.xAxisID),h=this.getScaleForId(n.yAxisID);o=r.min<0&&r.max<0?r.getPixelForValue(r.max):r.min>0&&r.max>0?r.getPixelForValue(r.min):r.getPixelForValue(0),e.extend(t,{_chart:this.chart.chart,_xScale:r,_yScale:h,_datasetIndex:this.index,_index:i,_model:{x:s?o:this.calculateBarX(i,this.index),y:this.calculateBarY(i,this.index),label:this.chart.data.labels[i],datasetLabel:this.getDataset().label,base:s?o:this.calculateBarBase(this.index,i),height:this.calculateBarHeight(a),backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.rectangle.backgroundColor),borderSkipped:t.custom&&t.custom.borderSkipped?t.custom.borderSkipped:this.chart.options.elements.rectangle.borderSkipped,borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.rectangle.borderColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.rectangle.borderWidth)},draw:function(){function t(t){return h[(c+t)%4]}var e=this._chart.ctx,i=this._view,s=i.height/2,a=i.y-s,o=i.y+s,n=i.base-(i.base-i.x),r=i.borderWidth/2;i.borderWidth&&(a+=r,o-=r,n+=r),e.beginPath(),e.fillStyle=i.backgroundColor,e.strokeStyle=i.borderColor,e.lineWidth=i.borderWidth;var h=[[i.base,o],[i.base,a],[n,a],[n,o]],l=["bottom","left","top","right"],c=l.indexOf(i.borderSkipped,0);-1===c&&(c=0),e.moveTo.apply(e,t(0));for(var d=1;4>d;d++)e.lineTo.apply(e,t(d));e.fill(),i.borderWidth&&e.stroke()},inRange:function(t,e){var i=this._view,s=!1;return i&&(s=i.x<i.base?e>=i.y-i.height/2&&e<=i.y+i.height/2&&t>=i.x&&t<=i.base:e>=i.y-i.height/2&&e<=i.y+i.height/2&&t>=i.base&&t<=i.x),s}}),t.pivot()},calculateBarBase:function(t,e){var i=this.getMeta(),s=this.getScaleForId(i.xAxisID),a=(this.getScaleForId(i.yAxisID),0);if(s.options.stacked){var o=this.chart.data.datasets[t].data[e];if(0>o)for(var n=0;t>n;n++){var r=this.chart.data.datasets[n],h=this.chart.getDatasetMeta(n);h.bar&&h.xAxisID===s.id&&this.chart.isDatasetVisible(n)&&(a+=r.data[e]<0?r.data[e]:0)}else for(var l=0;t>l;l++){var c=this.chart.data.datasets[l],d=this.chart.getDatasetMeta(l);d.bar&&d.xAxisID===s.id&&this.chart.isDatasetVisible(l)&&(a+=c.data[e]>0?c.data[e]:0)}return s.getPixelForValue(a)}return a=s.getPixelForValue(s.min),s.beginAtZero||s.min<=0&&s.max>=0||s.min>=0&&s.max<=0?a=s.getPixelForValue(0,0):s.min<0&&s.max<0&&(a=s.getPixelForValue(s.max)),a},getRuler:function(){var t=this.getMeta(),e=(this.getScaleForId(t.xAxisID),this.getScaleForId(t.yAxisID)),i=this.getBarCount(),s=function(){for(var t=e.getPixelForTick(1)-e.getPixelForTick(0),i=2;i<this.getDataset().data.length;i++)t=Math.min(e.getPixelForTick(i)-e.getPixelForTick(i-1),t);return t}.call(this),a=s*e.options.categoryPercentage,o=(s-s*e.options.categoryPercentage)/2,n=a/i;if(e.ticks.length!==this.chart.data.labels.length){var r=e.ticks.length/this.chart.data.labels.length;n*=r}var h=n*e.options.barPercentage,l=n-n*e.options.barPercentage;return{datasetCount:i,tickHeight:s,categoryHeight:a,categorySpacing:o,fullBarHeight:n,barHeight:h,barSpacing:l}},calculateBarHeight:function(){var t=this.getScaleForId(this.getMeta().yAxisID),e=this.getRuler();return t.options.stacked?e.categoryHeight:e.barHeight},calculateBarX:function(t,e){var i=this.getMeta(),s=this.getScaleForId(i.xAxisID),a=(this.getScaleForId(i.yAxisID),this.getDataset().data[t]);if(s.options.stacked){for(var o=0,n=0,r=0;e>r;r++){var h=this.chart.data.datasets[r],l=this.chart.getDatasetMeta(r);l.bar&&l.xAxisID===s.id&&this.chart.isDatasetVisible(r)&&(h.data[t]<0?n+=h.data[t]||0:o+=h.data[t]||0)}return 0>a?s.getPixelForValue(n+a):s.getPixelForValue(o+a)}return s.getPixelForValue(a)},calculateBarY:function(t,e){var i=this.getMeta(),s=this.getScaleForId(i.yAxisID),a=(this.getScaleForId(i.xAxisID),this.getBarIndex(e)),o=this.getRuler(),n=s.getPixelForValue(null,t,e,this.chart.isCombo);return n-=this.chart.isCombo?o.tickHeight/2:0,s.options.stacked?n+o.categoryHeight/2+o.categorySpacing:n+o.barHeight/2+o.categorySpacing+o.barHeight*a+o.barSpacing/2+o.barSpacing*a}})}},{}],10:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.bubble={hover:{mode:"single"},scales:{xAxes:[{type:"linear",position:"bottom",id:"x-axis-0"}],yAxes:[{type:"linear",position:"left",id:"y-axis-0"}]},tooltips:{callbacks:{title:function(t,e){return""},label:function(t,e){var i=e.datasets[t.datasetIndex].label||"",s=e.datasets[t.datasetIndex].data[t.index];return i+": ("+s.x+", "+s.y+", "+s.r+")"}}}},t.controllers.bubble=t.DatasetController.extend({addElements:function(){var i=this.getMeta();e.each(this.getDataset().data,function(e,s){i.data[s]=i.data[s]||new t.elements.Point({_chart:this.chart.chart,_datasetIndex:this.index,_index:s})},this)},addElementAndReset:function(e){var i=new t.elements.Point({_chart:this.chart.chart,_datasetIndex:this.index,_index:e});this.getMeta().data.splice(e,0,i),this.updateElement(i,e,!0)},update:function(t){var i,s=this.getMeta(),a=s.data,o=this.getScaleForId(s.yAxisID);this.getScaleForId(s.xAxisID);i=o.min<0&&o.max<0?o.getPixelForValue(o.max):o.min>0&&o.max>0?o.getPixelForValue(o.min):o.getPixelForValue(0),e.each(a,function(e,i){this.updateElement(e,i,t)},this)},updateElement:function(t,i,s){var a,o=this.getMeta(),n=this.getScaleForId(o.yAxisID),r=this.getScaleForId(o.xAxisID);a=n.min<0&&n.max<0?n.getPixelForValue(n.max):n.min>0&&n.max>0?n.getPixelForValue(n.min):n.getPixelForValue(0),e.extend(t,{_chart:this.chart.chart,_xScale:r,_yScale:n,_datasetIndex:this.index,_index:i,_model:{x:s?r.getPixelForDecimal(.5):r.getPixelForValue(this.getDataset().data[i],i,this.index,this.chart.isCombo),y:s?a:n.getPixelForValue(this.getDataset().data[i],i,this.index),radius:s?0:t.custom&&t.custom.radius?t.custom.radius:this.getRadius(this.getDataset().data[i]),backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.point.backgroundColor),borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.point.borderColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.point.borderWidth),hitRadius:t.custom&&t.custom.hitRadius?t.custom.hitRadius:e.getValueAtIndexOrDefault(this.getDataset().hitRadius,i,this.chart.options.elements.point.hitRadius)}}),t._model.skip=t.custom&&t.custom.skip?t.custom.skip:isNaN(t._model.x)||isNaN(t._model.y),t.pivot()},getRadius:function(t){return t.r||this.chart.options.elements.point.radius},draw:function(t){var i=t||1;e.each(this.getMeta().data,function(t,e){t.transition(i),t.draw()})},setHoverStyle:function(t){var i=this.chart.data.datasets[t._datasetIndex],s=t._index;t._model.radius=t.custom&&t.custom.hoverRadius?t.custom.hoverRadius:e.getValueAtIndexOrDefault(i.hoverRadius,s,this.chart.options.elements.point.hoverRadius)+this.getRadius(this.getDataset().data[t._index]),t._model.backgroundColor=t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(i.hoverBackgroundColor,s,e.color(t._model.backgroundColor).saturate(.5).darken(.1).rgbString()),t._model.borderColor=t.custom&&t.custom.hoverBorderColor?t.custom.hoverBorderColor:e.getValueAtIndexOrDefault(i.hoverBorderColor,s,e.color(t._model.borderColor).saturate(.5).darken(.1).rgbString()),t._model.borderWidth=t.custom&&t.custom.hoverBorderWidth?t.custom.hoverBorderWidth:e.getValueAtIndexOrDefault(i.hoverBorderWidth,s,t._model.borderWidth)},removeHoverStyle:function(t){var i=(this.chart.data.datasets[t._datasetIndex],t._index);t._model.radius=t.custom&&t.custom.radius?t.custom.radius:this.getRadius(this.getDataset().data[t._index]),t._model.backgroundColor=t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.point.backgroundColor),t._model.borderColor=t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.point.borderColor),t._model.borderWidth=t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.point.borderWidth)}})}},{}],11:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.doughnut={animation:{animateRotate:!0,animateScale:!1},aspectRatio:1,hover:{mode:"single"},legendCallback:function(t){var e=[];if(e.push('<ul class="'+t.id+'-legend">'),t.data.datasets.length)for(var i=0;i<t.data.datasets[0].data.length;++i)e.push('<li><span style="background-color:'+t.data.datasets[0].backgroundColor[i]+'"></span>'),t.data.labels[i]&&e.push(t.data.labels[i]),e.push("</li>");return e.push("</ul>"),e.join("")},legend:{labels:{generateLabels:function(t){var i=t.data;return i.labels.length&&i.datasets.length?i.labels.map(function(s,a){var o=t.getDatasetMeta(0),n=i.datasets[0],r=o.data[a],h=r.custom&&r.custom.backgroundColor?r.custom.backgroundColor:e.getValueAtIndexOrDefault(n.backgroundColor,a,this.chart.options.elements.arc.backgroundColor),l=r.custom&&r.custom.borderColor?r.custom.borderColor:e.getValueAtIndexOrDefault(n.borderColor,a,this.chart.options.elements.arc.borderColor),c=r.custom&&r.custom.borderWidth?r.custom.borderWidth:e.getValueAtIndexOrDefault(n.borderWidth,a,this.chart.options.elements.arc.borderWidth);return{text:s,fillStyle:h,strokeStyle:l,lineWidth:c,hidden:isNaN(n.data[a])||o.data[a].hidden,index:a}},this):[]}},onClick:function(t,e){var i,s,a,o=e.index,n=this.chart;for(i=0,s=(n.data.datasets||[]).length;s>i;++i)a=n.getDatasetMeta(i),a.data[o].hidden=!a.data[o].hidden;n.update()}},cutoutPercentage:50,rotation:Math.PI*-.5,circumference:2*Math.PI,tooltips:{callbacks:{title:function(){return""},label:function(t,e){return e.labels[t.index]+": "+e.datasets[t.datasetIndex].data[t.index]}}}},t.defaults.pie=e.clone(t.defaults.doughnut),e.extend(t.defaults.pie,{cutoutPercentage:0}),t.controllers.doughnut=t.controllers.pie=t.DatasetController.extend({linkScales:function(){},addElements:function(){var i=this.getMeta();e.each(this.getDataset().data,function(e,s){i.data[s]=i.data[s]||new t.elements.Arc({_chart:this.chart.chart,_datasetIndex:this.index,_index:s})},this)},addElementAndReset:function(i,s){var a=new t.elements.Arc({_chart:this.chart.chart,_datasetIndex:this.index,_index:i});s&&e.isArray(this.getDataset().backgroundColor)&&this.getDataset().backgroundColor.splice(i,0,s),this.getMeta().data.splice(i,0,a),this.updateElement(a,i,!0)},getRingIndex:function(t){for(var e=0,i=0;t>i;++i)this.chart.isDatasetVisible(i)&&++e;return e},update:function(t){var i=this.chart.chartArea.right-this.chart.chartArea.left-this.chart.options.elements.arc.borderWidth,s=this.chart.chartArea.bottom-this.chart.chartArea.top-this.chart.options.elements.arc.borderWidth,a=Math.min(i,s),o={x:0,y:0};if(this.chart.options.circumference<2*Math.PI){var n=this.chart.options.rotation%(2*Math.PI);n+=2*Math.PI*(n>=Math.PI?-1:n<-Math.PI?1:0);var r=n+this.chart.options.circumference,h={x:Math.cos(n),y:Math.sin(n)},l={x:Math.cos(r),y:Math.sin(r)},c=0>=n&&r>=0||n<=2*Math.PI&&2*Math.PI<=r,d=n<=.5*Math.PI&&.5*Math.PI<=r||n<=2.5*Math.PI&&2.5*Math.PI<=r,u=n<=-Math.PI&&-Math.PI<=r||n<=Math.PI&&Math.PI<=r,f=n<=.5*-Math.PI&&.5*-Math.PI<=r||n<=1.5*Math.PI&&1.5*Math.PI<=r,g=this.chart.options.cutoutPercentage/100,m={x:u?-1:Math.min(h.x*(h.x<0?1:g),l.x*(l.x<0?1:g)),y:f?-1:Math.min(h.y*(h.y<0?1:g),l.y*(l.y<0?1:g))},p={x:c?1:Math.max(h.x*(h.x>0?1:g),l.x*(l.x>0?1:g)),y:d?1:Math.max(h.y*(h.y>0?1:g),l.y*(l.y>0?1:g))},b={width:.5*(p.x-m.x),height:.5*(p.y-m.y)};a=Math.min(i/b.width,s/b.height),o={x:(p.x+m.x)*-.5,y:(p.y+m.y)*-.5}}this.chart.outerRadius=Math.max(a/2,0),this.chart.innerRadius=Math.max(this.chart.options.cutoutPercentage?this.chart.outerRadius/100*this.chart.options.cutoutPercentage:1,0),this.chart.radiusLength=(this.chart.outerRadius-this.chart.innerRadius)/this.chart.getVisibleDatasetCount(),this.chart.offsetX=o.x*this.chart.outerRadius,this.chart.offsetY=o.y*this.chart.outerRadius,this.getMeta().total=this.calculateTotal(),this.outerRadius=this.chart.outerRadius-this.chart.radiusLength*this.getRingIndex(this.index),this.innerRadius=this.outerRadius-this.chart.radiusLength,e.each(this.getMeta().data,function(e,i){this.updateElement(e,i,t)},this)},updateElement:function(t,i,s){var a=(this.chart.chartArea.left+this.chart.chartArea.right)/2,o=(this.chart.chartArea.top+this.chart.chartArea.bottom)/2,n=this.chart.options.rotation,r=this.chart.options.rotation,h=s&&this.chart.options.animation.animateRotate?0:t.hidden?0:this.calculateCircumference(this.getDataset().data[i])*(this.chart.options.circumference/(2*Math.PI)),l=s&&this.chart.options.animation.animateScale?0:this.innerRadius,c=s&&this.chart.options.animation.animateScale?0:this.outerRadius;e.extend(t,{_chart:this.chart.chart,_datasetIndex:this.index,_index:i,_model:{x:a+this.chart.offsetX,y:o+this.chart.offsetY,startAngle:n,endAngle:r,circumference:h,outerRadius:c,innerRadius:l,backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.arc.backgroundColor),hoverBackgroundColor:t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(this.getDataset().hoverBackgroundColor,i,this.chart.options.elements.arc.hoverBackgroundColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.arc.borderWidth),borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.arc.borderColor),label:e.getValueAtIndexOrDefault(this.getDataset().label,i,this.chart.data.labels[i])}}),s&&this.chart.options.animation.animateRotate||(0===i?t._model.startAngle=this.chart.options.rotation:t._model.startAngle=this.getMeta().data[i-1]._model.endAngle,t._model.endAngle=t._model.startAngle+t._model.circumference),t.pivot()},draw:function(t){var i=t||1;e.each(this.getMeta().data,function(t,e){t.transition(i).draw()})},setHoverStyle:function(t){var i=this.chart.data.datasets[t._datasetIndex],s=t._index;t._model.backgroundColor=t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(i.hoverBackgroundColor,s,e.color(t._model.backgroundColor).saturate(.5).darken(.1).rgbString()),t._model.borderColor=t.custom&&t.custom.hoverBorderColor?t.custom.hoverBorderColor:e.getValueAtIndexOrDefault(i.hoverBorderColor,s,e.color(t._model.borderColor).saturate(.5).darken(.1).rgbString()),t._model.borderWidth=t.custom&&t.custom.hoverBorderWidth?t.custom.hoverBorderWidth:e.getValueAtIndexOrDefault(i.hoverBorderWidth,s,t._model.borderWidth)},removeHoverStyle:function(t){var i=(this.chart.data.datasets[t._datasetIndex],t._index);t._model.backgroundColor=t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.arc.backgroundColor),t._model.borderColor=t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.arc.borderColor),t._model.borderWidth=t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.arc.borderWidth)},calculateTotal:function(){var t,i=this.getDataset(),s=this.getMeta(),a=0;return e.each(s.data,function(e,s){t=i.data[s],isNaN(t)||e.hidden||(a+=Math.abs(t))}),a},calculateCircumference:function(t){var e=this.getMeta().total;return e>0&&!isNaN(t)?2*Math.PI*(t/e):0}})}},{}],12:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.line={showLines:!0,hover:{mode:"label"},scales:{xAxes:[{type:"category",id:"x-axis-0"}],yAxes:[{type:"linear",id:"y-axis-0"}]}},t.controllers.line=t.DatasetController.extend({addElements:function(){var i=this.getMeta();i.dataset=i.dataset||new t.elements.Line({_chart:this.chart.chart,_datasetIndex:this.index,_points:i.data}),e.each(this.getDataset().data,function(e,s){i.data[s]=i.data[s]||new t.elements.Point({_chart:this.chart.chart,_datasetIndex:this.index,_index:s})},this)},addElementAndReset:function(e){var i=new t.elements.Point({_chart:this.chart.chart,_datasetIndex:this.index,_index:e});this.getMeta().data.splice(e,0,i),this.updateElement(i,e,!0),this.chart.options.showLines&&0!==this.chart.options.elements.line.tension&&this.updateBezierControlPoints()},update:function(t){var i,s=this.getMeta(),a=s.dataset,o=s.data,n=this.getScaleForId(s.yAxisID);this.getScaleForId(s.xAxisID);i=n.min<0&&n.max<0?n.getPixelForValue(n.max):n.min>0&&n.max>0?n.getPixelForValue(n.min):n.getPixelForValue(0),this.chart.options.showLines&&(a._scale=n,a._datasetIndex=this.index,a._children=o,void 0!==this.getDataset().tension&&void 0===this.getDataset().lineTension&&(this.getDataset().lineTension=this.getDataset().tension),a._model={tension:a.custom&&a.custom.tension?a.custom.tension:e.getValueOrDefault(this.getDataset().lineTension,this.chart.options.elements.line.tension),backgroundColor:a.custom&&a.custom.backgroundColor?a.custom.backgroundColor:this.getDataset().backgroundColor||this.chart.options.elements.line.backgroundColor,borderWidth:a.custom&&a.custom.borderWidth?a.custom.borderWidth:this.getDataset().borderWidth||this.chart.options.elements.line.borderWidth,borderColor:a.custom&&a.custom.borderColor?a.custom.borderColor:this.getDataset().borderColor||this.chart.options.elements.line.borderColor,borderCapStyle:a.custom&&a.custom.borderCapStyle?a.custom.borderCapStyle:this.getDataset().borderCapStyle||this.chart.options.elements.line.borderCapStyle,borderDash:a.custom&&a.custom.borderDash?a.custom.borderDash:this.getDataset().borderDash||this.chart.options.elements.line.borderDash,borderDashOffset:a.custom&&a.custom.borderDashOffset?a.custom.borderDashOffset:this.getDataset().borderDashOffset||this.chart.options.elements.line.borderDashOffset,borderJoinStyle:a.custom&&a.custom.borderJoinStyle?a.custom.borderJoinStyle:this.getDataset().borderJoinStyle||this.chart.options.elements.line.borderJoinStyle,fill:a.custom&&a.custom.fill?a.custom.fill:void 0!==this.getDataset().fill?this.getDataset().fill:this.chart.options.elements.line.fill,scaleTop:n.top,scaleBottom:n.bottom,scaleZero:i},a.pivot()),e.each(o,function(e,i){this.updateElement(e,i,t)},this),this.chart.options.showLines&&0!==this.chart.options.elements.line.tension&&this.updateBezierControlPoints()},getPointBackgroundColor:function(t,i){var s=this.chart.options.elements.point.backgroundColor,a=this.getDataset();return t.custom&&t.custom.backgroundColor?s=t.custom.backgroundColor:a.pointBackgroundColor?s=e.getValueAtIndexOrDefault(a.pointBackgroundColor,i,s):a.backgroundColor&&(s=a.backgroundColor),s},getPointBorderColor:function(t,i){var s=this.chart.options.elements.point.borderColor,a=this.getDataset();return t.custom&&t.custom.borderColor?s=t.custom.borderColor:a.pointBorderColor?s=e.getValueAtIndexOrDefault(this.getDataset().pointBorderColor,i,s):a.borderColor&&(s=a.borderColor),s},getPointBorderWidth:function(t,i){var s=this.chart.options.elements.point.borderWidth,a=this.getDataset();return t.custom&&void 0!==t.custom.borderWidth?s=t.custom.borderWidth:void 0!==a.pointBorderWidth?s=e.getValueAtIndexOrDefault(a.pointBorderWidth,i,s):void 0!==a.borderWidth&&(s=a.borderWidth),s},updateElement:function(t,i,s){var a,o=this.getMeta(),n=this.getScaleForId(o.yAxisID),r=this.getScaleForId(o.xAxisID);a=n.min<0&&n.max<0?n.getPixelForValue(n.max):n.min>0&&n.max>0?n.getPixelForValue(n.min):n.getPixelForValue(0),t._chart=this.chart.chart,t._xScale=r,t._yScale=n,t._datasetIndex=this.index,t._index=i,void 0!==this.getDataset().radius&&void 0===this.getDataset().pointRadius&&(this.getDataset().pointRadius=this.getDataset().radius),void 0!==this.getDataset().hitRadius&&void 0===this.getDataset().pointHitRadius&&(this.getDataset().pointHitRadius=this.getDataset().hitRadius),t._model={x:r.getPixelForValue(this.getDataset().data[i],i,this.index,this.chart.isCombo),y:s?a:this.calculatePointY(this.getDataset().data[i],i,this.index,this.chart.isCombo),radius:t.custom&&t.custom.radius?t.custom.radius:e.getValueAtIndexOrDefault(this.getDataset().pointRadius,i,this.chart.options.elements.point.radius),pointStyle:t.custom&&t.custom.pointStyle?t.custom.pointStyle:e.getValueAtIndexOrDefault(this.getDataset().pointStyle,i,this.chart.options.elements.point.pointStyle),backgroundColor:this.getPointBackgroundColor(t,i),borderColor:this.getPointBorderColor(t,i),borderWidth:this.getPointBorderWidth(t,i),hitRadius:t.custom&&t.custom.hitRadius?t.custom.hitRadius:e.getValueAtIndexOrDefault(this.getDataset().pointHitRadius,i,this.chart.options.elements.point.hitRadius) },t._model.skip=t.custom&&t.custom.skip?t.custom.skip:isNaN(t._model.x)||isNaN(t._model.y)},calculatePointY:function(t,e,i,s){var a=this.getMeta(),o=(this.getScaleForId(a.xAxisID),this.getScaleForId(a.yAxisID));if(o.options.stacked){for(var n=0,r=0,h=0;i>h;h++){var l=this.chart.data.datasets[h],c=this.chart.getDatasetMeta(h);"line"===c.type&&this.chart.isDatasetVisible(h)&&(l.data[e]<0?r+=l.data[e]||0:n+=l.data[e]||0)}return 0>t?o.getPixelForValue(r+t):o.getPixelForValue(n+t)}return o.getPixelForValue(t)},updateBezierControlPoints:function(){var t=this.getMeta();e.each(t.data,function(i,s){var a=e.splineCurve(e.previousItem(t.data,s)._model,i._model,e.nextItem(t.data,s)._model,t.dataset._model.tension);i._model.controlPointPreviousX=Math.max(Math.min(a.previous.x,this.chart.chartArea.right),this.chart.chartArea.left),i._model.controlPointPreviousY=Math.max(Math.min(a.previous.y,this.chart.chartArea.bottom),this.chart.chartArea.top),i._model.controlPointNextX=Math.max(Math.min(a.next.x,this.chart.chartArea.right),this.chart.chartArea.left),i._model.controlPointNextY=Math.max(Math.min(a.next.y,this.chart.chartArea.bottom),this.chart.chartArea.top),i.pivot()},this)},draw:function(t){var i=this.getMeta(),s=t||1;e.each(i.data,function(t){t.transition(s)}),this.chart.options.showLines&&i.dataset.transition(s).draw(),e.each(i.data,function(t){t.draw()})},setHoverStyle:function(t){var i=this.chart.data.datasets[t._datasetIndex],s=t._index;t._model.radius=t.custom&&t.custom.hoverRadius?t.custom.hoverRadius:e.getValueAtIndexOrDefault(i.pointHoverRadius,s,this.chart.options.elements.point.hoverRadius),t._model.backgroundColor=t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(i.pointHoverBackgroundColor,s,e.color(t._model.backgroundColor).saturate(.5).darken(.1).rgbString()),t._model.borderColor=t.custom&&t.custom.hoverBorderColor?t.custom.hoverBorderColor:e.getValueAtIndexOrDefault(i.pointHoverBorderColor,s,e.color(t._model.borderColor).saturate(.5).darken(.1).rgbString()),t._model.borderWidth=t.custom&&t.custom.hoverBorderWidth?t.custom.hoverBorderWidth:e.getValueAtIndexOrDefault(i.pointHoverBorderWidth,s,t._model.borderWidth)},removeHoverStyle:function(t){var i=(this.chart.data.datasets[t._datasetIndex],t._index);void 0!==this.getDataset().radius&&void 0===this.getDataset().pointRadius&&(this.getDataset().pointRadius=this.getDataset().radius),t._model.radius=t.custom&&t.custom.radius?t.custom.radius:e.getValueAtIndexOrDefault(this.getDataset().pointRadius,i,this.chart.options.elements.point.radius),t._model.backgroundColor=this.getPointBackgroundColor(t,i),t._model.borderColor=this.getPointBorderColor(t,i),t._model.borderWidth=this.getPointBorderWidth(t,i)}})}},{}],13:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.polarArea={scale:{type:"radialLinear",lineArc:!0},animation:{animateRotate:!0,animateScale:!0},aspectRatio:1,legendCallback:function(t){var e=[];if(e.push('<ul class="'+t.id+'-legend">'),t.data.datasets.length)for(var i=0;i<t.data.datasets[0].data.length;++i)e.push('<li><span style="background-color:'+t.data.datasets[0].backgroundColor[i]+'">'),t.data.labels[i]&&e.push(t.data.labels[i]),e.push("</span></li>");return e.push("</ul>"),e.join("")},legend:{labels:{generateLabels:function(t){var i=t.data;return i.labels.length&&i.datasets.length?i.labels.map(function(s,a){var o=t.getDatasetMeta(0),n=i.datasets[0],r=o.data[a],h=r.custom&&r.custom.backgroundColor?r.custom.backgroundColor:e.getValueAtIndexOrDefault(n.backgroundColor,a,this.chart.options.elements.arc.backgroundColor),l=r.custom&&r.custom.borderColor?r.custom.borderColor:e.getValueAtIndexOrDefault(n.borderColor,a,this.chart.options.elements.arc.borderColor),c=r.custom&&r.custom.borderWidth?r.custom.borderWidth:e.getValueAtIndexOrDefault(n.borderWidth,a,this.chart.options.elements.arc.borderWidth);return{text:s,fillStyle:h,strokeStyle:l,lineWidth:c,hidden:isNaN(n.data[a])||o.data[a].hidden,index:a}},this):[]}},onClick:function(t,e){var i,s,a,o=e.index,n=this.chart;for(i=0,s=(n.data.datasets||[]).length;s>i;++i)a=n.getDatasetMeta(i),a.data[o].hidden=!a.data[o].hidden;n.update()}},tooltips:{callbacks:{title:function(){return""},label:function(t,e){return e.labels[t.index]+": "+t.yLabel}}}},t.controllers.polarArea=t.DatasetController.extend({linkScales:function(){},addElements:function(){var i=this.getMeta();e.each(this.getDataset().data,function(e,s){i.data[s]=i.data[s]||new t.elements.Arc({_chart:this.chart.chart,_datasetIndex:this.index,_index:s})},this)},addElementAndReset:function(e){var i=new t.elements.Arc({_chart:this.chart.chart,_datasetIndex:this.index,_index:e});this.getMeta().data.splice(e,0,i),this.updateElement(i,e,!0)},update:function(t){var i=this.getMeta(),s=Math.min(this.chart.chartArea.right-this.chart.chartArea.left,this.chart.chartArea.bottom-this.chart.chartArea.top);this.chart.outerRadius=Math.max((s-this.chart.options.elements.arc.borderWidth/2)/2,0),this.chart.innerRadius=Math.max(this.chart.options.cutoutPercentage?this.chart.outerRadius/100*this.chart.options.cutoutPercentage:1,0),this.chart.radiusLength=(this.chart.outerRadius-this.chart.innerRadius)/this.chart.getVisibleDatasetCount(),this.outerRadius=this.chart.outerRadius-this.chart.radiusLength*this.index,this.innerRadius=this.outerRadius-this.chart.radiusLength,i.count=this.countVisibleElements(),e.each(i.data,function(e,i){this.updateElement(e,i,t)},this)},updateElement:function(t,i,s){for(var a=this.calculateCircumference(this.getDataset().data[i]),o=(this.chart.chartArea.left+this.chart.chartArea.right)/2,n=(this.chart.chartArea.top+this.chart.chartArea.bottom)/2,r=0,h=this.getMeta(),l=0;i>l;++l)isNaN(this.getDataset().data[l])||h.data[l].hidden||++r;var c=t.hidden?0:this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[i]),d=-.5*Math.PI+a*r,u=d+(t.hidden?0:a),f={x:o,y:n,innerRadius:0,outerRadius:this.chart.options.animation.animateScale?0:this.chart.scale.getDistanceFromCenterForValue(this.getDataset().data[i]),startAngle:this.chart.options.animation.animateRotate?Math.PI*-.5:d,endAngle:this.chart.options.animation.animateRotate?Math.PI*-.5:u,backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.arc.backgroundColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.arc.borderWidth),borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.arc.borderColor),label:e.getValueAtIndexOrDefault(this.chart.data.labels,i,this.chart.data.labels[i])};e.extend(t,{_chart:this.chart.chart,_datasetIndex:this.index,_index:i,_scale:this.chart.scale,_model:s?f:{x:o,y:n,innerRadius:0,outerRadius:c,startAngle:d,endAngle:u,backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.arc.backgroundColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.arc.borderWidth),borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.arc.borderColor),label:e.getValueAtIndexOrDefault(this.chart.data.labels,i,this.chart.data.labels[i])}}),t.pivot()},draw:function(t){var i=t||1;e.each(this.getMeta().data,function(t,e){t.transition(i).draw()})},setHoverStyle:function(t){var i=this.chart.data.datasets[t._datasetIndex],s=t._index;t._model.backgroundColor=t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(i.hoverBackgroundColor,s,e.color(t._model.backgroundColor).saturate(.5).darken(.1).rgbString()),t._model.borderColor=t.custom&&t.custom.hoverBorderColor?t.custom.hoverBorderColor:e.getValueAtIndexOrDefault(i.hoverBorderColor,s,e.color(t._model.borderColor).saturate(.5).darken(.1).rgbString()),t._model.borderWidth=t.custom&&t.custom.hoverBorderWidth?t.custom.hoverBorderWidth:e.getValueAtIndexOrDefault(i.hoverBorderWidth,s,t._model.borderWidth)},removeHoverStyle:function(t){var i=(this.chart.data.datasets[t._datasetIndex],t._index);t._model.backgroundColor=t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().backgroundColor,i,this.chart.options.elements.arc.backgroundColor),t._model.borderColor=t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().borderColor,i,this.chart.options.elements.arc.borderColor),t._model.borderWidth=t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().borderWidth,i,this.chart.options.elements.arc.borderWidth)},countVisibleElements:function(){var t=this.getDataset(),i=this.getMeta(),s=0;return e.each(i.data,function(e,i){isNaN(t.data[i])||e.hidden||s++}),s},calculateCircumference:function(t){var e=this.getMeta().count;return e>0&&!isNaN(t)?2*Math.PI/e:0}})}},{}],14:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.radar={scale:{type:"radialLinear"},elements:{line:{tension:0}}},t.controllers.radar=t.DatasetController.extend({linkScales:function(){},addElements:function(){var i=this.getMeta();i.dataset=i.dataset||new t.elements.Line({_chart:this.chart.chart,_datasetIndex:this.index,_points:i.data,_loop:!0}),e.each(this.getDataset().data,function(e,s){i.data[s]=i.data[s]||new t.elements.Point({_chart:this.chart.chart,_datasetIndex:this.index,_index:s,_model:{x:0,y:0}})},this)},addElementAndReset:function(e){var i=new t.elements.Point({_chart:this.chart.chart,_datasetIndex:this.index,_index:e});this.getMeta().data.splice(e,0,i),this.updateElement(i,e,!0),this.updateBezierControlPoints()},update:function(t){var i,s=this.getMeta(),a=s.dataset,o=s.data,n=this.chart.scale;i=n.min<0&&n.max<0?n.getPointPositionForValue(0,n.max):n.min>0&&n.max>0?n.getPointPositionForValue(0,n.min):n.getPointPositionForValue(0,0),void 0!==this.getDataset().tension&&void 0===this.getDataset().lineTension&&(this.getDataset().lineTension=this.getDataset().tension),e.extend(s.dataset,{_datasetIndex:this.index,_children:o,_model:{tension:a.custom&&a.custom.tension?a.custom.tension:e.getValueOrDefault(this.getDataset().lineTension,this.chart.options.elements.line.tension),backgroundColor:a.custom&&a.custom.backgroundColor?a.custom.backgroundColor:this.getDataset().backgroundColor||this.chart.options.elements.line.backgroundColor,borderWidth:a.custom&&a.custom.borderWidth?a.custom.borderWidth:this.getDataset().borderWidth||this.chart.options.elements.line.borderWidth,borderColor:a.custom&&a.custom.borderColor?a.custom.borderColor:this.getDataset().borderColor||this.chart.options.elements.line.borderColor,fill:a.custom&&a.custom.fill?a.custom.fill:void 0!==this.getDataset().fill?this.getDataset().fill:this.chart.options.elements.line.fill,borderCapStyle:a.custom&&a.custom.borderCapStyle?a.custom.borderCapStyle:this.getDataset().borderCapStyle||this.chart.options.elements.line.borderCapStyle,borderDash:a.custom&&a.custom.borderDash?a.custom.borderDash:this.getDataset().borderDash||this.chart.options.elements.line.borderDash,borderDashOffset:a.custom&&a.custom.borderDashOffset?a.custom.borderDashOffset:this.getDataset().borderDashOffset||this.chart.options.elements.line.borderDashOffset,borderJoinStyle:a.custom&&a.custom.borderJoinStyle?a.custom.borderJoinStyle:this.getDataset().borderJoinStyle||this.chart.options.elements.line.borderJoinStyle,scaleTop:n.top,scaleBottom:n.bottom,scaleZero:i}}),s.dataset.pivot(),e.each(o,function(e,i){this.updateElement(e,i,t)},this),this.updateBezierControlPoints()},updateElement:function(t,i,s){var a=this.chart.scale.getPointPositionForValue(i,this.getDataset().data[i]);e.extend(t,{_datasetIndex:this.index,_index:i,_scale:this.chart.scale,_model:{x:s?this.chart.scale.xCenter:a.x,y:s?this.chart.scale.yCenter:a.y,tension:t.custom&&t.custom.tension?t.custom.tension:e.getValueOrDefault(this.getDataset().tension,this.chart.options.elements.line.tension),radius:t.custom&&t.custom.radius?t.custom.radius:e.getValueAtIndexOrDefault(this.getDataset().pointRadius,i,this.chart.options.elements.point.radius),backgroundColor:t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().pointBackgroundColor,i,this.chart.options.elements.point.backgroundColor),borderColor:t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().pointBorderColor,i,this.chart.options.elements.point.borderColor),borderWidth:t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().pointBorderWidth,i,this.chart.options.elements.point.borderWidth),pointStyle:t.custom&&t.custom.pointStyle?t.custom.pointStyle:e.getValueAtIndexOrDefault(this.getDataset().pointStyle,i,this.chart.options.elements.point.pointStyle),hitRadius:t.custom&&t.custom.hitRadius?t.custom.hitRadius:e.getValueAtIndexOrDefault(this.getDataset().hitRadius,i,this.chart.options.elements.point.hitRadius)}}),t._model.skip=t.custom&&t.custom.skip?t.custom.skip:isNaN(t._model.x)||isNaN(t._model.y)},updateBezierControlPoints:function(){var t=this.getMeta();e.each(t.data,function(i,s){var a=e.splineCurve(e.previousItem(t.data,s,!0)._model,i._model,e.nextItem(t.data,s,!0)._model,i._model.tension);i._model.controlPointPreviousX=Math.max(Math.min(a.previous.x,this.chart.chartArea.right),this.chart.chartArea.left),i._model.controlPointPreviousY=Math.max(Math.min(a.previous.y,this.chart.chartArea.bottom),this.chart.chartArea.top),i._model.controlPointNextX=Math.max(Math.min(a.next.x,this.chart.chartArea.right),this.chart.chartArea.left),i._model.controlPointNextY=Math.max(Math.min(a.next.y,this.chart.chartArea.bottom),this.chart.chartArea.top),i.pivot()},this)},draw:function(t){var i=this.getMeta(),s=t||1;e.each(i.data,function(t,e){t.transition(s)}),i.dataset.transition(s).draw(),e.each(i.data,function(t){t.draw()})},setHoverStyle:function(t){var i=this.chart.data.datasets[t._datasetIndex],s=t._index;t._model.radius=t.custom&&t.custom.hoverRadius?t.custom.hoverRadius:e.getValueAtIndexOrDefault(i.pointHoverRadius,s,this.chart.options.elements.point.hoverRadius),t._model.backgroundColor=t.custom&&t.custom.hoverBackgroundColor?t.custom.hoverBackgroundColor:e.getValueAtIndexOrDefault(i.pointHoverBackgroundColor,s,e.color(t._model.backgroundColor).saturate(.5).darken(.1).rgbString()),t._model.borderColor=t.custom&&t.custom.hoverBorderColor?t.custom.hoverBorderColor:e.getValueAtIndexOrDefault(i.pointHoverBorderColor,s,e.color(t._model.borderColor).saturate(.5).darken(.1).rgbString()),t._model.borderWidth=t.custom&&t.custom.hoverBorderWidth?t.custom.hoverBorderWidth:e.getValueAtIndexOrDefault(i.pointHoverBorderWidth,s,t._model.borderWidth)},removeHoverStyle:function(t){var i=(this.chart.data.datasets[t._datasetIndex],t._index);t._model.radius=t.custom&&t.custom.radius?t.custom.radius:e.getValueAtIndexOrDefault(this.getDataset().radius,i,this.chart.options.elements.point.radius),t._model.backgroundColor=t.custom&&t.custom.backgroundColor?t.custom.backgroundColor:e.getValueAtIndexOrDefault(this.getDataset().pointBackgroundColor,i,this.chart.options.elements.point.backgroundColor),t._model.borderColor=t.custom&&t.custom.borderColor?t.custom.borderColor:e.getValueAtIndexOrDefault(this.getDataset().pointBorderColor,i,this.chart.options.elements.point.borderColor),t._model.borderWidth=t.custom&&t.custom.borderWidth?t.custom.borderWidth:e.getValueAtIndexOrDefault(this.getDataset().pointBorderWidth,i,this.chart.options.elements.point.borderWidth)}})}},{}],15:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.animation={duration:1e3,easing:"easeOutQuart",onProgress:e.noop,onComplete:e.noop},t.Animation=t.Element.extend({currentStep:null,numSteps:60,easing:"",render:null,onAnimationProgress:null,onAnimationComplete:null}),t.animationService={frameDuration:17,animations:[],dropFrames:0,request:null,addAnimation:function(t,e,i,s){s||(t.animating=!0);for(var a=0;a<this.animations.length;++a)if(this.animations[a].chartInstance===t)return void(this.animations[a].animationObject=e);this.animations.push({chartInstance:t,animationObject:e}),1===this.animations.length&&this.requestAnimationFrame()},cancelAnimation:function(t){var i=e.findIndex(this.animations,function(e){return e.chartInstance===t});-1!==i&&(this.animations.splice(i,1),t.animating=!1)},requestAnimationFrame:function(){var t=this;null===t.request&&(t.request=e.requestAnimFrame.call(window,function(){t.request=null,t.startDigest()}))},startDigest:function(){var t=Date.now(),e=0;this.dropFrames>1&&(e=Math.floor(this.dropFrames),this.dropFrames=this.dropFrames%1);for(var i=0;i<this.animations.length;)null===this.animations[i].animationObject.currentStep&&(this.animations[i].animationObject.currentStep=0),this.animations[i].animationObject.currentStep+=1+e,this.animations[i].animationObject.currentStep>this.animations[i].animationObject.numSteps&&(this.animations[i].animationObject.currentStep=this.animations[i].animationObject.numSteps),this.animations[i].animationObject.render(this.animations[i].chartInstance,this.animations[i].animationObject),this.animations[i].animationObject.onAnimationProgress&&this.animations[i].animationObject.onAnimationProgress.call&&this.animations[i].animationObject.onAnimationProgress.call(this.animations[i].chartInstance,this.animations[i]),this.animations[i].animationObject.currentStep===this.animations[i].animationObject.numSteps?(this.animations[i].animationObject.onAnimationComplete&&this.animations[i].animationObject.onAnimationComplete.call&&this.animations[i].animationObject.onAnimationComplete.call(this.animations[i].chartInstance,this.animations[i]),this.animations[i].chartInstance.animating=!1,this.animations.splice(i,1)):++i;var s=Date.now(),a=(s-t)/this.frameDuration;this.dropFrames+=a,this.animations.length>0&&this.requestAnimationFrame()}}}},{}],16:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.types={},t.instances={},t.controllers={},t.Controller=function(i){return this.chart=i,this.config=i.config,this.options=this.config.options=e.configMerge(t.defaults.global,t.defaults[this.config.type],this.config.options||{}),this.id=e.uid(),Object.defineProperty(this,"data",{get:function(){return this.config.data}}),t.instances[this.id]=this,this.options.responsive&&this.resize(!0),this.initialize(),this},e.extend(t.Controller.prototype,{initialize:function(){return t.pluginService.notifyPlugins("beforeInit",[this]),this.bindEvents(),this.ensureScalesHaveIDs(),this.buildOrUpdateControllers(),this.buildScales(),this.buildSurroundingItems(),this.updateLayout(),this.resetElements(),this.initToolTip(),this.update(),t.pluginService.notifyPlugins("afterInit",[this]),this},clear:function(){return e.clear(this.chart),this},stop:function(){return t.animationService.cancelAnimation(this),this},resize:function(t){var i=this.chart.canvas,s=e.getMaximumWidth(this.chart.canvas),a=this.options.maintainAspectRatio&&isNaN(this.chart.aspectRatio)===!1&&isFinite(this.chart.aspectRatio)&&0!==this.chart.aspectRatio?s/this.chart.aspectRatio:e.getMaximumHeight(this.chart.canvas),o=this.chart.width!==s||this.chart.height!==a;return o?(i.width=this.chart.width=s,i.height=this.chart.height=a,e.retinaScale(this.chart),t||(this.stop(),this.update(this.options.responsiveAnimationDuration)),this):this},ensureScalesHaveIDs:function(){var t="x-axis-",i="y-axis-";this.options.scales&&(this.options.scales.xAxes&&this.options.scales.xAxes.length&&e.each(this.options.scales.xAxes,function(e,i){e.id=e.id||t+i}),this.options.scales.yAxes&&this.options.scales.yAxes.length&&e.each(this.options.scales.yAxes,function(t,e){t.id=t.id||i+e}))},buildScales:function(){if(this.scales={},this.options.scales&&(this.options.scales.xAxes&&this.options.scales.xAxes.length&&e.each(this.options.scales.xAxes,function(i,s){var a=e.getValueOrDefault(i.type,"category"),o=t.scaleService.getScaleConstructor(a);if(o){var n=new o({ctx:this.chart.ctx,options:i,chart:this,id:i.id});this.scales[n.id]=n}},this),this.options.scales.yAxes&&this.options.scales.yAxes.length&&e.each(this.options.scales.yAxes,function(i,s){var a=e.getValueOrDefault(i.type,"linear"),o=t.scaleService.getScaleConstructor(a);if(o){var n=new o({ctx:this.chart.ctx,options:i,chart:this,id:i.id});this.scales[n.id]=n}},this)),this.options.scale){var i=t.scaleService.getScaleConstructor(this.options.scale.type);if(i){var s=new i({ctx:this.chart.ctx,options:this.options.scale,chart:this});this.scale=s,this.scales.radialScale=s}}t.scaleService.addScalesToLayout(this)},buildSurroundingItems:function(){this.options.title&&(this.titleBlock=new t.Title({ctx:this.chart.ctx,options:this.options.title,chart:this}),t.layoutService.addBox(this,this.titleBlock)),this.options.legend&&(this.legend=new t.Legend({ctx:this.chart.ctx,options:this.options.legend,chart:this}),t.layoutService.addBox(this,this.legend))},updateLayout:function(){t.layoutService.update(this,this.chart.width,this.chart.height)},buildOrUpdateControllers:function(){var i=[],s=[];if(e.each(this.data.datasets,function(e,a){var o=this.getDatasetMeta(a);o.type||(o.type=e.type||this.config.type),i.push(o.type),o.controller?o.controller.updateIndex(a):(o.controller=new t.controllers[o.type](this,a),s.push(o.controller))},this),i.length>1)for(var a=1;a<i.length;a++)if(i[a]!==i[a-1]){this.isCombo=!0;break}return s},resetElements:function(){e.each(this.data.datasets,function(t,e){this.getDatasetMeta(e).controller.reset()},this)},update:function(i,s){t.pluginService.notifyPlugins("beforeUpdate",[this]),this.tooltip._data=this.data;var a=this.buildOrUpdateControllers();e.each(this.data.datasets,function(t,e){this.getDatasetMeta(e).controller.buildOrUpdateElements()},this),t.layoutService.update(this,this.chart.width,this.chart.height),e.each(a,function(t){t.reset()}),e.each(this.data.datasets,function(t,e){this.getDatasetMeta(e).controller.update()},this),this.render(i,s),t.pluginService.notifyPlugins("afterUpdate",[this])},render:function(i,s){if(t.pluginService.notifyPlugins("beforeRender",[this]),this.options.animation&&("undefined"!=typeof i&&0!==i||"undefined"==typeof i&&0!==this.options.animation.duration)){var a=new t.Animation;a.numSteps=(i||this.options.animation.duration)/16.66,a.easing=this.options.animation.easing,a.render=function(t,i){var s=e.easingEffects[i.easing],a=i.currentStep/i.numSteps,o=s(a);t.draw(o,a,i.currentStep)},a.onAnimationProgress=this.options.animation.onProgress,a.onAnimationComplete=this.options.animation.onComplete,t.animationService.addAnimation(this,a,i,s)}else this.draw(),this.options.animation&&this.options.animation.onComplete&&this.options.animation.onComplete.call&&this.options.animation.onComplete.call(this);return this},draw:function(i){var s=i||1;this.clear(),t.pluginService.notifyPlugins("beforeDraw",[this,s]),e.each(this.boxes,function(t){t.draw(this.chartArea)},this),this.scale&&this.scale.draw(),this.chart.ctx.save(),this.chart.ctx.beginPath(),this.chart.ctx.rect(this.chartArea.left,this.chartArea.top,this.chartArea.right-this.chartArea.left,this.chartArea.bottom-this.chartArea.top),this.chart.ctx.clip(),e.each(this.data.datasets,function(t,e){this.isDatasetVisible(e)&&this.getDatasetMeta(e).controller.draw(i)},this,!0),this.chart.ctx.restore(),this.tooltip.transition(s).draw(),t.pluginService.notifyPlugins("afterDraw",[this,s])},getElementAtEvent:function(t){var i=e.getRelativePosition(t,this.chart),s=[];return e.each(this.data.datasets,function(t,a){if(this.isDatasetVisible(a)){var o=this.getDatasetMeta(a);e.each(o.data,function(t,e){return t.inRange(i.x,i.y)?(s.push(t),s):void 0})}},this),s},getElementsAtEvent:function(t){var i=e.getRelativePosition(t,this.chart),s=[],a=function(){if(this.data.datasets)for(var t=0;t<this.data.datasets.length;t++){var e=this.getDatasetMeta(t);if(this.isDatasetVisible(t))for(var s=0;s<e.data.length;s++)if(e.data[s].inRange(i.x,i.y))return e.data[s]}}.call(this);return a?(e.each(this.data.datasets,function(t,e){if(this.isDatasetVisible(e)){var i=this.getDatasetMeta(e);s.push(i.data[a._index])}},this),s):s},getDatasetAtEvent:function(t){var e=this.getElementAtEvent(t);return e.length>0&&(e=this.getDatasetMeta(e[0]._datasetIndex).data),e},getDatasetMeta:function(t){var e=this.data.datasets[t];e._meta||(e._meta={});var i=e._meta[this.id];return i||(i=e._meta[this.id]={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null}),i},getVisibleDatasetCount:function(){for(var t=0,e=0,i=this.data.datasets.length;i>e;++e)this.isDatasetVisible(e)&&t++;return t},isDatasetVisible:function(t){var e=this.getDatasetMeta(t);return"boolean"==typeof e.hidden?!e.hidden:!this.data.datasets[t].hidden},generateLegend:function(){return this.options.legendCallback(this)},destroy:function(){this.clear(),e.unbindEvents(this,this.events),e.removeResizeListener(this.chart.canvas.parentNode);var i=this.chart.canvas;i.width=this.chart.width,i.height=this.chart.height,void 0!==this.chart.originalDevicePixelRatio&&this.chart.ctx.scale(1/this.chart.originalDevicePixelRatio,1/this.chart.originalDevicePixelRatio),i.style.width=this.chart.originalCanvasStyleWidth,i.style.height=this.chart.originalCanvasStyleHeight,t.pluginService.notifyPlugins("destroy",[this]),delete t.instances[this.id]},toBase64Image:function(){return this.chart.canvas.toDataURL.apply(this.chart.canvas,arguments)},initToolTip:function(){this.tooltip=new t.Tooltip({_chart:this.chart,_chartInstance:this,_data:this.data,_options:this.options},this)},bindEvents:function(){e.bindEvents(this,this.options.events,function(t){this.eventHandler(t)})},eventHandler:function(t){if(this.lastActive=this.lastActive||[],this.lastTooltipActive=this.lastTooltipActive||[],"mouseout"===t.type)this.active=[],this.tooltipActive=[];else{var i=this,s=function(e){switch(e){case"single":return i.getElementAtEvent(t);case"label":return i.getElementsAtEvent(t);case"dataset":return i.getDatasetAtEvent(t);default:return t}};this.active=s(this.options.hover.mode),this.tooltipActive=s(this.options.tooltips.mode)}if(this.options.hover.onHover&&this.options.hover.onHover.call(this,this.active),"mouseup"!==t.type&&"click"!==t.type||(this.options.onClick&&this.options.onClick.call(this,t,this.active),this.legend&&this.legend.handleEvent&&this.legend.handleEvent(t)),this.lastActive.length)switch(this.options.hover.mode){case"single":this.getDatasetMeta(this.lastActive[0]._datasetIndex).controller.removeHoverStyle(this.lastActive[0],this.lastActive[0]._datasetIndex,this.lastActive[0]._index);break;case"label":case"dataset":for(var a=0;a<this.lastActive.length;a++)this.lastActive[a]&&this.getDatasetMeta(this.lastActive[a]._datasetIndex).controller.removeHoverStyle(this.lastActive[a],this.lastActive[a]._datasetIndex,this.lastActive[a]._index)}if(this.active.length&&this.options.hover.mode)switch(this.options.hover.mode){case"single":this.getDatasetMeta(this.active[0]._datasetIndex).controller.setHoverStyle(this.active[0]);break;case"label":case"dataset":for(var o=0;o<this.active.length;o++)this.active[o]&&this.getDatasetMeta(this.active[o]._datasetIndex).controller.setHoverStyle(this.active[o])}if((this.options.tooltips.enabled||this.options.tooltips.custom)&&(this.tooltip.initialize(),this.tooltip._active=this.tooltipActive,this.tooltip.update()),this.tooltip.pivot(),!this.animating){var n;e.each(this.active,function(t,e){t!==this.lastActive[e]&&(n=!0)},this),e.each(this.tooltipActive,function(t,e){t!==this.lastTooltipActive[e]&&(n=!0)},this),(this.lastActive.length!==this.active.length||this.lastTooltipActive.length!==this.tooltipActive.length||n)&&(this.stop(),(this.options.tooltips.enabled||this.options.tooltips.custom)&&this.tooltip.update(!0),this.render(this.options.hover.animationDuration,!0))}return this.lastActive=this.active,this.lastTooltipActive=this.tooltipActive,this}})}},{}],17:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.DatasetController=function(t,e){this.initialize.call(this,t,e)},e.extend(t.DatasetController.prototype,{initialize:function(t,e){this.chart=t,this.index=e,this.linkScales(),this.addElements()},updateIndex:function(t){this.index=t},linkScales:function(){var t=this.getMeta(),e=this.getDataset();null===t.xAxisID&&(t.xAxisID=e.xAxisID||this.chart.options.scales.xAxes[0].id),null===t.yAxisID&&(t.yAxisID=e.yAxisID||this.chart.options.scales.yAxes[0].id)},getDataset:function(){return this.chart.data.datasets[this.index]},getMeta:function(){return this.chart.getDatasetMeta(this.index)},getScaleForId:function(t){return this.chart.scales[t]},reset:function(){this.update(!0)},buildOrUpdateElements:function(){var t=this.getMeta(),e=this.getDataset().data.length,i=t.data.length;if(i>e)t.data.splice(e,i-e);else if(e>i)for(var s=i;e>s;++s)this.addElementAndReset(s)},addElements:e.noop,addElementAndReset:e.noop,draw:e.noop,removeHoverStyle:e.noop,setHoverStyle:e.noop,update:e.noop}),t.DatasetController.extend=e.inherits}},{}],18:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.elements={},t.Element=function(t){e.extend(this,t),this.initialize.apply(this,arguments)},e.extend(t.Element.prototype,{initialize:function(){this.hidden=!1},pivot:function(){return this._view||(this._view=e.clone(this._model)),this._start=e.clone(this._view),this},transition:function(t){return this._view||(this._view=e.clone(this._model)),1===t?(this._view=this._model,this._start=null,this):(this._start||this.pivot(),e.each(this._model,function(i,s){if("_"!==s[0]&&this._model.hasOwnProperty(s))if(this._view.hasOwnProperty(s))if(i===this._view[s]);else if("string"==typeof i)try{var a=e.color(this._start[s]).mix(e.color(this._model[s]),t);this._view[s]=a.rgbString()}catch(o){this._view[s]=i}else if("number"==typeof i){var n=void 0!==this._start[s]&&isNaN(this._start[s])===!1?this._start[s]:0;this._view[s]=(this._model[s]-n)*t+n}else this._view[s]=i;else"number"!=typeof i||isNaN(this._view[s])?this._view[s]=i:this._view[s]=i*t;else;},this),this)},tooltipPosition:function(){return{x:this._model.x,y:this._model.y}},hasValue:function(){return e.isNumber(this._model.x)&&e.isNumber(this._model.y)}}),t.Element.extend=e.inherits}},{}],19:[function(t,e,i){"use strict";var s=t("chartjs-color");e.exports=function(t){function e(t,e,i){var s;return"string"==typeof t?(s=parseInt(t,10),-1!=t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}function i(t,i,s){var a,o=document.defaultView.getComputedStyle(t)[i],n=document.defaultView.getComputedStyle(t.parentNode)[i],r=null!==o&&"none"!==o,h=null!==n&&"none"!==n;return(r||h)&&(a=Math.min(r?e(o,t,s):Number.POSITIVE_INFINITY,h?e(n,t.parentNode,s):Number.POSITIVE_INFINITY)),a}var a=t.helpers={};a.each=function(t,e,i,s){var o,n;if(a.isArray(t))if(n=t.length,s)for(o=n-1;o>=0;o--)e.call(i,t[o],o);else for(o=0;n>o;o++)e.call(i,t[o],o);else if("object"==typeof t){var r=Object.keys(t);for(n=r.length,o=0;n>o;o++)e.call(i,t[r[o]],r[o])}},a.clone=function(t){var e={};return a.each(t,function(i,s){t.hasOwnProperty(s)&&(a.isArray(i)?e[s]=i.slice(0):"object"==typeof i&&null!==i?e[s]=a.clone(i):e[s]=i)}),e},a.extend=function(t){for(var e=arguments.length,i=[],s=1;e>s;s++)i.push(arguments[s]);return a.each(i,function(e){a.each(e,function(i,s){e.hasOwnProperty(s)&&(t[s]=i)})}),t},a.configMerge=function(e){var i=a.clone(e);return a.each(Array.prototype.slice.call(arguments,1),function(e){a.each(e,function(s,o){if(e.hasOwnProperty(o))if("scales"===o)i[o]=a.scaleMerge(i.hasOwnProperty(o)?i[o]:{},s);else if("scale"===o)i[o]=a.configMerge(i.hasOwnProperty(o)?i[o]:{},t.scaleService.getScaleDefaults(s.type),s);else if(i.hasOwnProperty(o)&&a.isArray(i[o])&&a.isArray(s)){ var n=i[o];a.each(s,function(t,e){e<n.length?"object"==typeof n[e]&&null!==n[e]&&"object"==typeof t&&null!==t?n[e]=a.configMerge(n[e],t):n[e]=t:n.push(t)})}else i.hasOwnProperty(o)&&"object"==typeof i[o]&&null!==i[o]&&"object"==typeof s?i[o]=a.configMerge(i[o],s):i[o]=s})}),i},a.extendDeep=function(t){function e(t){return a.each(arguments,function(i){i!==t&&a.each(i,function(i,s){t[s]&&t[s].constructor&&t[s].constructor===Object?e(t[s],i):t[s]=i})}),t}return e.apply(this,arguments)},a.scaleMerge=function(e,i){var s=a.clone(e);return a.each(i,function(e,o){i.hasOwnProperty(o)&&("xAxes"===o||"yAxes"===o?s.hasOwnProperty(o)?a.each(e,function(e,i){var n=a.getValueOrDefault(e.type,"xAxes"===o?"category":"linear"),r=t.scaleService.getScaleDefaults(n);i>=s[o].length||!s[o][i].type?s[o].push(a.configMerge(r,e)):e.type&&e.type!==s[o][i].type?s[o][i]=a.configMerge(s[o][i],r,e):s[o][i]=a.configMerge(s[o][i],e)}):(s[o]=[],a.each(e,function(e){var i=a.getValueOrDefault(e.type,"xAxes"===o?"category":"linear");s[o].push(a.configMerge(t.scaleService.getScaleDefaults(i),e))})):s.hasOwnProperty(o)&&"object"==typeof s[o]&&null!==s[o]&&"object"==typeof e?s[o]=a.configMerge(s[o],e):s[o]=e)}),s},a.getValueAtIndexOrDefault=function(t,e,i){return void 0===t||null===t?i:a.isArray(t)?e<t.length?t[e]:i:t},a.getValueOrDefault=function(t,e){return void 0===t?e:t},a.indexOf=function(t,e){if(Array.prototype.indexOf)return t.indexOf(e);for(var i=0;i<t.length;i++)if(t[i]===e)return i;return-1},a.where=function(t,e){var i=[];return a.each(t,function(t){e(t)&&i.push(t)}),i},a.findIndex=function(t,e,i){var s=-1;if(Array.prototype.findIndex)s=t.findIndex(e,i);else for(var a=0;a<t.length;++a)if(i=void 0!==i?i:t,e.call(i,t[a],a,t)){s=a;break}return s},a.findNextWhere=function(t,e,i){void 0!==i&&null!==i||(i=-1);for(var s=i+1;s<t.length;s++){var a=t[s];if(e(a))return a}},a.findPreviousWhere=function(t,e,i){void 0!==i&&null!==i||(i=t.length);for(var s=i-1;s>=0;s--){var a=t[s];if(e(a))return a}},a.inherits=function(t){var e=this,i=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return e.apply(this,arguments)},s=function(){this.constructor=i};return s.prototype=e.prototype,i.prototype=new s,i.extend=a.inherits,t&&a.extend(i.prototype,t),i.__super__=e.prototype,i},a.noop=function(){},a.uid=function(){var t=0;return function(){return t++}}(),a.warn=function(t){console&&"function"==typeof console.warn&&console.warn(t)},a.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},a.almostEquals=function(t,e,i){return Math.abs(t-e)<i},a.max=function(t){return t.reduce(function(t,e){return isNaN(e)?t:Math.max(t,e)},Number.NEGATIVE_INFINITY)},a.min=function(t){return t.reduce(function(t,e){return isNaN(e)?t:Math.min(t,e)},Number.POSITIVE_INFINITY)},a.sign=function(t){return Math.sign?Math.sign(t):(t=+t,0===t||isNaN(t)?t:t>0?1:-1)},a.log10=function(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10},a.toRadians=function(t){return t*(Math.PI/180)},a.toDegrees=function(t){return t*(180/Math.PI)},a.getAngleFromPoint=function(t,e){var i=e.x-t.x,s=e.y-t.y,a=Math.sqrt(i*i+s*s),o=Math.atan2(s,i);return o<-.5*Math.PI&&(o+=2*Math.PI),{angle:o,distance:a}},a.aliasPixel=function(t){return t%2===0?0:.5},a.splineCurve=function(t,e,i,s){var a=t.skip?e:t,o=e,n=i.skip?e:i,r=Math.sqrt(Math.pow(o.x-a.x,2)+Math.pow(o.y-a.y,2)),h=Math.sqrt(Math.pow(n.x-o.x,2)+Math.pow(n.y-o.y,2)),l=r/(r+h),c=h/(r+h);l=isNaN(l)?0:l,c=isNaN(c)?0:c;var d=s*l,u=s*c;return{previous:{x:o.x-d*(n.x-a.x),y:o.y-d*(n.y-a.y)},next:{x:o.x+u*(n.x-a.x),y:o.y+u*(n.y-a.y)}}},a.nextItem=function(t,e,i){return i?e>=t.length-1?t[0]:t[e+1]:e>=t.length-1?t[t.length-1]:t[e+1]},a.previousItem=function(t,e,i){return i?0>=e?t[t.length-1]:t[e-1]:0>=e?t[0]:t[e-1]},a.niceNum=function(t,e){var i,s=Math.floor(a.log10(t)),o=t/Math.pow(10,s);return i=e?1.5>o?1:3>o?2:7>o?5:10:1>=o?1:2>=o?2:5>=o?5:10,i*Math.pow(10,s)};var o=a.easingEffects={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-1*t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-0.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return 1*((t=t/1-1)*t*t+1)},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-1*((t=t/1-1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-0.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return 1*(t/=1)*t*t*t*t},easeOutQuint:function(t){return 1*((t=t/1-1)*t*t*t*t+1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return-1*Math.cos(t/1*(Math.PI/2))+1},easeOutSine:function(t){return 1*Math.sin(t/1*(Math.PI/2))},easeInOutSine:function(t){return-0.5*(Math.cos(Math.PI*t/1)-1)},easeInExpo:function(t){return 0===t?1:1*Math.pow(2,10*(t/1-1))},easeOutExpo:function(t){return 1===t?1:1*(-Math.pow(2,-10*t/1)+1)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(-Math.pow(2,-10*--t)+2)},easeInCirc:function(t){return t>=1?t:-1*(Math.sqrt(1-(t/=1)*t)-1)},easeOutCirc:function(t){return 1*Math.sqrt(1-(t=t/1-1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-0.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var e=1.70158,i=0,s=1;return 0===t?0:1===(t/=1)?1:(i||(i=.3),s<Math.abs(1)?(s=1,e=i/4):e=i/(2*Math.PI)*Math.asin(1/s),-(s*Math.pow(2,10*(t-=1))*Math.sin((1*t-e)*(2*Math.PI)/i)))},easeOutElastic:function(t){var e=1.70158,i=0,s=1;return 0===t?0:1===(t/=1)?1:(i||(i=.3),s<Math.abs(1)?(s=1,e=i/4):e=i/(2*Math.PI)*Math.asin(1/s),s*Math.pow(2,-10*t)*Math.sin((1*t-e)*(2*Math.PI)/i)+1)},easeInOutElastic:function(t){var e=1.70158,i=0,s=1;return 0===t?0:2===(t/=.5)?1:(i||(i=1*(.3*1.5)),s<Math.abs(1)?(s=1,e=i/4):e=i/(2*Math.PI)*Math.asin(1/s),1>t?-.5*(s*Math.pow(2,10*(t-=1))*Math.sin((1*t-e)*(2*Math.PI)/i)):s*Math.pow(2,-10*(t-=1))*Math.sin((1*t-e)*(2*Math.PI)/i)*.5+1)},easeInBack:function(t){var e=1.70158;return 1*(t/=1)*t*((e+1)*t-e)},easeOutBack:function(t){var e=1.70158;return 1*((t=t/1-1)*t*((e+1)*t+e)+1)},easeInOutBack:function(t){var e=1.70158;return(t/=.5)<1?.5*(t*t*(((e*=1.525)+1)*t-e)):.5*((t-=2)*t*(((e*=1.525)+1)*t+e)+2)},easeInBounce:function(t){return 1-o.easeOutBounce(1-t)},easeOutBounce:function(t){return(t/=1)<1/2.75?1*(7.5625*t*t):2/2.75>t?1*(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1*(7.5625*(t-=2.25/2.75)*t+.9375):1*(7.5625*(t-=2.625/2.75)*t+.984375)},easeInOutBounce:function(t){return.5>t?.5*o.easeInBounce(2*t):.5*o.easeOutBounce(2*t-1)+.5}};a.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)}}(),a.cancelAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){return window.clearTimeout(t,1e3/60)}}(),a.getRelativePosition=function(t,e){var i,s,o=t.originalEvent||t,n=t.currentTarget||t.srcElement,r=n.getBoundingClientRect();o.touches&&o.touches.length>0?(i=o.touches[0].clientX,s=o.touches[0].clientY):(i=o.clientX,s=o.clientY);var h=parseFloat(a.getStyle(n,"padding-left")),l=parseFloat(a.getStyle(n,"padding-top")),c=parseFloat(a.getStyle(n,"padding-right")),d=parseFloat(a.getStyle(n,"padding-bottom")),u=r.right-r.left-h-c,f=r.bottom-r.top-l-d;return i=Math.round((i-r.left-h)/u*n.width/e.currentDevicePixelRatio),s=Math.round((s-r.top-l)/f*n.height/e.currentDevicePixelRatio),{x:i,y:s}},a.addEvent=function(t,e,i){t.addEventListener?t.addEventListener(e,i):t.attachEvent?t.attachEvent("on"+e,i):t["on"+e]=i},a.removeEvent=function(t,e,i){t.removeEventListener?t.removeEventListener(e,i,!1):t.detachEvent?t.detachEvent("on"+e,i):t["on"+e]=a.noop},a.bindEvents=function(t,e,i){t.events||(t.events={}),a.each(e,function(e){t.events[e]=function(){i.apply(t,arguments)},a.addEvent(t.chart.canvas,e,t.events[e])})},a.unbindEvents=function(t,e){a.each(e,function(e,i){a.removeEvent(t.chart.canvas,i,e)})},a.getConstraintWidth=function(t){return i(t,"max-width","clientWidth")},a.getConstraintHeight=function(t){return i(t,"max-height","clientHeight")},a.getMaximumWidth=function(t){var e=t.parentNode,i=parseInt(a.getStyle(e,"padding-left"))+parseInt(a.getStyle(e,"padding-right")),s=e.clientWidth-i,o=a.getConstraintWidth(t);return void 0!==o&&(s=Math.min(s,o)),s},a.getMaximumHeight=function(t){var e=t.parentNode,i=parseInt(a.getStyle(e,"padding-top"))+parseInt(a.getStyle(e,"padding-bottom")),s=e.clientHeight-i,o=a.getConstraintHeight(t);return void 0!==o&&(s=Math.min(s,o)),s},a.getStyle=function(t,e){return t.currentStyle?t.currentStyle[e]:document.defaultView.getComputedStyle(t,null).getPropertyValue(e)},a.retinaScale=function(t){var e=t.ctx,i=t.canvas.width,s=t.canvas.height,a=t.currentDevicePixelRatio=window.devicePixelRatio||1;1!==a&&(e.canvas.height=s*a,e.canvas.width=i*a,e.scale(a,a),t.originalDevicePixelRatio=t.originalDevicePixelRatio||a),e.canvas.style.width=i+"px",e.canvas.style.height=s+"px"},a.clear=function(t){t.ctx.clearRect(0,0,t.width,t.height)},a.fontString=function(t,e,i){return e+" "+t+"px "+i},a.longestText=function(t,e,i,s){s=s||{},s.data=s.data||{},s.garbageCollect=s.garbageCollect||[],s.font!==e&&(s.data={},s.garbageCollect=[],s.font=e),t.font=e;var o=0;a.each(i,function(e){if(void 0!==e&&null!==e){var i=s.data[e];i||(i=s.data[e]=t.measureText(e).width,s.garbageCollect.push(e)),i>o&&(o=i)}});var n=s.garbageCollect.length/2;if(n>i.length){for(var r=0;n>r;r++)delete s.data[s.garbageCollect[r]];s.garbageCollect.splice(0,n)}return o},a.drawRoundedRectangle=function(t,e,i,s,a,o){t.beginPath(),t.moveTo(e+o,i),t.lineTo(e+s-o,i),t.quadraticCurveTo(e+s,i,e+s,i+o),t.lineTo(e+s,i+a-o),t.quadraticCurveTo(e+s,i+a,e+s-o,i+a),t.lineTo(e+o,i+a),t.quadraticCurveTo(e,i+a,e,i+a-o),t.lineTo(e,i+o),t.quadraticCurveTo(e,i,e+o,i),t.closePath()},a.color=function(e){return s?s(e instanceof CanvasGradient?t.defaults.global.defaultColor:e):(console.log("Color.js not found!"),e)},a.addResizeListener=function(t,e){var i=document.createElement("iframe"),s="chartjs-hidden-iframe";i.classlist?i.classlist.add(s):i.setAttribute("class",s),i.style.width="100%",i.style.display="block",i.style.border=0,i.style.height=0,i.style.margin=0,i.style.position="absolute",i.style.left=0,i.style.right=0,i.style.top=0,i.style.bottom=0,t.insertBefore(i,t.firstChild),(i.contentWindow||i).onresize=function(){e&&e()}},a.removeResizeListener=function(t){var e=t.querySelector(".chartjs-hidden-iframe");e&&e.parentNode.removeChild(e)},a.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===Object.prototype.toString.call(t)},a.pushAllIfDefined=function(t,e){"undefined"!=typeof t&&(a.isArray(t)?e.push.apply(e,t):e.push(t))},a.callCallback=function(t,e,i){t&&"function"==typeof t.call&&t.apply(i,e)}}},{"chartjs-color":38}],20:[function(t,e,i){"use strict";e.exports=function(){var t=function(e,i){this.config=i,e.length&&e[0].getContext&&(e=e[0]),e.getContext&&(e=e.getContext("2d")),this.ctx=e,this.canvas=e.canvas,this.width=e.canvas.width||parseInt(t.helpers.getStyle(e.canvas,"width"))||t.helpers.getMaximumWidth(e.canvas),this.height=e.canvas.height||parseInt(t.helpers.getStyle(e.canvas,"height"))||t.helpers.getMaximumHeight(e.canvas),this.aspectRatio=this.width/this.height,(isNaN(this.aspectRatio)||isFinite(this.aspectRatio)===!1)&&(this.aspectRatio=void 0!==i.aspectRatio?i.aspectRatio:2),this.originalCanvasStyleWidth=e.canvas.style.width,this.originalCanvasStyleHeight=e.canvas.style.height,t.helpers.retinaScale(this),i&&(this.controller=new t.Controller(this));var s=this;return t.helpers.addResizeListener(e.canvas.parentNode,function(){s.controller&&s.controller.config.options.responsive&&s.controller.resize()}),this.controller?this.controller:this};return t.defaults={global:{responsive:!0,responsiveAnimationDuration:0,maintainAspectRatio:!0,events:["mousemove","mouseout","click","touchstart","touchmove"],hover:{onHover:null,mode:"single",animationDuration:400},onClick:null,defaultColor:"rgba(0,0,0,0.1)",defaultFontColor:"#666",defaultFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",defaultFontSize:12,defaultFontStyle:"normal",showLines:!0,elements:{},legendCallback:function(t){var e=[];e.push('<ul class="'+t.id+'-legend">');for(var i=0;i<t.data.datasets.length;i++)e.push('<li><span style="background-color:'+t.data.datasets[i].backgroundColor+'"></span>'),t.data.datasets[i].label&&e.push(t.data.datasets[i].label),e.push("</li>");return e.push("</ul>"),e.join("")}}},t}},{}],21:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.layoutService={defaults:{},addBox:function(t,e){t.boxes||(t.boxes=[]),t.boxes.push(e)},removeBox:function(t,e){t.boxes&&t.boxes.splice(t.boxes.indexOf(e),1)},update:function(t,i,s){function a(t){var e,i=t.isHorizontal();i?(e=t.update(t.options.fullWidth?m:k,y),_-=e.height):(e=t.update(x,v),k-=e.width),S.push({horizontal:i,minSize:e,box:t})}function o(t){var i=e.findNextWhere(S,function(e){return e.box===t});if(i)if(t.isHorizontal()){var s={left:w,right:D,top:0,bottom:0};t.update(t.options.fullWidth?m:k,p/2,s)}else t.update(i.minSize.width,_)}function n(t){var i=e.findNextWhere(S,function(e){return e.box===t}),s={left:0,right:0,top:M,bottom:C};i&&t.update(i.minSize.width,_,s)}function r(t){t.isHorizontal()?(t.left=t.options.fullWidth?h:w,t.right=t.options.fullWidth?i-h:w+k,t.top=T,t.bottom=T+t.height,T=t.bottom):(t.left=P,t.right=P+t.width,t.top=M,t.bottom=M+_,P=t.right)}if(t){var h=0,l=0,c=e.where(t.boxes,function(t){return"left"===t.options.position}),d=e.where(t.boxes,function(t){return"right"===t.options.position}),u=e.where(t.boxes,function(t){return"top"===t.options.position}),f=e.where(t.boxes,function(t){return"bottom"===t.options.position}),g=e.where(t.boxes,function(t){return"chartArea"===t.options.position});u.sort(function(t,e){return(e.options.fullWidth?1:0)-(t.options.fullWidth?1:0)}),f.sort(function(t,e){return(t.options.fullWidth?1:0)-(e.options.fullWidth?1:0)});var m=i-2*h,p=s-2*l,b=m/2,v=p/2,x=(i-b)/(c.length+d.length),y=(s-v)/(u.length+f.length),k=m,_=p,S=[];e.each(c.concat(d,u,f),a);var w=h,D=h,M=l,C=l;e.each(c.concat(d),o),e.each(c,function(t){w+=t.width}),e.each(d,function(t){D+=t.width}),e.each(u.concat(f),o),e.each(u,function(t){M+=t.height}),e.each(f,function(t){C+=t.height}),e.each(c.concat(d),n),w=h,D=h,M=l,C=l,e.each(c,function(t){w+=t.width}),e.each(d,function(t){D+=t.width}),e.each(u,function(t){M+=t.height}),e.each(f,function(t){C+=t.height});var A=s-M-C,I=i-w-D;I===k&&A===_||(e.each(c,function(t){t.height=A}),e.each(d,function(t){t.height=A}),e.each(u,function(t){t.options.fullWidth||(t.width=I)}),e.each(f,function(t){t.options.fullWidth||(t.width=I)}),_=A,k=I);var P=h,T=l;e.each(c.concat(u),r),P+=k,T+=_,e.each(d,r),e.each(f,r),t.chartArea={left:w,top:M,right:w+k,bottom:M+_},e.each(g,function(e){e.left=t.chartArea.left,e.top=t.chartArea.top,e.right=t.chartArea.right,e.bottom=t.chartArea.bottom,e.update(k,_)})}}}}},{}],22:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.legend={display:!0,position:"top",fullWidth:!0,reverse:!1,onClick:function(t,e){var i=e.datasetIndex,s=this.chart.getDatasetMeta(i);s.hidden=null===s.hidden?!this.chart.data.datasets[i].hidden:null,this.chart.update()},labels:{boxWidth:40,padding:10,generateLabels:function(t){var i=t.data;return e.isArray(i.datasets)?i.datasets.map(function(e,i){return{text:e.label,fillStyle:e.backgroundColor,hidden:!t.isDatasetVisible(i),lineCap:e.borderCapStyle,lineDash:e.borderDash,lineDashOffset:e.borderDashOffset,lineJoin:e.borderJoinStyle,lineWidth:e.borderWidth,strokeStyle:e.borderColor,datasetIndex:i}},this):[]}}},t.Legend=t.Element.extend({initialize:function(t){e.extend(this,t),this.legendHitBoxes=[],this.doughnutMode=!1},beforeUpdate:e.noop,update:function(t,e,i){return this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this.margins=i,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this.beforeBuildLabels(),this.buildLabels(),this.afterBuildLabels(),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate(),this.minSize},afterUpdate:e.noop,beforeSetDimensions:e.noop,setDimensions:function(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0,this.minSize={width:0,height:0}},afterSetDimensions:e.noop,beforeBuildLabels:e.noop,buildLabels:function(){this.legendItems=this.options.labels.generateLabels.call(this,this.chart),this.options.reverse&&this.legendItems.reverse()},afterBuildLabels:e.noop,beforeFit:e.noop,fit:function(){var i=this.ctx,s=e.getValueOrDefault(this.options.labels.fontSize,t.defaults.global.defaultFontSize),a=e.getValueOrDefault(this.options.labels.fontStyle,t.defaults.global.defaultFontStyle),o=e.getValueOrDefault(this.options.labels.fontFamily,t.defaults.global.defaultFontFamily),n=e.fontString(s,a,o);if(this.legendHitBoxes=[],this.isHorizontal()?this.minSize.width=this.maxWidth:this.minSize.width=this.options.display?10:0,this.isHorizontal()?this.minSize.height=this.options.display?10:0:this.minSize.height=this.maxHeight,this.options.display&&this.isHorizontal()){this.lineWidths=[0];var r=this.legendItems.length?s+this.options.labels.padding:0;i.textAlign="left",i.textBaseline="top",i.font=n,e.each(this.legendItems,function(t,e){var a=this.options.labels.boxWidth+s/2+i.measureText(t.text).width;this.lineWidths[this.lineWidths.length-1]+a+this.options.labels.padding>=this.width&&(r+=s+this.options.labels.padding,this.lineWidths[this.lineWidths.length]=this.left),this.legendHitBoxes[e]={left:0,top:0,width:a,height:s},this.lineWidths[this.lineWidths.length-1]+=a+this.options.labels.padding},this),this.minSize.height+=r}this.width=this.minSize.width,this.height=this.minSize.height},afterFit:e.noop,isHorizontal:function(){return"top"===this.options.position||"bottom"===this.options.position},draw:function(){if(this.options.display){var i=this.ctx,s={x:this.left+(this.width-this.lineWidths[0])/2,y:this.top+this.options.labels.padding,line:0},a=e.getValueOrDefault(this.options.labels.fontColor,t.defaults.global.defaultFontColor),o=e.getValueOrDefault(this.options.labels.fontSize,t.defaults.global.defaultFontSize),n=e.getValueOrDefault(this.options.labels.fontStyle,t.defaults.global.defaultFontStyle),r=e.getValueOrDefault(this.options.labels.fontFamily,t.defaults.global.defaultFontFamily),h=e.fontString(o,n,r);this.isHorizontal()&&(i.textAlign="left",i.textBaseline="top",i.lineWidth=.5,i.strokeStyle=a,i.fillStyle=a,i.font=h,e.each(this.legendItems,function(e,a){var n=i.measureText(e.text).width,r=this.options.labels.boxWidth+o/2+n;s.x+r>=this.width&&(s.y+=o+this.options.labels.padding,s.line++,s.x=this.left+(this.width-this.lineWidths[s.line])/2),i.save();var h=function(t,e){return void 0!==t?t:e};i.fillStyle=h(e.fillStyle,t.defaults.global.defaultColor),i.lineCap=h(e.lineCap,t.defaults.global.elements.line.borderCapStyle),i.lineDashOffset=h(e.lineDashOffset,t.defaults.global.elements.line.borderDashOffset),i.lineJoin=h(e.lineJoin,t.defaults.global.elements.line.borderJoinStyle),i.lineWidth=h(e.lineWidth,t.defaults.global.elements.line.borderWidth),i.strokeStyle=h(e.strokeStyle,t.defaults.global.defaultColor),i.setLineDash&&i.setLineDash(h(e.lineDash,t.defaults.global.elements.line.borderDash)),i.strokeRect(s.x,s.y,this.options.labels.boxWidth,o),i.fillRect(s.x,s.y,this.options.labels.boxWidth,o),i.restore(),this.legendHitBoxes[a].left=s.x,this.legendHitBoxes[a].top=s.y,i.fillText(e.text,this.options.labels.boxWidth+o/2+s.x,s.y),e.hidden&&(i.beginPath(),i.lineWidth=2,i.moveTo(this.options.labels.boxWidth+o/2+s.x,s.y+o/2),i.lineTo(this.options.labels.boxWidth+o/2+s.x+n,s.y+o/2),i.stroke()),s.x+=r+this.options.labels.padding},this))}},handleEvent:function(t){var i=e.getRelativePosition(t,this.chart.chart);if(i.x>=this.left&&i.x<=this.right&&i.y>=this.top&&i.y<=this.bottom)for(var s=0;s<this.legendHitBoxes.length;++s){var a=this.legendHitBoxes[s];if(i.x>=a.left&&i.x<=a.left+a.width&&i.y>=a.top&&i.y<=a.top+a.height){this.options.onClick&&this.options.onClick.call(this,t,this.legendItems[s]);break}}}})}},{}],23:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.plugins=[],t.pluginService={register:function(e){-1===t.plugins.indexOf(e)&&t.plugins.push(e)},remove:function(e){var i=t.plugins.indexOf(e);-1!==i&&t.plugins.splice(i,1)},notifyPlugins:function(i,s,a){e.each(t.plugins,function(t){t[i]&&"function"==typeof t[i]&&t[i].apply(a,s)},a)}},t.PluginBase=t.Element.extend({beforeInit:e.noop,afterInit:e.noop,beforeUpdate:e.noop,afterUpdate:e.noop,beforeDraw:e.noop,afterDraw:e.noop,destroy:e.noop})}},{}],24:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.scale={display:!0,position:"left",gridLines:{display:!0,color:"rgba(0, 0, 0, 0.1)",lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickMarkLength:10,zeroLineWidth:1,zeroLineColor:"rgba(0,0,0,0.25)",offsetGridLines:!1},scaleLabel:{labelString:"",display:!1},ticks:{beginAtZero:!1,maxRotation:50,mirror:!1,padding:10,reverse:!1,display:!0,autoSkip:!0,autoSkipPadding:0,callback:function(t){return""+t}}},t.Scale=t.Element.extend({beforeUpdate:function(){e.callCallback(this.options.beforeUpdate,[this])},update:function(t,i,s){return this.beforeUpdate(),this.maxWidth=t,this.maxHeight=i,this.margins=e.extend({left:0,right:0,top:0,bottom:0},s),this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this.beforeBuildTicks(),this.buildTicks(),this.afterBuildTicks(),this.beforeTickToLabelConversion(),this.convertTicksToLabels(),this.afterTickToLabelConversion(),this.beforeCalculateTickRotation(),this.calculateTickRotation(),this.afterCalculateTickRotation(),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate(),this.minSize},afterUpdate:function(){e.callCallback(this.options.afterUpdate,[this])},beforeSetDimensions:function(){e.callCallback(this.options.beforeSetDimensions,[this])},setDimensions:function(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0},afterSetDimensions:function(){e.callCallback(this.options.afterSetDimensions,[this])},beforeDataLimits:function(){e.callCallback(this.options.beforeDataLimits,[this])},determineDataLimits:e.noop,afterDataLimits:function(){e.callCallback(this.options.afterDataLimits,[this])},beforeBuildTicks:function(){e.callCallback(this.options.beforeBuildTicks,[this])},buildTicks:e.noop,afterBuildTicks:function(){e.callCallback(this.options.afterBuildTicks,[this])},beforeTickToLabelConversion:function(){e.callCallback(this.options.beforeTickToLabelConversion,[this])},convertTicksToLabels:function(){this.ticks=this.ticks.map(function(t,e,i){return this.options.ticks.userCallback?this.options.ticks.userCallback(t,e,i):this.options.ticks.callback(t,e,i)},this)},afterTickToLabelConversion:function(){e.callCallback(this.options.afterTickToLabelConversion,[this])},beforeCalculateTickRotation:function(){e.callCallback(this.options.beforeCalculateTickRotation,[this])},calculateTickRotation:function(){var i=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize),s=e.getValueOrDefault(this.options.ticks.fontStyle,t.defaults.global.defaultFontStyle),a=e.getValueOrDefault(this.options.ticks.fontFamily,t.defaults.global.defaultFontFamily),o=e.fontString(i,s,a);this.ctx.font=o;var n,r=this.ctx.measureText(this.ticks[0]).width,h=this.ctx.measureText(this.ticks[this.ticks.length-1]).width;if(this.labelRotation=0,this.paddingRight=0,this.paddingLeft=0,this.options.display&&this.isHorizontal()){this.paddingRight=h/2+3,this.paddingLeft=r/2+3,this.longestTextCache||(this.longestTextCache={});for(var l,c,d=e.longestText(this.ctx,o,this.ticks,this.longestTextCache),u=d,f=this.getPixelForTick(1)-this.getPixelForTick(0)-6;u>f&&this.labelRotation<this.options.ticks.maxRotation;){if(l=Math.cos(e.toRadians(this.labelRotation)),c=Math.sin(e.toRadians(this.labelRotation)),n=l*r,n+i/2>this.yLabelWidth&&(this.paddingLeft=n+i/2),this.paddingRight=i/2,c*d>this.maxHeight){this.labelRotation--;break}this.labelRotation++,u=l*d}}this.margins&&(this.paddingLeft=Math.max(this.paddingLeft-this.margins.left,0),this.paddingRight=Math.max(this.paddingRight-this.margins.right,0))},afterCalculateTickRotation:function(){e.callCallback(this.options.afterCalculateTickRotation,[this])},beforeFit:function(){e.callCallback(this.options.beforeFit,[this])},fit:function(){this.minSize={width:0,height:0};var i=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize),s=e.getValueOrDefault(this.options.ticks.fontStyle,t.defaults.global.defaultFontStyle),a=e.getValueOrDefault(this.options.ticks.fontFamily,t.defaults.global.defaultFontFamily),o=e.fontString(i,s,a),n=e.getValueOrDefault(this.options.scaleLabel.fontSize,t.defaults.global.defaultFontSize),r=e.getValueOrDefault(this.options.scaleLabel.fontStyle,t.defaults.global.defaultFontStyle),h=e.getValueOrDefault(this.options.scaleLabel.fontFamily,t.defaults.global.defaultFontFamily);e.fontString(n,r,h);if(this.isHorizontal()?this.minSize.width=this.isFullWidth()?this.maxWidth-this.margins.left-this.margins.right:this.maxWidth:this.minSize.width=this.options.gridLines.tickMarkLength,this.isHorizontal()?this.minSize.height=this.options.gridLines.tickMarkLength:this.minSize.height=this.maxHeight,this.options.scaleLabel.display&&(this.isHorizontal()?this.minSize.height+=1.5*n:this.minSize.width+=1.5*n),this.options.ticks.display&&this.options.display){this.longestTextCache||(this.longestTextCache={});var l=e.longestText(this.ctx,o,this.ticks,this.longestTextCache);if(this.isHorizontal()){this.longestLabelWidth=l;var c=Math.sin(e.toRadians(this.labelRotation))*this.longestLabelWidth+1.5*i;this.minSize.height=Math.min(this.maxHeight,this.minSize.height+c),this.ctx.font=o;var d=this.ctx.measureText(this.ticks[0]).width,u=this.ctx.measureText(this.ticks[this.ticks.length-1]).width,f=Math.cos(e.toRadians(this.labelRotation)),g=Math.sin(e.toRadians(this.labelRotation));this.paddingLeft=0!==this.labelRotation?f*d+3:d/2+3,this.paddingRight=0!==this.labelRotation?g*(i/2)+3:u/2+3}else{var m=this.maxWidth-this.minSize.width;this.options.ticks.mirror||(l+=this.options.ticks.padding),m>l?this.minSize.width+=l:this.minSize.width=this.maxWidth,this.paddingTop=i/2,this.paddingBottom=i/2}}this.margins&&(this.paddingLeft=Math.max(this.paddingLeft-this.margins.left,0),this.paddingTop=Math.max(this.paddingTop-this.margins.top,0),this.paddingRight=Math.max(this.paddingRight-this.margins.right,0),this.paddingBottom=Math.max(this.paddingBottom-this.margins.bottom,0)),this.width=this.minSize.width,this.height=this.minSize.height},afterFit:function(){e.callCallback(this.options.afterFit,[this])},isHorizontal:function(){return"top"===this.options.position||"bottom"===this.options.position},isFullWidth:function(){return this.options.fullWidth},getRightValue:function i(t){return null===t||"undefined"==typeof t?NaN:"number"==typeof t&&isNaN(t)?NaN:"object"==typeof t?t instanceof Date?t:i(this.isHorizontal()?t.x:t.y):t},getLabelForIndex:e.noop,getPixelForValue:e.noop,getValueForPixel:e.noop,getPixelForTick:function(t,e){if(this.isHorizontal()){var i=this.width-(this.paddingLeft+this.paddingRight),s=i/Math.max(this.ticks.length-(this.options.gridLines.offsetGridLines?0:1),1),a=s*t+this.paddingLeft;e&&(a+=s/2);var o=this.left+Math.round(a);return o+=this.isFullWidth()?this.margins.left:0}var n=this.height-(this.paddingTop+this.paddingBottom);return this.top+t*(n/(this.ticks.length-1))},getPixelForDecimal:function(t){if(this.isHorizontal()){var e=this.width-(this.paddingLeft+this.paddingRight),i=e*t+this.paddingLeft,s=this.left+Math.round(i);return s+=this.isFullWidth()?this.margins.left:0}return this.top+t*this.height},draw:function(i){if(this.options.display){var s,a,o,n,r,h=0!==this.labelRotation,l=this.options.ticks.autoSkip;this.options.ticks.maxTicksLimit&&(r=this.options.ticks.maxTicksLimit);var c=e.getValueOrDefault(this.options.ticks.fontColor,t.defaults.global.defaultFontColor),d=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize),u=e.getValueOrDefault(this.options.ticks.fontStyle,t.defaults.global.defaultFontStyle),f=e.getValueOrDefault(this.options.ticks.fontFamily,t.defaults.global.defaultFontFamily),g=e.fontString(d,u,f),m=this.options.gridLines.tickMarkLength,p=e.getValueOrDefault(this.options.scaleLabel.fontColor,t.defaults.global.defaultFontColor),b=e.getValueOrDefault(this.options.scaleLabel.fontSize,t.defaults.global.defaultFontSize),v=e.getValueOrDefault(this.options.scaleLabel.fontStyle,t.defaults.global.defaultFontStyle),x=e.getValueOrDefault(this.options.scaleLabel.fontFamily,t.defaults.global.defaultFontFamily),y=e.fontString(b,v,x),k=Math.cos(e.toRadians(this.labelRotation)),_=(Math.sin(e.toRadians(this.labelRotation)),this.longestLabelWidth*k);if(this.ctx.fillStyle=c,this.isHorizontal()){s=!0;var S="bottom"===this.options.position?this.top:this.bottom-m,w="bottom"===this.options.position?this.top+m:this.bottom;if(a=!1,(_/2+this.options.ticks.autoSkipPadding)*this.ticks.length>this.width-(this.paddingLeft+this.paddingRight)&&(a=1+Math.floor((_/2+this.options.ticks.autoSkipPadding)*this.ticks.length/(this.width-(this.paddingLeft+this.paddingRight)))),r&&this.ticks.length>r)for(;!a||this.ticks.length/(a||1)>r;)a||(a=1),a+=1;l||(a=!1),e.each(this.ticks,function(t,o){var n=this.ticks.length===o+1,r=a>1&&o%a>0||o%a===0&&o+a>this.ticks.length;if((!r||n)&&void 0!==t&&null!==t){var l=this.getPixelForTick(o),c=this.getPixelForTick(o,this.options.gridLines.offsetGridLines);this.options.gridLines.display&&(o===("undefined"!=typeof this.zeroLineIndex?this.zeroLineIndex:0)?(this.ctx.lineWidth=this.options.gridLines.zeroLineWidth,this.ctx.strokeStyle=this.options.gridLines.zeroLineColor,s=!0):s&&(this.ctx.lineWidth=this.options.gridLines.lineWidth,this.ctx.strokeStyle=this.options.gridLines.color,s=!1),l+=e.aliasPixel(this.ctx.lineWidth),this.ctx.beginPath(),this.options.gridLines.drawTicks&&(this.ctx.moveTo(l,S),this.ctx.lineTo(l,w)),this.options.gridLines.drawOnChartArea&&(this.ctx.moveTo(l,i.top),this.ctx.lineTo(l,i.bottom)),this.ctx.stroke()),this.options.ticks.display&&(this.ctx.save(),this.ctx.translate(c,h?this.top+12:"top"===this.options.position?this.bottom-m:this.top+m),this.ctx.rotate(-1*e.toRadians(this.labelRotation)),this.ctx.font=g,this.ctx.textAlign=h?"right":"center",this.ctx.textBaseline=h?"middle":"top"===this.options.position?"bottom":"top",this.ctx.fillText(t,0,0),this.ctx.restore())}},this),this.options.scaleLabel.display&&(this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillStyle=p,this.ctx.font=y,o=this.left+(this.right-this.left)/2,n="bottom"===this.options.position?this.bottom-b/2:this.top+b/2,this.ctx.fillText(this.options.scaleLabel.labelString,o,n))}else{s=!0;var D="right"===this.options.position?this.left:this.right-5,M="right"===this.options.position?this.left+5:this.right;if(e.each(this.ticks,function(t,a){if(void 0!==t&&null!==t){var o=this.getPixelForTick(a);if(this.options.gridLines.display&&(a===("undefined"!=typeof this.zeroLineIndex?this.zeroLineIndex:0)?(this.ctx.lineWidth=this.options.gridLines.zeroLineWidth,this.ctx.strokeStyle=this.options.gridLines.zeroLineColor,s=!0):s&&(this.ctx.lineWidth=this.options.gridLines.lineWidth,this.ctx.strokeStyle=this.options.gridLines.color,s=!1),o+=e.aliasPixel(this.ctx.lineWidth),this.ctx.beginPath(), this.options.gridLines.drawTicks&&(this.ctx.moveTo(D,o),this.ctx.lineTo(M,o)),this.options.gridLines.drawOnChartArea&&(this.ctx.moveTo(i.left,o),this.ctx.lineTo(i.right,o)),this.ctx.stroke()),this.options.ticks.display){var n,r=this.getPixelForTick(a,this.options.gridLines.offsetGridLines);this.ctx.save(),"left"===this.options.position?this.options.ticks.mirror?(n=this.right+this.options.ticks.padding,this.ctx.textAlign="left"):(n=this.right-this.options.ticks.padding,this.ctx.textAlign="right"):this.options.ticks.mirror?(n=this.left-this.options.ticks.padding,this.ctx.textAlign="right"):(n=this.left+this.options.ticks.padding,this.ctx.textAlign="left"),this.ctx.translate(n,r),this.ctx.rotate(-1*e.toRadians(this.labelRotation)),this.ctx.font=g,this.ctx.textBaseline="middle",this.ctx.fillText(t,0,0),this.ctx.restore()}}},this),this.options.scaleLabel.display){o="left"===this.options.position?this.left+b/2:this.right-b/2,n=this.top+(this.bottom-this.top)/2;var C="left"===this.options.position?-.5*Math.PI:.5*Math.PI;this.ctx.save(),this.ctx.translate(o,n),this.ctx.rotate(C),this.ctx.textAlign="center",this.ctx.fillStyle=p,this.ctx.font=y,this.ctx.textBaseline="middle",this.ctx.fillText(this.options.scaleLabel.labelString,0,0),this.ctx.restore()}}this.ctx.lineWidth=this.options.gridLines.lineWidth,this.ctx.strokeStyle=this.options.gridLines.color;var A=this.left,I=this.right,P=this.top,T=this.bottom;this.isHorizontal()?(P=T="top"===this.options.position?this.bottom:this.top,P+=e.aliasPixel(this.ctx.lineWidth),T+=e.aliasPixel(this.ctx.lineWidth)):(A=I="left"===this.options.position?this.right:this.left,A+=e.aliasPixel(this.ctx.lineWidth),I+=e.aliasPixel(this.ctx.lineWidth)),this.ctx.beginPath(),this.ctx.moveTo(A,P),this.ctx.lineTo(I,T),this.ctx.stroke()}}})}},{}],25:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.scaleService={constructors:{},defaults:{},registerScaleType:function(t,i,s){this.constructors[t]=i,this.defaults[t]=e.clone(s)},getScaleConstructor:function(t){return this.constructors.hasOwnProperty(t)?this.constructors[t]:void 0},getScaleDefaults:function(i){return this.defaults.hasOwnProperty(i)?e.scaleMerge(t.defaults.scale,this.defaults[i]):{}},addScalesToLayout:function(i){e.each(i.scales,function(e){t.layoutService.addBox(i,e)})}}}},{}],26:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.title={display:!1,position:"top",fullWidth:!0,fontStyle:"bold",padding:10,text:""},t.Title=t.Element.extend({initialize:function(i){e.extend(this,i),this.options=e.configMerge(t.defaults.global.title,i.options),this.legendHitBoxes=[]},beforeUpdate:e.noop,update:function(t,e,i){return this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this.margins=i,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this.beforeBuildLabels(),this.buildLabels(),this.afterBuildLabels(),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate(),this.minSize},afterUpdate:e.noop,beforeSetDimensions:e.noop,setDimensions:function(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0,this.minSize={width:0,height:0}},afterSetDimensions:e.noop,beforeBuildLabels:e.noop,buildLabels:e.noop,afterBuildLabels:e.noop,beforeFit:e.noop,fit:function(){var i=(this.ctx,e.getValueOrDefault(this.options.fontSize,t.defaults.global.defaultFontSize)),s=e.getValueOrDefault(this.options.fontStyle,t.defaults.global.defaultFontStyle),a=e.getValueOrDefault(this.options.fontFamily,t.defaults.global.defaultFontFamily);e.fontString(i,s,a);this.isHorizontal()?this.minSize.width=this.maxWidth:this.minSize.width=0,this.isHorizontal()?this.minSize.height=0:this.minSize.height=this.maxHeight,this.isHorizontal()?this.options.display&&(this.minSize.height+=i+2*this.options.padding):this.options.display&&(this.minSize.width+=i+2*this.options.padding),this.width=this.minSize.width,this.height=this.minSize.height},afterFit:e.noop,isHorizontal:function(){return"top"===this.options.position||"bottom"===this.options.position},draw:function(){if(this.options.display){var i,s,a=this.ctx,o=e.getValueOrDefault(this.options.fontColor,t.defaults.global.defaultFontColor),n=e.getValueOrDefault(this.options.fontSize,t.defaults.global.defaultFontSize),r=e.getValueOrDefault(this.options.fontStyle,t.defaults.global.defaultFontStyle),h=e.getValueOrDefault(this.options.fontFamily,t.defaults.global.defaultFontFamily),l=e.fontString(n,r,h);if(a.fillStyle=o,a.font=l,this.isHorizontal())a.textAlign="center",a.textBaseline="middle",i=this.left+(this.right-this.left)/2,s=this.top+(this.bottom-this.top)/2,a.fillText(this.options.text,i,s);else{i="left"===this.options.position?this.left+n/2:this.right-n/2,s=this.top+(this.bottom-this.top)/2;var c="left"===this.options.position?-.5*Math.PI:.5*Math.PI;a.save(),a.translate(i,s),a.rotate(c),a.textAlign="center",a.textBaseline="middle",a.fillText(this.options.text,0,0),a.restore()}}}})}},{}],27:[function(t,e,i){"use strict";e.exports=function(t){function e(t,e){return e&&(i.isArray(e)?t=t.concat(e):t.push(e)),t}var i=t.helpers;t.defaults.global.tooltips={enabled:!0,custom:null,mode:"single",backgroundColor:"rgba(0,0,0,0.8)",titleFontStyle:"bold",titleSpacing:2,titleMarginBottom:6,titleColor:"#fff",titleAlign:"left",bodySpacing:2,bodyColor:"#fff",bodyAlign:"left",footerFontStyle:"bold",footerSpacing:2,footerMarginTop:6,footerColor:"#fff",footerAlign:"left",yPadding:6,xPadding:6,yAlign:"center",xAlign:"center",caretSize:5,cornerRadius:6,multiKeyBackground:"#fff",callbacks:{beforeTitle:i.noop,title:function(t,e){var i="";return t.length>0&&(t[0].xLabel?i=t[0].xLabel:e.labels.length>0&&t[0].index<e.labels.length&&(i=e.labels[t[0].index])),i},afterTitle:i.noop,beforeBody:i.noop,beforeLabel:i.noop,label:function(t,e){var i=e.datasets[t.datasetIndex].label||"";return i+": "+t.yLabel},afterLabel:i.noop,afterBody:i.noop,beforeFooter:i.noop,footer:i.noop,afterFooter:i.noop}},t.Tooltip=t.Element.extend({initialize:function(){var e=this._options;i.extend(this,{_model:{xPadding:e.tooltips.xPadding,yPadding:e.tooltips.yPadding,xAlign:e.tooltips.yAlign,yAlign:e.tooltips.xAlign,bodyColor:e.tooltips.bodyColor,_bodyFontFamily:i.getValueOrDefault(e.tooltips.bodyFontFamily,t.defaults.global.defaultFontFamily),_bodyFontStyle:i.getValueOrDefault(e.tooltips.bodyFontStyle,t.defaults.global.defaultFontStyle),_bodyAlign:e.tooltips.bodyAlign,bodyFontSize:i.getValueOrDefault(e.tooltips.bodyFontSize,t.defaults.global.defaultFontSize),bodySpacing:e.tooltips.bodySpacing,titleColor:e.tooltips.titleColor,_titleFontFamily:i.getValueOrDefault(e.tooltips.titleFontFamily,t.defaults.global.defaultFontFamily),_titleFontStyle:i.getValueOrDefault(e.tooltips.titleFontStyle,t.defaults.global.defaultFontStyle),titleFontSize:i.getValueOrDefault(e.tooltips.titleFontSize,t.defaults.global.defaultFontSize),_titleAlign:e.tooltips.titleAlign,titleSpacing:e.tooltips.titleSpacing,titleMarginBottom:e.tooltips.titleMarginBottom,footerColor:e.tooltips.footerColor,_footerFontFamily:i.getValueOrDefault(e.tooltips.footerFontFamily,t.defaults.global.defaultFontFamily),_footerFontStyle:i.getValueOrDefault(e.tooltips.footerFontStyle,t.defaults.global.defaultFontStyle),footerFontSize:i.getValueOrDefault(e.tooltips.footerFontSize,t.defaults.global.defaultFontSize),_footerAlign:e.tooltips.footerAlign,footerSpacing:e.tooltips.footerSpacing,footerMarginTop:e.tooltips.footerMarginTop,caretSize:e.tooltips.caretSize,cornerRadius:e.tooltips.cornerRadius,backgroundColor:e.tooltips.backgroundColor,opacity:0,legendColorBackground:e.tooltips.multiKeyBackground}})},getTitle:function(){var t=this._options.tooltips.callbacks.beforeTitle.apply(this,arguments),i=this._options.tooltips.callbacks.title.apply(this,arguments),s=this._options.tooltips.callbacks.afterTitle.apply(this,arguments),a=[];return a=e(a,t),a=e(a,i),a=e(a,s)},getBeforeBody:function(){var t=this._options.tooltips.callbacks.beforeBody.apply(this,arguments);return i.isArray(t)?t:void 0!==t?[t]:[]},getBody:function(t,e){var s=[];return i.each(t,function(t){i.pushAllIfDefined(this._options.tooltips.callbacks.beforeLabel.call(this,t,e),s),i.pushAllIfDefined(this._options.tooltips.callbacks.label.call(this,t,e),s),i.pushAllIfDefined(this._options.tooltips.callbacks.afterLabel.call(this,t,e),s)},this),s},getAfterBody:function(){var t=this._options.tooltips.callbacks.afterBody.apply(this,arguments);return i.isArray(t)?t:void 0!==t?[t]:[]},getFooter:function(){var t=this._options.tooltips.callbacks.beforeFooter.apply(this,arguments),i=this._options.tooltips.callbacks.footer.apply(this,arguments),s=this._options.tooltips.callbacks.afterFooter.apply(this,arguments),a=[];return a=e(a,t),a=e(a,i),a=e(a,s)},getAveragePosition:function(t){if(!t.length)return!1;var e=[],s=[];i.each(t,function(t){if(t){var i=t.tooltipPosition();e.push(i.x),s.push(i.y)}});for(var a=0,o=0,n=0;n<e.length;n++)a+=e[n],o+=s[n];return{x:Math.round(a/e.length),y:Math.round(o/e.length)}},update:function(t){if(this._active.length){this._model.opacity=1;var e,s=this._active[0],a=[],o=[];if("single"===this._options.tooltips.mode){var n=s._yScale||s._scale;o.push({xLabel:s._xScale?s._xScale.getLabelForIndex(s._index,s._datasetIndex):"",yLabel:n?n.getLabelForIndex(s._index,s._datasetIndex):"",index:s._index,datasetIndex:s._datasetIndex}),e=this.getAveragePosition(this._active)}else i.each(this._data.datasets,function(t,e){if(this._chartInstance.isDatasetVisible(e)){var i=this._chartInstance.getDatasetMeta(e),a=i.data[s._index];if(a){var n=s._yScale||s._scale;o.push({xLabel:a._xScale?a._xScale.getLabelForIndex(a._index,a._datasetIndex):"",yLabel:n?n.getLabelForIndex(a._index,a._datasetIndex):"",index:s._index,datasetIndex:e})}}},this),i.each(this._active,function(t){t&&a.push({borderColor:t._view.borderColor,backgroundColor:t._view.backgroundColor})},null),e=this.getAveragePosition(this._active);i.extend(this._model,{title:this.getTitle(o,this._data),beforeBody:this.getBeforeBody(o,this._data),body:this.getBody(o,this._data),afterBody:this.getAfterBody(o,this._data),footer:this.getFooter(o,this._data)}),i.extend(this._model,{x:Math.round(e.x),y:Math.round(e.y),caretPadding:i.getValueOrDefault(e.padding,2),labelColors:a});var r=this.getTooltipSize(this._model);this.determineAlignment(r),i.extend(this._model,this.getBackgroundPoint(this._model,r))}else this._model.opacity=0;return t&&this._options.tooltips.custom&&this._options.tooltips.custom.call(this,this._model),this},getTooltipSize:function(t){var e=this._chart.ctx,s={height:2*t.yPadding,width:0},a=t.body.length+t.beforeBody.length+t.afterBody.length;return s.height+=t.title.length*t.titleFontSize,s.height+=(t.title.length-1)*t.titleSpacing,s.height+=t.title.length?t.titleMarginBottom:0,s.height+=a*t.bodyFontSize,s.height+=a?(a-1)*t.bodySpacing:0,s.height+=t.footer.length?t.footerMarginTop:0,s.height+=t.footer.length*t.footerFontSize,s.height+=t.footer.length?(t.footer.length-1)*t.footerSpacing:0,e.font=i.fontString(t.titleFontSize,t._titleFontStyle,t._titleFontFamily),i.each(t.title,function(t){s.width=Math.max(s.width,e.measureText(t).width)}),e.font=i.fontString(t.bodyFontSize,t._bodyFontStyle,t._bodyFontFamily),i.each(t.beforeBody.concat(t.afterBody),function(t){s.width=Math.max(s.width,e.measureText(t).width)}),i.each(t.body,function(i){s.width=Math.max(s.width,e.measureText(i).width+("single"!==this._options.tooltips.mode?t.bodyFontSize+2:0))},this),e.font=i.fontString(t.footerFontSize,t._footerFontStyle,t._footerFontFamily),i.each(t.footer,function(t){s.width=Math.max(s.width,e.measureText(t).width)}),s.width+=2*t.xPadding,s},determineAlignment:function(t){this._model.y<t.height?this._model.yAlign="top":this._model.y>this._chart.height-t.height&&(this._model.yAlign="bottom");var e,i,s,a,o,n=this,r=(this._chartInstance.chartArea.left+this._chartInstance.chartArea.right)/2,h=(this._chartInstance.chartArea.top+this._chartInstance.chartArea.bottom)/2;"center"===this._model.yAlign?(e=function(t){return r>=t},i=function(t){return t>r}):(e=function(e){return e<=t.width/2},i=function(e){return e>=n._chart.width-t.width/2}),s=function(e){return e+t.width>n._chart.width},a=function(e){return e-t.width<0},o=function(t){return h>=t?"top":"bottom"},e(this._model.x)?(this._model.xAlign="left",s(this._model.x)&&(this._model.xAlign="center",this._model.yAlign=o(this._model.y))):i(this._model.x)&&(this._model.xAlign="right",a(this._model.x)&&(this._model.xAlign="center",this._model.yAlign=o(this._model.y)))},getBackgroundPoint:function(t,e){var i={x:t.x,y:t.y};return"right"===t.xAlign?i.x-=e.width:"center"===t.xAlign&&(i.x-=e.width/2),"top"===t.yAlign?i.y+=t.caretPadding+t.caretSize:"bottom"===t.yAlign?i.y-=e.height+t.caretPadding+t.caretSize:i.y-=e.height/2,"center"===t.yAlign?"left"===t.xAlign?i.x+=t.caretPadding+t.caretSize:"right"===t.xAlign&&(i.x-=t.caretPadding+t.caretSize):"left"===t.xAlign?i.x-=t.cornerRadius+t.caretPadding:"right"===t.xAlign&&(i.x+=t.cornerRadius+t.caretPadding),i},drawCaret:function(t,e,s,a){var o,n,r,h,l,c,d=this._view,u=this._chart.ctx;"center"===d.yAlign?("left"===d.xAlign?(o=t.x,n=o-d.caretSize,r=o):(o=t.x+e.width,n=o+d.caretSize,r=o),l=t.y+e.height/2,h=l-d.caretSize,c=l+d.caretSize):("left"===d.xAlign?(o=t.x+d.cornerRadius,n=o+d.caretSize,r=n+d.caretSize):"right"===d.xAlign?(o=t.x+e.width-d.cornerRadius,n=o-d.caretSize,r=n-d.caretSize):(n=t.x+e.width/2,o=n-d.caretSize,r=n+d.caretSize),"top"===d.yAlign?(h=t.y,l=h-d.caretSize,c=h):(h=t.y+e.height,l=h+d.caretSize,c=h));var f=i.color(d.backgroundColor);u.fillStyle=f.alpha(s*f.alpha()).rgbString(),u.beginPath(),u.moveTo(o,h),u.lineTo(n,l),u.lineTo(r,c),u.closePath(),u.fill()},drawTitle:function(t,e,s,a){if(e.title.length){s.textAlign=e._titleAlign,s.textBaseline="top";var o=i.color(e.titleColor);s.fillStyle=o.alpha(a*o.alpha()).rgbString(),s.font=i.fontString(e.titleFontSize,e._titleFontStyle,e._titleFontFamily),i.each(e.title,function(i,a){s.fillText(i,t.x,t.y),t.y+=e.titleFontSize+e.titleSpacing,a+1===e.title.length&&(t.y+=e.titleMarginBottom-e.titleSpacing)})}},drawBody:function(t,e,s,a){s.textAlign=e._bodyAlign,s.textBaseline="top";var o=i.color(e.bodyColor);s.fillStyle=o.alpha(a*o.alpha()).rgbString(),s.font=i.fontString(e.bodyFontSize,e._bodyFontStyle,e._bodyFontFamily),i.each(e.beforeBody,function(i){s.fillText(i,t.x,t.y),t.y+=e.bodyFontSize+e.bodySpacing}),i.each(e.body,function(o,n){"single"!==this._options.tooltips.mode&&(s.fillStyle=i.color(e.legendColorBackground).alpha(a).rgbaString(),s.fillRect(t.x,t.y,e.bodyFontSize,e.bodyFontSize),s.strokeStyle=i.color(e.labelColors[n].borderColor).alpha(a).rgbaString(),s.strokeRect(t.x,t.y,e.bodyFontSize,e.bodyFontSize),s.fillStyle=i.color(e.labelColors[n].backgroundColor).alpha(a).rgbaString(),s.fillRect(t.x+1,t.y+1,e.bodyFontSize-2,e.bodyFontSize-2),s.fillStyle=i.color(e.bodyColor).alpha(a).rgbaString()),s.fillText(o,t.x+("single"!==this._options.tooltips.mode?e.bodyFontSize+2:0),t.y),t.y+=e.bodyFontSize+e.bodySpacing},this),i.each(e.afterBody,function(i){s.fillText(i,t.x,t.y),t.y+=e.bodyFontSize}),t.y-=e.bodySpacing},drawFooter:function(t,e,s,a){if(e.footer.length){t.y+=e.footerMarginTop,s.textAlign=e._footerAlign,s.textBaseline="top";var o=i.color(e.footerColor);s.fillStyle=o.alpha(a*o.alpha()).rgbString(),s.font=i.fontString(e.footerFontSize,e._footerFontStyle,e._footerFontFamily),i.each(e.footer,function(i){s.fillText(i,t.x,t.y),t.y+=e.footerFontSize+e.footerSpacing})}},draw:function(){var t=this._chart.ctx,e=this._view;if(0!==e.opacity){var s=e.caretPadding,a=this.getTooltipSize(e),o={x:e.x,y:e.y},n=Math.abs(e.opacity<.001)?0:e.opacity;if(this._options.tooltips.enabled){var r=i.color(e.backgroundColor);t.fillStyle=r.alpha(n*r.alpha()).rgbString(),i.drawRoundedRectangle(t,o.x,o.y,a.width,a.height,e.cornerRadius),t.fill(),this.drawCaret(o,a,n,s),o.x+=e.xPadding,o.y+=e.yPadding,this.drawTitle(o,e,t,n),this.drawBody(o,e,t,n),this.drawFooter(o,e,t,n)}}}})}},{}],28:[function(t,e,i){"use strict";e.exports=function(t,e){var i=t.helpers;t.defaults.global.elements.arc={backgroundColor:t.defaults.global.defaultColor,borderColor:"#fff",borderWidth:2},t.elements.Arc=t.Element.extend({inLabelRange:function(t){var e=this._view;return e?Math.pow(t-e.x,2)<Math.pow(e.radius+e.hoverRadius,2):!1},inRange:function(t,e){var s=this._view;if(s){for(var a=i.getAngleFromPoint(s,{x:t,y:e}),o=s.startAngle,n=s.endAngle;o>n;)n+=2*Math.PI;for(;a.angle>n;)a.angle-=2*Math.PI;for(;a.angle<o;)a.angle+=2*Math.PI;var r=a.angle>=o&&a.angle<=n,h=a.distance>=s.innerRadius&&a.distance<=s.outerRadius;return r&&h}return!1},tooltipPosition:function(){var t=this._view,e=t.startAngle+(t.endAngle-t.startAngle)/2,i=(t.outerRadius-t.innerRadius)/2+t.innerRadius;return{x:t.x+Math.cos(e)*i,y:t.y+Math.sin(e)*i}},draw:function(){var t=this._chart.ctx,e=this._view;t.beginPath(),t.arc(e.x,e.y,e.outerRadius,e.startAngle,e.endAngle),t.arc(e.x,e.y,e.innerRadius,e.endAngle,e.startAngle,!0),t.closePath(),t.strokeStyle=e.borderColor,t.lineWidth=e.borderWidth,t.fillStyle=e.backgroundColor,t.fill(),t.lineJoin="bevel",e.borderWidth&&t.stroke()}})}},{}],29:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.elements.line={tension:.4,backgroundColor:t.defaults.global.defaultColor,borderWidth:3,borderColor:t.defaults.global.defaultColor,borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",fill:!0},t.elements.Line=t.Element.extend({lineToNextPoint:function(t,e,i,s,a){var o=this._chart.ctx;e._view.skip?s.call(this,t,e,i):t._view.skip?a.call(this,t,e,i):0===e._view.tension?o.lineTo(e._view.x,e._view.y):o.bezierCurveTo(t._view.controlPointNextX,t._view.controlPointNextY,e._view.controlPointPreviousX,e._view.controlPointPreviousY,e._view.x,e._view.y)},draw:function(){function i(t){n._view.skip||r._view.skip?t&&o.lineTo(s._view.scaleZero.x,s._view.scaleZero.y):o.bezierCurveTo(r._view.controlPointNextX,r._view.controlPointNextY,n._view.controlPointPreviousX,n._view.controlPointPreviousY,n._view.x,n._view.y)}var s=this,a=this._view,o=this._chart.ctx,n=this._children[0],r=this._children[this._children.length-1];o.save(),this._children.length>0&&a.fill&&(o.beginPath(),e.each(this._children,function(t,i){var s=e.previousItem(this._children,i),n=e.nextItem(this._children,i);0===i?(this._loop?o.moveTo(a.scaleZero.x,a.scaleZero.y):o.moveTo(t._view.x,a.scaleZero),t._view.skip?this._loop||o.moveTo(n._view.x,this._view.scaleZero):o.lineTo(t._view.x,t._view.y)):this.lineToNextPoint(s,t,n,function(t,e,i){this._loop?o.lineTo(this._view.scaleZero.x,this._view.scaleZero.y):(o.lineTo(t._view.x,this._view.scaleZero),o.moveTo(i._view.x,this._view.scaleZero))},function(t,e){o.lineTo(e._view.x,e._view.y)})},this),this._loop?i(!0):(o.lineTo(this._children[this._children.length-1]._view.x,a.scaleZero),o.lineTo(this._children[0]._view.x,a.scaleZero)),o.fillStyle=a.backgroundColor||t.defaults.global.defaultColor,o.closePath(),o.fill()),o.lineCap=a.borderCapStyle||t.defaults.global.elements.line.borderCapStyle,o.setLineDash&&o.setLineDash(a.borderDash||t.defaults.global.elements.line.borderDash),o.lineDashOffset=a.borderDashOffset||t.defaults.global.elements.line.borderDashOffset,o.lineJoin=a.borderJoinStyle||t.defaults.global.elements.line.borderJoinStyle,o.lineWidth=a.borderWidth||t.defaults.global.elements.line.borderWidth,o.strokeStyle=a.borderColor||t.defaults.global.defaultColor,o.beginPath(),e.each(this._children,function(t,i){var s=e.previousItem(this._children,i),a=e.nextItem(this._children,i);0===i?o.moveTo(t._view.x,t._view.y):this.lineToNextPoint(s,t,a,function(t,e,i){o.moveTo(i._view.x,i._view.y)},function(t,e){o.moveTo(e._view.x,e._view.y)})},this),this._loop&&this._children.length>0&&i(),o.stroke(),o.restore()}})}},{}],30:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers;t.defaults.global.elements.point={radius:3,pointStyle:"circle",backgroundColor:t.defaults.global.defaultColor,borderWidth:1,borderColor:t.defaults.global.defaultColor,hitRadius:1,hoverRadius:4,hoverBorderWidth:1},t.elements.Point=t.Element.extend({inRange:function(t,e){var i=this._view;if(i){var s=i.hitRadius+i.radius;return Math.pow(t-i.x,2)+Math.pow(e-i.y,2)<Math.pow(s,2)}return!1},inLabelRange:function(t){var e=this._view;return e?Math.pow(t-e.x,2)<Math.pow(e.radius+e.hitRadius,2):!1},tooltipPosition:function(){var t=this._view;return{x:t.x,y:t.y,padding:t.radius+t.borderWidth}},draw:function(){var i=this._view,s=this._chart.ctx;if(!i.skip){if("object"==typeof i.pointStyle&&("[object HTMLImageElement]"===i.pointStyle.toString()||"[object HTMLCanvasElement]"===i.pointStyle.toString()))return void s.drawImage(i.pointStyle,i.x-i.pointStyle.width/2,i.y-i.pointStyle.height/2);if(!isNaN(i.radius)&&i.radius>0){s.strokeStyle=i.borderColor||t.defaults.global.defaultColor,s.lineWidth=e.getValueOrDefault(i.borderWidth,t.defaults.global.elements.point.borderWidth),s.fillStyle=i.backgroundColor||t.defaults.global.defaultColor;var a,o,n=i.radius;switch(i.pointStyle){default:s.beginPath(),s.arc(i.x,i.y,n,0,2*Math.PI),s.closePath(),s.fill();break;case"triangle":s.beginPath();var r=3*n/Math.sqrt(3),h=r*Math.sqrt(3)/2;s.moveTo(i.x-r/2,i.y+h/3),s.lineTo(i.x+r/2,i.y+h/3),s.lineTo(i.x,i.y-2*h/3),s.closePath(),s.fill();break;case"rect":s.fillRect(i.x-1/Math.SQRT2*n,i.y-1/Math.SQRT2*n,2/Math.SQRT2*n,2/Math.SQRT2*n),s.strokeRect(i.x-1/Math.SQRT2*n,i.y-1/Math.SQRT2*n,2/Math.SQRT2*n,2/Math.SQRT2*n);break;case"rectRot":s.translate(i.x,i.y),s.rotate(Math.PI/4),s.fillRect(-1/Math.SQRT2*n,-1/Math.SQRT2*n,2/Math.SQRT2*n,2/Math.SQRT2*n),s.strokeRect(-1/Math.SQRT2*n,-1/Math.SQRT2*n,2/Math.SQRT2*n,2/Math.SQRT2*n),s.setTransform(1,0,0,1,0,0);break;case"cross":s.beginPath(),s.moveTo(i.x,i.y+n),s.lineTo(i.x,i.y-n),s.moveTo(i.x-n,i.y),s.lineTo(i.x+n,i.y),s.closePath();break;case"crossRot":s.beginPath(),a=Math.cos(Math.PI/4)*n,o=Math.sin(Math.PI/4)*n,s.moveTo(i.x-a,i.y-o),s.lineTo(i.x+a,i.y+o),s.moveTo(i.x-a,i.y+o),s.lineTo(i.x+a,i.y-o),s.closePath();break;case"star":s.beginPath(),s.moveTo(i.x,i.y+n),s.lineTo(i.x,i.y-n),s.moveTo(i.x-n,i.y),s.lineTo(i.x+n,i.y),a=Math.cos(Math.PI/4)*n,o=Math.sin(Math.PI/4)*n,s.moveTo(i.x-a,i.y-o),s.lineTo(i.x+a,i.y+o),s.moveTo(i.x-a,i.y+o),s.lineTo(i.x+a,i.y-o),s.closePath();break;case"line":s.beginPath(),s.moveTo(i.x-n,i.y),s.lineTo(i.x+n,i.y),s.closePath();break;case"dash":s.beginPath(),s.moveTo(i.x,i.y),s.lineTo(i.x+n,i.y),s.closePath()}s.stroke()}}}})}},{}],31:[function(t,e,i){"use strict";e.exports=function(t){t.helpers;t.defaults.global.elements.rectangle={backgroundColor:t.defaults.global.defaultColor,borderWidth:0,borderColor:t.defaults.global.defaultColor,borderSkipped:"bottom"},t.elements.Rectangle=t.Element.extend({draw:function(){function t(t){return h[(c+t)%4]}var e=this._chart.ctx,i=this._view,s=i.width/2,a=i.x-s,o=i.x+s,n=i.base-(i.base-i.y),r=i.borderWidth/2;i.borderWidth&&(a+=r,o-=r,n+=r),e.beginPath(),e.fillStyle=i.backgroundColor,e.strokeStyle=i.borderColor,e.lineWidth=i.borderWidth;var h=[[a,i.base],[a,n],[o,n],[o,i.base]],l=["bottom","left","top","right"],c=l.indexOf(i.borderSkipped,0);-1===c&&(c=0),e.moveTo.apply(e,t(0));for(var d=1;4>d;d++)e.lineTo.apply(e,t(d));e.fill(),i.borderWidth&&e.stroke()},height:function(){var t=this._view;return t.base-t.y},inRange:function(t,e){var i=this._view,s=!1;return i&&(s=i.y<i.base?t>=i.x-i.width/2&&t<=i.x+i.width/2&&e>=i.y&&e<=i.base:t>=i.x-i.width/2&&t<=i.x+i.width/2&&e>=i.base&&e<=i.y),s},inLabelRange:function(t){var e=this._view;return e?t>=e.x-e.width/2&&t<=e.x+e.width/2:!1},tooltipPosition:function(){var t=this._view;return{x:t.x,y:t.y}}})}},{}],32:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers,i={position:"bottom"},s=t.Scale.extend({determineDataLimits:function(){this.minIndex=0,this.maxIndex=this.chart.data.labels.length-1;var t;void 0!==this.options.ticks.min&&(t=e.indexOf(this.chart.data.labels,this.options.ticks.min),this.minIndex=-1!==t?t:this.minIndex),void 0!==this.options.ticks.max&&(t=e.indexOf(this.chart.data.labels,this.options.ticks.max),this.maxIndex=-1!==t?t:this.maxIndex),this.min=this.chart.data.labels[this.minIndex],this.max=this.chart.data.labels[this.maxIndex]},buildTicks:function(t){this.ticks=0===this.minIndex&&this.maxIndex===this.chart.data.labels.length-1?this.chart.data.labels:this.chart.data.labels.slice(this.minIndex,this.maxIndex+1)},getLabelForIndex:function(t,e){return this.ticks[t]},getPixelForValue:function(t,e,i,s){var a=Math.max(this.maxIndex+1-this.minIndex-(this.options.gridLines.offsetGridLines?0:1),1);if(this.isHorizontal()){var o=this.width-(this.paddingLeft+this.paddingRight),n=o/a,r=n*(e-this.minIndex)+this.paddingLeft;return this.options.gridLines.offsetGridLines&&s&&(r+=n/2),this.left+Math.round(r)}var h=this.height-(this.paddingTop+this.paddingBottom),l=h/a,c=l*(e-this.minIndex)+this.paddingTop;return this.options.gridLines.offsetGridLines&&s&&(c+=l/2),this.top+Math.round(c)},getPixelForTick:function(t,e){return this.getPixelForValue(this.ticks[t],t+this.minIndex,null,e)},getValueForPixel:function(t){var e,i=Math.max(this.ticks.length-(this.options.gridLines.offsetGridLines?0:1),1),s=this.isHorizontal(),a=s?this.width-(this.paddingLeft+this.paddingRight):this.height-(this.paddingTop+this.paddingBottom),o=a/i;return this.options.gridLines.offsetGridLines&&(t-=o/2),t-=s?this.paddingLeft:this.paddingTop,e=0>=t?0:Math.round(t/o)}});t.scaleService.registerScaleType("category",s,i)}},{}],33:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers,i={position:"left",ticks:{callback:function(t,i,s){var a=s.length>3?s[2]-s[1]:s[1]-s[0];Math.abs(a)>1&&t!==Math.floor(t)&&(a=t-Math.floor(t));var o=e.log10(Math.abs(a)),n="";if(0!==t){var r=-1*Math.floor(o);r=Math.max(Math.min(r,20),0),n=t.toFixed(r)}else n="0";return n}}},s=t.Scale.extend({determineDataLimits:function(){if(this.min=null,this.max=null,this.options.stacked){var t={},i=!1,s=!1;e.each(this.chart.data.datasets,function(a,o){var n=this.chart.getDatasetMeta(o);void 0===t[n.type]&&(t[n.type]={positiveValues:[],negativeValues:[]});var r=t[n.type].positiveValues,h=t[n.type].negativeValues;this.chart.isDatasetVisible(o)&&(this.isHorizontal()?n.xAxisID===this.id:n.yAxisID===this.id)&&e.each(a.data,function(t,e){var a=+this.getRightValue(t);isNaN(a)||n.data[e].hidden||(r[e]=r[e]||0,h[e]=h[e]||0,this.options.relativePoints?r[e]=100:0>a?(s=!0,h[e]+=a):(i=!0,r[e]+=a))},this)},this),e.each(t,function(t){var i=t.positiveValues.concat(t.negativeValues),s=e.min(i),a=e.max(i);this.min=null===this.min?s:Math.min(this.min,s),this.max=null===this.max?a:Math.max(this.max,a)},this)}else e.each(this.chart.data.datasets,function(t,i){var s=this.chart.getDatasetMeta(i);this.chart.isDatasetVisible(i)&&(this.isHorizontal()?s.xAxisID===this.id:s.yAxisID===this.id)&&e.each(t.data,function(t,e){var i=+this.getRightValue(t);isNaN(i)||s.data[e].hidden||(null===this.min?this.min=i:i<this.min&&(this.min=i),null===this.max?this.max=i:i>this.max&&(this.max=i))},this)},this);if(this.options.ticks.beginAtZero){var a=e.sign(this.min),o=e.sign(this.max);0>a&&0>o?this.max=0:a>0&&o>0&&(this.min=0)}void 0!==this.options.ticks.min?this.min=this.options.ticks.min:void 0!==this.options.ticks.suggestedMin&&(this.min=Math.min(this.min,this.options.ticks.suggestedMin)),void 0!==this.options.ticks.max?this.max=this.options.ticks.max:void 0!==this.options.ticks.suggestedMax&&(this.max=Math.max(this.max,this.options.ticks.suggestedMax)),this.min===this.max&&(this.min--,this.max++)},buildTicks:function(){this.ticks=[];var i;if(this.isHorizontal())i=Math.min(this.options.ticks.maxTicksLimit?this.options.ticks.maxTicksLimit:11,Math.ceil(this.width/50));else{var s=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize);i=Math.min(this.options.ticks.maxTicksLimit?this.options.ticks.maxTicksLimit:11,Math.ceil(this.height/(2*s)))}i=Math.max(2,i);var a,o=this.options.ticks.fixedStepSize&&this.options.ticks.fixedStepSize>0||this.options.ticks.stepSize&&this.options.ticks.stepSize>0;if(o)a=e.getValueOrDefault(this.options.ticks.fixedStepSize,this.options.ticks.stepSize);else{var n=e.niceNum(this.max-this.min,!1);a=e.niceNum(n/(i-1),!0)}var r=Math.floor(this.min/a)*a,h=Math.ceil(this.max/a)*a,l=(h-r)/a;l=e.almostEquals(l,Math.round(l),a/1e3)?Math.round(l):Math.ceil(l),this.ticks.push(void 0!==this.options.ticks.min?this.options.ticks.min:r);for(var c=1;l>c;++c)this.ticks.push(r+c*a);this.ticks.push(void 0!==this.options.ticks.max?this.options.ticks.max:h),"left"!==this.options.position&&"right"!==this.options.position||this.ticks.reverse(),this.max=e.max(this.ticks),this.min=e.min(this.ticks),this.options.ticks.reverse?(this.ticks.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max)},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},convertTicksToLabels:function(){this.ticksAsNumbers=this.ticks.slice(),this.zeroLineIndex=this.ticks.indexOf(0),t.Scale.prototype.convertTicksToLabels.call(this)},getPixelForValue:function(t,e,i,s){var a,o=+this.getRightValue(t),n=this.end-this.start;if(this.isHorizontal()){var r=this.width-(this.paddingLeft+this.paddingRight);return a=this.left+r/n*(o-this.start),Math.round(a+this.paddingLeft)}var h=this.height-(this.paddingTop+this.paddingBottom);return a=this.bottom-this.paddingBottom-h/n*(o-this.start),Math.round(a)},getValueForPixel:function(t){var e;if(this.isHorizontal()){var i=this.width-(this.paddingLeft+this.paddingRight);e=(t-this.left-this.paddingLeft)/i}else{var s=this.height-(this.paddingTop+this.paddingBottom);e=(this.bottom-this.paddingBottom-t)/s}return this.start+(this.end-this.start)*e},getPixelForTick:function(t,e){return this.getPixelForValue(this.ticksAsNumbers[t],null,null,e)}});t.scaleService.registerScaleType("linear",s,i)}},{}],34:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers,i={position:"left",ticks:{callback:function(e,i,s){var a=e/Math.pow(10,Math.floor(t.helpers.log10(e)));return 1===a||2===a||5===a||0===i||i===s.length-1?e.toExponential():""}}},s=t.Scale.extend({determineDataLimits:function(){if(this.min=null,this.max=null,this.options.stacked){var t={};e.each(this.chart.data.datasets,function(i,s){var a=this.chart.getDatasetMeta(s);this.chart.isDatasetVisible(s)&&(this.isHorizontal()?a.xAxisID===this.id:a.yAxisID===this.id)&&(void 0===t[a.type]&&(t[a.type]=[]),e.each(i.data,function(e,i){var s=t[a.type],o=+this.getRightValue(e);isNaN(o)||a.data[i].hidden||(s[i]=s[i]||0,this.options.relativePoints?s[i]=100:s[i]+=o)},this))},this),e.each(t,function(t){var i=e.min(t),s=e.max(t);this.min=null===this.min?i:Math.min(this.min,i),this.max=null===this.max?s:Math.max(this.max,s)},this)}else e.each(this.chart.data.datasets,function(t,i){var s=this.chart.getDatasetMeta(i);this.chart.isDatasetVisible(i)&&(this.isHorizontal()?s.xAxisID===this.id:s.yAxisID===this.id)&&e.each(t.data,function(t,e){var i=+this.getRightValue(t);isNaN(i)||s.data[e].hidden||(null===this.min?this.min=i:i<this.min&&(this.min=i),null===this.max?this.max=i:i>this.max&&(this.max=i))},this)},this);this.min=void 0!==this.options.ticks.min?this.options.ticks.min:this.min,this.max=void 0!==this.options.ticks.max?this.options.ticks.max:this.max,this.min===this.max&&(0!==this.min&&null!==this.min?(this.min=Math.pow(10,Math.floor(e.log10(this.min))-1),this.max=Math.pow(10,Math.floor(e.log10(this.max))+1)):(this.min=1,this.max=10))},buildTicks:function(){this.ticks=[];for(var t=void 0!==this.options.ticks.min?this.options.ticks.min:Math.pow(10,Math.floor(e.log10(this.min)));t<this.max;){this.ticks.push(t);var i=Math.floor(e.log10(t)),s=Math.floor(t/Math.pow(10,i))+1;10===s&&(s=1,++i),t=s*Math.pow(10,i)}var a=void 0!==this.options.ticks.max?this.options.ticks.max:t;this.ticks.push(a),"left"!==this.options.position&&"right"!==this.options.position||this.ticks.reverse(), this.max=e.max(this.ticks),this.min=e.min(this.ticks),this.options.ticks.reverse?(this.ticks.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max)},convertTicksToLabels:function(){this.tickValues=this.ticks.slice(),t.Scale.prototype.convertTicksToLabels.call(this)},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},getPixelForTick:function(t,e){return this.getPixelForValue(this.tickValues[t],null,null,e)},getPixelForValue:function(t,i,s,a){var o,n=+this.getRightValue(t),r=e.log10(this.end)-e.log10(this.start);if(this.isHorizontal())if(0===n)o=this.left+this.paddingLeft;else{var h=this.width-(this.paddingLeft+this.paddingRight);o=this.left+h/r*(e.log10(n)-e.log10(this.start)),o+=this.paddingLeft}else if(0===n)o=this.top+this.paddingTop;else{var l=this.height-(this.paddingTop+this.paddingBottom);o=this.bottom-this.paddingBottom-l/r*(e.log10(n)-e.log10(this.start))}return o},getValueForPixel:function(t){var i,s=e.log10(this.end)-e.log10(this.start);if(this.isHorizontal()){var a=this.width-(this.paddingLeft+this.paddingRight);i=this.start*Math.pow(10,(t-this.left-this.paddingLeft)*s/a)}else{var o=this.height-(this.paddingTop+this.paddingBottom);i=Math.pow(10,(this.bottom-this.paddingBottom-t)*s/o)/this.start}return i}});t.scaleService.registerScaleType("logarithmic",s,i)}},{}],35:[function(t,e,i){"use strict";e.exports=function(t){var e=t.helpers,i={display:!0,animate:!0,lineArc:!1,position:"chartArea",angleLines:{display:!0,color:"rgba(0, 0, 0, 0.1)",lineWidth:1},ticks:{showLabelBackdrop:!0,backdropColor:"rgba(255,255,255,0.75)",backdropPaddingY:2,backdropPaddingX:2},pointLabels:{fontSize:10,callback:function(t){return t}}},s=t.Scale.extend({getValueCount:function(){return this.chart.data.labels.length},setDimensions:function(){this.width=this.maxWidth,this.height=this.maxHeight,this.xCenter=Math.round(this.width/2),this.yCenter=Math.round(this.height/2);var i=e.min([this.height,this.width]),s=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize);this.drawingArea=this.options.display?i/2-(s/2+this.options.ticks.backdropPaddingY):i/2},determineDataLimits:function(){if(this.min=null,this.max=null,e.each(this.chart.data.datasets,function(t,i){if(this.chart.isDatasetVisible(i)){var s=this.chart.getDatasetMeta(i);e.each(t.data,function(t,e){var i=+this.getRightValue(t);isNaN(i)||s.data[e].hidden||(null===this.min?this.min=i:i<this.min&&(this.min=i),null===this.max?this.max=i:i>this.max&&(this.max=i))},this)}},this),this.options.ticks.beginAtZero){var t=e.sign(this.min),i=e.sign(this.max);0>t&&0>i?this.max=0:t>0&&i>0&&(this.min=0)}void 0!==this.options.ticks.min?this.min=this.options.ticks.min:void 0!==this.options.ticks.suggestedMin&&(this.min=Math.min(this.min,this.options.ticks.suggestedMin)),void 0!==this.options.ticks.max?this.max=this.options.ticks.max:void 0!==this.options.ticks.suggestedMax&&(this.max=Math.max(this.max,this.options.ticks.suggestedMax)),this.min===this.max&&(this.min--,this.max++)},buildTicks:function(){this.ticks=[];var i=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize),s=Math.min(this.options.ticks.maxTicksLimit?this.options.ticks.maxTicksLimit:11,Math.ceil(this.drawingArea/(1.5*i)));s=Math.max(2,s);var a=e.niceNum(this.max-this.min,!1),o=e.niceNum(a/(s-1),!0),n=Math.floor(this.min/o)*o,r=Math.ceil(this.max/o)*o,h=Math.ceil((r-n)/o);this.ticks.push(void 0!==this.options.ticks.min?this.options.ticks.min:n);for(var l=1;h>l;++l)this.ticks.push(n+l*o);this.ticks.push(void 0!==this.options.ticks.max?this.options.ticks.max:r),this.max=e.max(this.ticks),this.min=e.min(this.ticks),this.options.ticks.reverse?(this.ticks.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),this.zeroLineIndex=this.ticks.indexOf(0)},convertTicksToLabels:function(){t.Scale.prototype.convertTicksToLabels.call(this),this.pointLabels=this.chart.data.labels.map(this.options.pointLabels.callback,this)},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},fit:function(){var i,s,a,o,n,r,h,l,c,d,u,f,g=e.getValueOrDefault(this.options.pointLabels.fontSize,t.defaults.global.defaultFontSize),m=e.getValueOrDefault(this.options.pointLabels.fontStyle,t.defaults.global.defaultFontStyle),p=e.getValueOrDefault(this.options.pointLabels.fontFamily,t.defaults.global.defaultFontFamily),b=e.fontString(g,m,p),v=e.min([this.height/2-g-5,this.width/2]),x=this.width,y=0;for(this.ctx.font=b,s=0;s<this.getValueCount();s++)i=this.getPointPosition(s,v),a=this.ctx.measureText(this.pointLabels[s]?this.pointLabels[s]:"").width+5,0===s||s===this.getValueCount()/2?(o=a/2,i.x+o>x&&(x=i.x+o,n=s),i.x-o<y&&(y=i.x-o,h=s)):s<this.getValueCount()/2?i.x+a>x&&(x=i.x+a,n=s):s>this.getValueCount()/2&&i.x-a<y&&(y=i.x-a,h=s);c=y,d=Math.ceil(x-this.width),r=this.getIndexAngle(n),l=this.getIndexAngle(h),u=d/Math.sin(r+Math.PI/2),f=c/Math.sin(l+Math.PI/2),u=e.isNumber(u)?u:0,f=e.isNumber(f)?f:0,this.drawingArea=Math.round(v-(f+u)/2),this.setCenterPoint(f,u)},setCenterPoint:function(t,e){var i=this.width-e-this.drawingArea,s=t+this.drawingArea;this.xCenter=Math.round((s+i)/2+this.left),this.yCenter=Math.round(this.height/2+this.top)},getIndexAngle:function(t){var e=2*Math.PI/this.getValueCount();return t*e-Math.PI/2},getDistanceFromCenterForValue:function(t){if(null===t)return 0;var e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e},getPointPosition:function(t,e){var i=this.getIndexAngle(t);return{x:Math.round(Math.cos(i)*e)+this.xCenter,y:Math.round(Math.sin(i)*e)+this.yCenter}},getPointPositionForValue:function(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))},draw:function(){if(this.options.display){var i=this.ctx;if(e.each(this.ticks,function(s,a){if(a>0||this.options.reverse){var o=this.getDistanceFromCenterForValue(this.ticks[a]),n=this.yCenter-o;if(this.options.gridLines.display)if(i.strokeStyle=this.options.gridLines.color,i.lineWidth=this.options.gridLines.lineWidth,this.options.lineArc)i.beginPath(),i.arc(this.xCenter,this.yCenter,o,0,2*Math.PI),i.closePath(),i.stroke();else{i.beginPath();for(var r=0;r<this.getValueCount();r++){var h=this.getPointPosition(r,this.getDistanceFromCenterForValue(this.ticks[a]));0===r?i.moveTo(h.x,h.y):i.lineTo(h.x,h.y)}i.closePath(),i.stroke()}if(this.options.ticks.display){var l=e.getValueOrDefault(this.options.ticks.fontColor,t.defaults.global.defaultFontColor),c=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize),d=e.getValueOrDefault(this.options.ticks.fontStyle,t.defaults.global.defaultFontStyle),u=e.getValueOrDefault(this.options.ticks.fontFamily,t.defaults.global.defaultFontFamily),f=e.fontString(c,d,u);if(i.font=f,this.options.ticks.showLabelBackdrop){var g=i.measureText(s).width;i.fillStyle=this.options.ticks.backdropColor,i.fillRect(this.xCenter-g/2-this.options.ticks.backdropPaddingX,n-c/2-this.options.ticks.backdropPaddingY,g+2*this.options.ticks.backdropPaddingX,c+2*this.options.ticks.backdropPaddingY)}i.textAlign="center",i.textBaseline="middle",i.fillStyle=l,i.fillText(s,this.xCenter,n)}}},this),!this.options.lineArc){i.lineWidth=this.options.angleLines.lineWidth,i.strokeStyle=this.options.angleLines.color;for(var s=this.getValueCount()-1;s>=0;s--){if(this.options.angleLines.display){var a=this.getPointPosition(s,this.getDistanceFromCenterForValue(this.options.reverse?this.min:this.max));i.beginPath(),i.moveTo(this.xCenter,this.yCenter),i.lineTo(a.x,a.y),i.stroke(),i.closePath()}var o=this.getPointPosition(s,this.getDistanceFromCenterForValue(this.options.reverse?this.min:this.max)+5),n=e.getValueOrDefault(this.options.pointLabels.fontColor,t.defaults.global.defaultFontColor),r=e.getValueOrDefault(this.options.pointLabels.fontSize,t.defaults.global.defaultFontSize),h=e.getValueOrDefault(this.options.pointLabels.fontStyle,t.defaults.global.defaultFontStyle),l=e.getValueOrDefault(this.options.pointLabels.fontFamily,t.defaults.global.defaultFontFamily),c=e.fontString(r,h,l);i.font=c,i.fillStyle=n;var d=this.pointLabels.length,u=this.pointLabels.length/2,f=u/2,g=f>s||s>d-f,m=s===f||s===d-f;0===s?i.textAlign="center":s===u?i.textAlign="center":u>s?i.textAlign="left":i.textAlign="right",m?i.textBaseline="middle":g?i.textBaseline="bottom":i.textBaseline="top",i.fillText(this.pointLabels[s]?this.pointLabels[s]:"",o.x,o.y)}}}}});t.scaleService.registerScaleType("radialLinear",s,i)}},{}],36:[function(t,e,i){"use strict";var s=t("moment");s="function"==typeof s?s:window.moment,e.exports=function(t){var e=t.helpers,i={units:[{name:"millisecond",steps:[1,2,5,10,20,50,100,250,500]},{name:"second",steps:[1,2,5,10,30]},{name:"minute",steps:[1,2,5,10,30]},{name:"hour",steps:[1,2,3,6,12]},{name:"day",steps:[1,2,5]},{name:"week",maxStep:4},{name:"month",maxStep:3},{name:"quarter",maxStep:4},{name:"year",maxStep:!1}]},a={position:"bottom",time:{parser:!1,format:!1,unit:!1,round:!1,displayFormat:!1,displayFormats:{millisecond:"h:mm:ss.SSS a",second:"h:mm:ss a",minute:"h:mm:ss a",hour:"MMM D, hA",day:"ll",week:"ll",month:"MMM YYYY",quarter:"[Q]Q - YYYY",year:"YYYY"}},ticks:{autoSkip:!1}},o=t.Scale.extend({initialize:function(){if(!s)throw new Error("Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com");t.Scale.prototype.initialize.call(this)},getLabelMoment:function(t,e){return this.labelMoments[t][e]},determineDataLimits:function(){this.labelMoments=[];var t=[];this.chart.data.labels&&this.chart.data.labels.length>0?(e.each(this.chart.data.labels,function(e,i){var s=this.parseTime(e);s.isValid()&&(this.options.time.round&&s.startOf(this.options.time.round),t.push(s))},this),this.firstTick=s.min.call(this,t),this.lastTick=s.max.call(this,t)):(this.firstTick=null,this.lastTick=null),e.each(this.chart.data.datasets,function(i,a){var o=[],n=this.chart.isDatasetVisible(a);"object"==typeof i.data[0]?e.each(i.data,function(t,e){var i=this.parseTime(this.getRightValue(t));i.isValid()&&(this.options.time.round&&i.startOf(this.options.time.round),o.push(i),n&&(this.firstTick=null!==this.firstTick?s.min(this.firstTick,i):i,this.lastTick=null!==this.lastTick?s.max(this.lastTick,i):i))},this):o=t,this.labelMoments.push(o)},this),this.options.time.min&&(this.firstTick=this.parseTime(this.options.time.min)),this.options.time.max&&(this.lastTick=this.parseTime(this.options.time.max)),this.firstTick=(this.firstTick||s()).clone(),this.lastTick=(this.lastTick||s()).clone()},buildTicks:function(s){this.ctx.save();var a=e.getValueOrDefault(this.options.ticks.fontSize,t.defaults.global.defaultFontSize),o=e.getValueOrDefault(this.options.ticks.fontStyle,t.defaults.global.defaultFontStyle),n=e.getValueOrDefault(this.options.ticks.fontFamily,t.defaults.global.defaultFontFamily),r=e.fontString(a,o,n);if(this.ctx.font=r,this.ticks=[],this.unitScale=1,this.scaleSizeInUnits=0,this.options.time.unit)this.tickUnit=this.options.time.unit||"day",this.displayFormat=this.options.time.displayFormats[this.tickUnit],this.scaleSizeInUnits=this.lastTick.diff(this.firstTick,this.tickUnit,!0),this.unitScale=e.getValueOrDefault(this.options.time.unitStepSize,1);else{var h=this.isHorizontal()?this.width-(this.paddingLeft+this.paddingRight):this.height-(this.paddingTop+this.paddingBottom),l=this.tickFormatFunction(this.firstTick,0,[]),c=this.ctx.measureText(l).width,d=Math.cos(e.toRadians(this.options.ticks.maxRotation)),u=Math.sin(e.toRadians(this.options.ticks.maxRotation));c=c*d+a*u;var f=h/c;this.tickUnit="millisecond",this.scaleSizeInUnits=this.lastTick.diff(this.firstTick,this.tickUnit,!0),this.displayFormat=this.options.time.displayFormats[this.tickUnit];for(var g=0,m=i.units[g];g<i.units.length;){if(this.unitScale=1,e.isArray(m.steps)&&Math.ceil(this.scaleSizeInUnits/f)<e.max(m.steps)){for(var p=0;p<m.steps.length;++p)if(m.steps[p]>=Math.ceil(this.scaleSizeInUnits/f)){this.unitScale=e.getValueOrDefault(this.options.time.unitStepSize,m.steps[p]);break}break}if(m.maxStep===!1||Math.ceil(this.scaleSizeInUnits/f)<m.maxStep){this.unitScale=e.getValueOrDefault(this.options.time.unitStepSize,Math.ceil(this.scaleSizeInUnits/f));break}++g,m=i.units[g],this.tickUnit=m.name;var b=this.firstTick.diff(this.firstTick.clone().startOf(this.tickUnit),this.tickUnit,!0),v=this.lastTick.clone().add(1,this.tickUnit).startOf(this.tickUnit).diff(this.lastTick,this.tickUnit,!0);this.scaleSizeInUnits=this.lastTick.diff(this.firstTick,this.tickUnit,!0)+b+v,this.displayFormat=this.options.time.displayFormats[m.name]}}var x;if(this.options.time.min?x=this.firstTick.clone().startOf(this.tickUnit):(this.firstTick.startOf(this.tickUnit),x=this.firstTick),!this.options.time.max){var y=this.lastTick.clone().startOf(this.tickUnit);0!==y.diff(this.lastTick,this.tickUnit,!0)&&this.lastTick.add(1,this.tickUnit).startOf(this.tickUnit)}this.smallestLabelSeparation=this.width,e.each(this.chart.data.datasets,function(t,e){for(var i=1;i<this.labelMoments[e].length;i++)this.smallestLabelSeparation=Math.min(this.smallestLabelSeparation,this.labelMoments[e][i].diff(this.labelMoments[e][i-1],this.tickUnit,!0))},this),this.options.time.displayFormat&&(this.displayFormat=this.options.time.displayFormat),this.ticks.push(this.firstTick.clone());for(var k=1;k<=this.scaleSizeInUnits;++k){var _=x.clone().add(k,this.tickUnit);if(this.options.time.max&&_.diff(this.lastTick,this.tickUnit,!0)>=0)break;k%this.unitScale===0&&this.ticks.push(_)}var S=this.ticks[this.ticks.length-1].diff(this.lastTick,this.tickUnit);0===S&&0!==this.scaleSizeInUnits||(this.options.time.max?(this.ticks.push(this.lastTick.clone()),this.scaleSizeInUnits=this.lastTick.diff(this.ticks[0],this.tickUnit,!0)):(this.ticks.push(this.lastTick.clone()),this.scaleSizeInUnits=this.lastTick.diff(this.firstTick,this.tickUnit,!0))),this.ctx.restore()},getLabelForIndex:function(t,e){var i=this.chart.data.labels&&t<this.chart.data.labels.length?this.chart.data.labels[t]:"";return"object"==typeof this.chart.data.datasets[e].data[0]&&(i=this.getRightValue(this.chart.data.datasets[e].data[t])),this.options.time.tooltipFormat&&(i=this.parseTime(i).format(this.options.time.tooltipFormat)),i},tickFormatFunction:function(t,e,i){var s=t.format(this.displayFormat);return this.options.ticks.userCallback?this.options.ticks.userCallback(s,e,i):s},convertTicksToLabels:function(){this.ticks=this.ticks.map(this.tickFormatFunction,this)},getPixelForValue:function(t,e,i,s){var a=t&&t.isValid&&t.isValid()?t:this.getLabelMoment(i,e);if(a){var o=a.diff(this.firstTick,this.tickUnit,!0),n=o/this.scaleSizeInUnits;if(this.isHorizontal()){var r=this.width-(this.paddingLeft+this.paddingRight),h=(r/Math.max(this.ticks.length-1,1),r*n+this.paddingLeft);return this.left+Math.round(h)}var l=this.height-(this.paddingTop+this.paddingBottom),c=(l/Math.max(this.ticks.length-1,1),l*n+this.paddingTop);return this.top+Math.round(c)}},getValueForPixel:function(t){var e=this.isHorizontal()?this.width-(this.paddingLeft+this.paddingRight):this.height-(this.paddingTop+this.paddingBottom),i=(t-(this.isHorizontal()?this.left+this.paddingLeft:this.top+this.paddingTop))/e;return i*=this.scaleSizeInUnits,this.firstTick.clone().add(s.duration(i,this.tickUnit).asSeconds(),"seconds")},parseTime:function(t){return"string"==typeof this.options.time.parser?s(t,this.options.time.parser):"function"==typeof this.options.time.parser?this.options.time.parser(t):"function"==typeof t.getMonth||"number"==typeof t?s(t):t.isValid&&t.isValid()?t:"string"!=typeof this.options.time.format&&this.options.time.format.call?(console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale"),this.options.time.format(t)):s(t,this.options.time.format)}});t.scaleService.registerScaleType("time",o,a)}},{moment:42}],37:[function(t,e,i){function s(t){if(t){var e=/^#([a-fA-F0-9]{3})$/,i=/^#([a-fA-F0-9]{6})$/,s=/^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,a=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/,o=/(\w+)/,n=[0,0,0],r=1,h=t.match(e);if(h){h=h[1];for(var l=0;l<n.length;l++)n[l]=parseInt(h[l]+h[l],16)}else if(h=t.match(i)){h=h[1];for(var l=0;l<n.length;l++)n[l]=parseInt(h.slice(2*l,2*l+2),16)}else if(h=t.match(s)){for(var l=0;l<n.length;l++)n[l]=parseInt(h[l+1]);r=parseFloat(h[4])}else if(h=t.match(a)){for(var l=0;l<n.length;l++)n[l]=Math.round(2.55*parseFloat(h[l+1]));r=parseFloat(h[4])}else if(h=t.match(o)){if("transparent"==h[1])return[0,0,0,0];if(n=y[h[1]],!n)return}for(var l=0;l<n.length;l++)n[l]=v(n[l],0,255);return r=r||0==r?v(r,0,1):1,n[3]=r,n}}function a(t){if(t){var e=/^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/,i=t.match(e);if(i){var s=parseFloat(i[4]),a=v(parseInt(i[1]),0,360),o=v(parseFloat(i[2]),0,100),n=v(parseFloat(i[3]),0,100),r=v(isNaN(s)?1:s,0,1);return[a,o,n,r]}}}function o(t){if(t){var e=/^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/,i=t.match(e);if(i){var s=parseFloat(i[4]),a=v(parseInt(i[1]),0,360),o=v(parseFloat(i[2]),0,100),n=v(parseFloat(i[3]),0,100),r=v(isNaN(s)?1:s,0,1);return[a,o,n,r]}}}function n(t){var e=s(t);return e&&e.slice(0,3)}function r(t){var e=a(t);return e&&e.slice(0,3)}function h(t){var e=s(t);return e?e[3]:(e=a(t))?e[3]:(e=o(t))?e[3]:void 0}function l(t){return"#"+x(t[0])+x(t[1])+x(t[2])}function c(t,e){return 1>e||t[3]&&t[3]<1?d(t,e):"rgb("+t[0]+", "+t[1]+", "+t[2]+")"}function d(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"rgba("+t[0]+", "+t[1]+", "+t[2]+", "+e+")"}function u(t,e){if(1>e||t[3]&&t[3]<1)return f(t,e);var i=Math.round(t[0]/255*100),s=Math.round(t[1]/255*100),a=Math.round(t[2]/255*100);return"rgb("+i+"%, "+s+"%, "+a+"%)"}function f(t,e){var i=Math.round(t[0]/255*100),s=Math.round(t[1]/255*100),a=Math.round(t[2]/255*100);return"rgba("+i+"%, "+s+"%, "+a+"%, "+(e||t[3]||1)+")"}function g(t,e){return 1>e||t[3]&&t[3]<1?m(t,e):"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)"}function m(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+e+")"}function p(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+(void 0!==e&&1!==e?", "+e:"")+")"}function b(t){return k[t.slice(0,3)]}function v(t,e,i){return Math.min(Math.max(e,t),i)}function x(t){var e=t.toString(16).toUpperCase();return e.length<2?"0"+e:e}var y=t("color-name");e.exports={getRgba:s,getHsla:a,getRgb:n,getHsl:r,getHwb:o,getAlpha:h,hexString:l,rgbString:c,rgbaString:d,percentString:u,percentaString:f,hslString:g,hslaString:m,hwbString:p,keyword:b};var k={};for(var _ in y)k[y[_]]=_},{"color-name":41}],38:[function(t,e,i){var s=t("color-convert"),a=t("chartjs-color-string"),o=function(t){if(t instanceof o)return t;if(!(this instanceof o))return new o(t);if(this.values={rgb:[0,0,0],hsl:[0,0,0],hsv:[0,0,0],hwb:[0,0,0],cmyk:[0,0,0,0],alpha:1},"string"==typeof t){var e=a.getRgba(t);if(e)this.setValues("rgb",e);else if(e=a.getHsla(t))this.setValues("hsl",e);else{if(!(e=a.getHwb(t)))throw new Error('Unable to parse color from string "'+t+'"');this.setValues("hwb",e)}}else if("object"==typeof t){var e=t;if(void 0!==e.r||void 0!==e.red)this.setValues("rgb",e);else if(void 0!==e.l||void 0!==e.lightness)this.setValues("hsl",e);else if(void 0!==e.v||void 0!==e.value)this.setValues("hsv",e);else if(void 0!==e.w||void 0!==e.whiteness)this.setValues("hwb",e);else{if(void 0===e.c&&void 0===e.cyan)throw new Error("Unable to parse color from object "+JSON.stringify(t));this.setValues("cmyk",e)}}};o.prototype={rgb:function(t){return this.setSpace("rgb",arguments)},hsl:function(t){return this.setSpace("hsl",arguments)},hsv:function(t){return this.setSpace("hsv",arguments)},hwb:function(t){return this.setSpace("hwb",arguments)},cmyk:function(t){return this.setSpace("cmyk",arguments)},rgbArray:function(){return this.values.rgb},hslArray:function(){return this.values.hsl},hsvArray:function(){return this.values.hsv},hwbArray:function(){return 1!==this.values.alpha?this.values.hwb.concat([this.values.alpha]):this.values.hwb},cmykArray:function(){return this.values.cmyk},rgbaArray:function(){var t=this.values.rgb;return t.concat([this.values.alpha])},hslaArray:function(){var t=this.values.hsl;return t.concat([this.values.alpha])},alpha:function(t){return void 0===t?this.values.alpha:(this.setValues("alpha",t),this)},red:function(t){return this.setChannel("rgb",0,t)},green:function(t){return this.setChannel("rgb",1,t)},blue:function(t){return this.setChannel("rgb",2,t)},hue:function(t){return this.setChannel("hsl",0,t)},saturation:function(t){return this.setChannel("hsl",1,t)},lightness:function(t){return this.setChannel("hsl",2,t)},saturationv:function(t){return this.setChannel("hsv",1,t)},whiteness:function(t){return this.setChannel("hwb",1,t)},blackness:function(t){return this.setChannel("hwb",2,t)},value:function(t){return this.setChannel("hsv",2,t)},cyan:function(t){return this.setChannel("cmyk",0,t)},magenta:function(t){return this.setChannel("cmyk",1,t)},yellow:function(t){return this.setChannel("cmyk",2,t)},black:function(t){return this.setChannel("cmyk",3,t)},hexString:function(){return a.hexString(this.values.rgb)},rgbString:function(){return a.rgbString(this.values.rgb,this.values.alpha)},rgbaString:function(){return a.rgbaString(this.values.rgb,this.values.alpha)},percentString:function(){return a.percentString(this.values.rgb,this.values.alpha)},hslString:function(){return a.hslString(this.values.hsl,this.values.alpha)},hslaString:function(){return a.hslaString(this.values.hsl,this.values.alpha)},hwbString:function(){return a.hwbString(this.values.hwb,this.values.alpha)},keyword:function(){return a.keyword(this.values.rgb,this.values.alpha)},rgbNumber:function(){return this.values.rgb[0]<<16|this.values.rgb[1]<<8|this.values.rgb[2]},luminosity:function(){for(var t=this.values.rgb,e=[],i=0;i<t.length;i++){var s=t[i]/255;e[i]=.03928>=s?s/12.92:Math.pow((s+.055)/1.055,2.4)}return.2126*e[0]+.7152*e[1]+.0722*e[2]},contrast:function(t){var e=this.luminosity(),i=t.luminosity();return e>i?(e+.05)/(i+.05):(i+.05)/(e+.05)},level:function(t){var e=this.contrast(t);return e>=7.1?"AAA":e>=4.5?"AA":""},dark:function(){var t=this.values.rgb,e=(299*t[0]+587*t[1]+114*t[2])/1e3;return 128>e},light:function(){return!this.dark()},negate:function(){for(var t=[],e=0;3>e;e++)t[e]=255-this.values.rgb[e];return this.setValues("rgb",t),this},lighten:function(t){return this.values.hsl[2]+=this.values.hsl[2]*t,this.setValues("hsl",this.values.hsl),this},darken:function(t){return this.values.hsl[2]-=this.values.hsl[2]*t,this.setValues("hsl",this.values.hsl),this},saturate:function(t){return this.values.hsl[1]+=this.values.hsl[1]*t,this.setValues("hsl",this.values.hsl),this},desaturate:function(t){return this.values.hsl[1]-=this.values.hsl[1]*t,this.setValues("hsl",this.values.hsl),this},whiten:function(t){return this.values.hwb[1]+=this.values.hwb[1]*t,this.setValues("hwb",this.values.hwb),this},blacken:function(t){return this.values.hwb[2]+=this.values.hwb[2]*t,this.setValues("hwb",this.values.hwb),this},greyscale:function(){var t=this.values.rgb,e=.3*t[0]+.59*t[1]+.11*t[2];return this.setValues("rgb",[e,e,e]),this},clearer:function(t){return this.setValues("alpha",this.values.alpha-this.values.alpha*t),this},opaquer:function(t){return this.setValues("alpha",this.values.alpha+this.values.alpha*t),this},rotate:function(t){var e=this.values.hsl[0];return e=(e+t)%360,e=0>e?360+e:e,this.values.hsl[0]=e,this.setValues("hsl",this.values.hsl),this},mix:function(t,e){e=1-(null==e?.5:e);for(var i=2*e-1,s=this.alpha()-t.alpha(),a=((i*s==-1?i:(i+s)/(1+i*s))+1)/2,o=1-a,n=this.rgbArray(),r=t.rgbArray(),h=0;h<n.length;h++)n[h]=n[h]*a+r[h]*o;this.setValues("rgb",n);var l=this.alpha()*e+t.alpha()*(1-e);return this.setValues("alpha",l),this},toJSON:function(){return this.rgb()},clone:function(){return new o(this.rgb())}},o.prototype.getValues=function(t){for(var e={},i=0;i<t.length;i++)e[t.charAt(i)]=this.values[t][i];return 1!=this.values.alpha&&(e.a=this.values.alpha),e},o.prototype.setValues=function(t,e){var i={rgb:["red","green","blue"],hsl:["hue","saturation","lightness"],hsv:["hue","saturation","value"],hwb:["hue","whiteness","blackness"],cmyk:["cyan","magenta","yellow","black"]},a={rgb:[255,255,255],hsl:[360,100,100],hsv:[360,100,100],hwb:[360,100,100],cmyk:[100,100,100,100]},o=1;if("alpha"==t)o=e;else if(e.length)this.values[t]=e.slice(0,t.length),o=e[t.length];else if(void 0!==e[t.charAt(0)]){for(var n=0;n<t.length;n++)this.values[t][n]=e[t.charAt(n)];o=e.a}else if(void 0!==e[i[t][0]]){for(var r=i[t],n=0;n<t.length;n++)this.values[t][n]=e[r[n]];o=e.alpha}if(this.values.alpha=Math.max(0,Math.min(1,void 0!==o?o:this.values.alpha)),"alpha"!=t){for(var n=0;n<t.length;n++){var h=Math.max(0,Math.min(a[t][n],this.values[t][n]));this.values[t][n]=Math.round(h)}for(var l in i){l!=t&&(this.values[l]=s[t][l](this.values[t]));for(var n=0;n<l.length;n++){var h=Math.max(0,Math.min(a[l][n],this.values[l][n]));this.values[l][n]=Math.round(h)}}return!0}},o.prototype.setSpace=function(t,e){var i=e[0];return void 0===i?this.getValues(t):("number"==typeof i&&(i=Array.prototype.slice.call(e)),this.setValues(t,i),this)},o.prototype.setChannel=function(t,e,i){return void 0===i?this.values[t][e]:(this.values[t][e]=i,this.setValues(t,this.values[t]),this)},window.Color=e.exports=o},{"chartjs-color-string":37,"color-convert":40}],39:[function(t,e,i){function s(t){var e,i,s,a=t[0]/255,o=t[1]/255,n=t[2]/255,r=Math.min(a,o,n),h=Math.max(a,o,n),l=h-r;return h==r?e=0:a==h?e=(o-n)/l:o==h?e=2+(n-a)/l:n==h&&(e=4+(a-o)/l),e=Math.min(60*e,360),0>e&&(e+=360),s=(r+h)/2,i=h==r?0:.5>=s?l/(h+r):l/(2-h-r),[e,100*i,100*s]}function a(t){var e,i,s,a=t[0],o=t[1],n=t[2],r=Math.min(a,o,n),h=Math.max(a,o,n),l=h-r;return i=0==h?0:l/h*1e3/10,h==r?e=0:a==h?e=(o-n)/l:o==h?e=2+(n-a)/l:n==h&&(e=4+(a-o)/l),e=Math.min(60*e,360),0>e&&(e+=360),s=h/255*1e3/10,[e,i,s]}function o(t){var e=t[0],i=t[1],a=t[2],o=s(t)[0],n=1/255*Math.min(e,Math.min(i,a)),a=1-1/255*Math.max(e,Math.max(i,a));return[o,100*n,100*a]}function n(t){var e,i,s,a,o=t[0]/255,n=t[1]/255,r=t[2]/255;return a=Math.min(1-o,1-n,1-r),e=(1-o-a)/(1-a)||0,i=(1-n-a)/(1-a)||0,s=(1-r-a)/(1-a)||0,[100*e,100*i,100*s,100*a]}function h(t){return X[JSON.stringify(t)]}function l(t){var e=t[0]/255,i=t[1]/255,s=t[2]/255;e=e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92,i=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92,s=s>.04045?Math.pow((s+.055)/1.055,2.4):s/12.92;var a=.4124*e+.3576*i+.1805*s,o=.2126*e+.7152*i+.0722*s,n=.0193*e+.1192*i+.9505*s;return[100*a,100*o,100*n]}function c(t){var e,i,s,a=l(t),o=a[0],n=a[1],r=a[2];return o/=95.047,n/=100,r/=108.883,o=o>.008856?Math.pow(o,1/3):7.787*o+16/116,n=n>.008856?Math.pow(n,1/3):7.787*n+16/116,r=r>.008856?Math.pow(r,1/3):7.787*r+16/116,e=116*n-16,i=500*(o-n),s=200*(n-r),[e,i,s]}function d(t){return z(c(t))}function u(t){var e,i,s,a,o,n=t[0]/360,r=t[1]/100,h=t[2]/100;if(0==r)return o=255*h,[o,o,o];i=.5>h?h*(1+r):h+r-h*r,e=2*h-i,a=[0,0,0];for(var l=0;3>l;l++)s=n+1/3*-(l-1),0>s&&s++,s>1&&s--,o=1>6*s?e+6*(i-e)*s:1>2*s?i:2>3*s?e+(i-e)*(2/3-s)*6:e,a[l]=255*o;return a}function f(t){var e,i,s=t[0],a=t[1]/100,o=t[2]/100;return 0===o?[0,0,0]:(o*=2,a*=1>=o?o:2-o,i=(o+a)/2,e=2*a/(o+a),[s,100*e,100*i])}function m(t){return o(u(t))}function p(t){return n(u(t))}function v(t){return h(u(t))}function x(t){var e=t[0]/60,i=t[1]/100,s=t[2]/100,a=Math.floor(e)%6,o=e-Math.floor(e),n=255*s*(1-i),r=255*s*(1-i*o),h=255*s*(1-i*(1-o)),s=255*s;switch(a){case 0:return[s,h,n];case 1:return[r,s,n];case 2:return[n,s,h];case 3:return[n,r,s];case 4:return[h,n,s];case 5:return[s,n,r]}}function y(t){var e,i,s=t[0],a=t[1]/100,o=t[2]/100;return i=(2-a)*o,e=a*o,e/=1>=i?i:2-i,e=e||0,i/=2,[s,100*e,100*i]}function k(t){return o(x(t))}function _(t){return n(x(t))}function S(t){return h(x(t))}function w(t){var e,i,s,a,o=t[0]/360,n=t[1]/100,h=t[2]/100,l=n+h;switch(l>1&&(n/=l,h/=l),e=Math.floor(6*o),i=1-h,s=6*o-e,0!=(1&e)&&(s=1-s),a=n+s*(i-n),e){default:case 6:case 0:r=i,g=a,b=n;break;case 1:r=a,g=i,b=n;break;case 2:r=n,g=i,b=a;break;case 3:r=n,g=a,b=i;break;case 4:r=a,g=n,b=i;break;case 5:r=i,g=n,b=a}return[255*r,255*g,255*b]}function D(t){return s(w(t))}function M(t){return a(w(t))}function C(t){return n(w(t))}function A(t){return h(w(t))}function I(t){var e,i,s,a=t[0]/100,o=t[1]/100,n=t[2]/100,r=t[3]/100;return e=1-Math.min(1,a*(1-r)+r),i=1-Math.min(1,o*(1-r)+r),s=1-Math.min(1,n*(1-r)+r),[255*e,255*i,255*s]}function P(t){return s(I(t))}function T(t){return a(I(t))}function F(t){return o(I(t))}function O(t){return h(I(t))}function V(t){var e,i,s,a=t[0]/100,o=t[1]/100,n=t[2]/100;return e=3.2406*a+-1.5372*o+n*-.4986,i=a*-.9689+1.8758*o+.0415*n,s=.0557*a+o*-.204+1.057*n,e=e>.0031308?1.055*Math.pow(e,1/2.4)-.055:e=12.92*e,i=i>.0031308?1.055*Math.pow(i,1/2.4)-.055:i=12.92*i,s=s>.0031308?1.055*Math.pow(s,1/2.4)-.055:s=12.92*s,e=Math.min(Math.max(0,e),1),i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),[255*e,255*i,255*s]}function R(t){var e,i,s,a=t[0],o=t[1],n=t[2];return a/=95.047,o/=100,n/=108.883,a=a>.008856?Math.pow(a,1/3):7.787*a+16/116,o=o>.008856?Math.pow(o,1/3):7.787*o+16/116,n=n>.008856?Math.pow(n,1/3):7.787*n+16/116,e=116*o-16,i=500*(a-o),s=200*(o-n),[e,i,s]}function W(t){return z(R(t))}function L(t){var e,i,s,a,o=t[0],n=t[1],r=t[2];return 8>=o?(i=100*o/903.3,a=7.787*(i/100)+16/116):(i=100*Math.pow((o+16)/116,3),a=Math.pow(i/100,1/3)),e=.008856>=e/95.047?e=95.047*(n/500+a-16/116)/7.787:95.047*Math.pow(n/500+a,3),s=.008859>=s/108.883?s=108.883*(a-r/200-16/116)/7.787:108.883*Math.pow(a-r/200,3),[e,i,s]}function z(t){var e,i,s,a=t[0],o=t[1],n=t[2];return e=Math.atan2(n,o),i=360*e/2/Math.PI,0>i&&(i+=360),s=Math.sqrt(o*o+n*n),[a,s,i]}function B(t){return V(L(t))}function Y(t){var e,i,s,a=t[0],o=t[1],n=t[2];return s=n/360*2*Math.PI,e=o*Math.cos(s),i=o*Math.sin(s),[a,e,i]}function H(t){return L(Y(t))}function N(t){return B(Y(t))}function E(t){return J[t]}function U(t){return s(E(t))}function j(t){return a(E(t))}function G(t){return o(E(t))}function q(t){return n(E(t))}function Z(t){return c(E(t))}function Q(t){return l(E(t))}e.exports={rgb2hsl:s,rgb2hsv:a,rgb2hwb:o,rgb2cmyk:n,rgb2keyword:h,rgb2xyz:l,rgb2lab:c,rgb2lch:d,hsl2rgb:u,hsl2hsv:f,hsl2hwb:m,hsl2cmyk:p,hsl2keyword:v,hsv2rgb:x,hsv2hsl:y,hsv2hwb:k,hsv2cmyk:_,hsv2keyword:S,hwb2rgb:w,hwb2hsl:D,hwb2hsv:M,hwb2cmyk:C,hwb2keyword:A,cmyk2rgb:I,cmyk2hsl:P,cmyk2hsv:T,cmyk2hwb:F,cmyk2keyword:O,keyword2rgb:E,keyword2hsl:U,keyword2hsv:j,keyword2hwb:G,keyword2cmyk:q,keyword2lab:Z,keyword2xyz:Q,xyz2rgb:V,xyz2lab:R,xyz2lch:W,lab2xyz:L,lab2rgb:B,lab2lch:z,lch2lab:Y,lch2xyz:H,lch2rgb:N};var J={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255], gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},X={};for(var $ in J)X[JSON.stringify(J[$])]=$},{}],40:[function(t,e,i){var s=t("./conversions"),a=function(){return new l};for(var o in s){a[o+"Raw"]=function(t){return function(e){return"number"==typeof e&&(e=Array.prototype.slice.call(arguments)),s[t](e)}}(o);var n=/(\w+)2(\w+)/.exec(o),r=n[1],h=n[2];a[r]=a[r]||{},a[r][h]=a[o]=function(t){return function(e){"number"==typeof e&&(e=Array.prototype.slice.call(arguments));var i=s[t](e);if("string"==typeof i||void 0===i)return i;for(var a=0;a<i.length;a++)i[a]=Math.round(i[a]);return i}}(o)}var l=function(){this.convs={}};l.prototype.routeSpace=function(t,e){var i=e[0];return void 0===i?this.getValues(t):("number"==typeof i&&(i=Array.prototype.slice.call(e)),this.setValues(t,i))},l.prototype.setValues=function(t,e){return this.space=t,this.convs={},this.convs[t]=e,this},l.prototype.getValues=function(t){var e=this.convs[t];if(!e){var i=this.space,s=this.convs[i];e=a[i][t](s),this.convs[t]=e}return e},["rgb","hsl","hsv","cmyk","keyword"].forEach(function(t){l.prototype[t]=function(e){return this.routeSpace(t,arguments)}}),e.exports=a},{"./conversions":39}],41:[function(t,e,i){e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},{}],42:[function(e,i,s){!function(e,a){"object"==typeof s&&"undefined"!=typeof i?i.exports=a():"function"==typeof t&&t.amd?t(a):e.moment=a()}(this,function(){"use strict";function t(){return rs.apply(null,arguments)}function s(t){rs=t}function a(t){return t instanceof Array||"[object Array]"===Object.prototype.toString.call(t)}function o(t){return t instanceof Date||"[object Date]"===Object.prototype.toString.call(t)}function n(t,e){var i,s=[];for(i=0;i<t.length;++i)s.push(e(t[i],i));return s}function r(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function h(t,e){for(var i in e)r(e,i)&&(t[i]=e[i]);return r(e,"toString")&&(t.toString=e.toString),r(e,"valueOf")&&(t.valueOf=e.valueOf),t}function l(t,e,i,s){return Lt(t,e,i,s,!0).utc()}function c(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null}}function d(t){return null==t._pf&&(t._pf=c()),t._pf}function u(t){if(null==t._isValid){var e=d(t),i=hs.call(e.parsedDateParts,function(t){return null!=t});t._isValid=!isNaN(t._d.getTime())&&e.overflow<0&&!e.empty&&!e.invalidMonth&&!e.invalidWeekday&&!e.nullInput&&!e.invalidFormat&&!e.userInvalidated&&(!e.meridiem||e.meridiem&&i),t._strict&&(t._isValid=t._isValid&&0===e.charsLeftOver&&0===e.unusedTokens.length&&void 0===e.bigHour)}return t._isValid}function f(t){var e=l(NaN);return null!=t?h(d(e),t):d(e).userInvalidated=!0,e}function g(t){return void 0===t}function m(t,e){var i,s,a;if(g(e._isAMomentObject)||(t._isAMomentObject=e._isAMomentObject),g(e._i)||(t._i=e._i),g(e._f)||(t._f=e._f),g(e._l)||(t._l=e._l),g(e._strict)||(t._strict=e._strict),g(e._tzm)||(t._tzm=e._tzm),g(e._isUTC)||(t._isUTC=e._isUTC),g(e._offset)||(t._offset=e._offset),g(e._pf)||(t._pf=d(e)),g(e._locale)||(t._locale=e._locale),ls.length>0)for(i in ls)s=ls[i],a=e[s],g(a)||(t[s]=a);return t}function p(e){m(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),cs===!1&&(cs=!0,t.updateOffset(this),cs=!1)}function b(t){return t instanceof p||null!=t&&null!=t._isAMomentObject}function v(t){return 0>t?Math.ceil(t):Math.floor(t)}function x(t){var e=+t,i=0;return 0!==e&&isFinite(e)&&(i=v(e)),i}function y(t,e,i){var s,a=Math.min(t.length,e.length),o=Math.abs(t.length-e.length),n=0;for(s=0;a>s;s++)(i&&t[s]!==e[s]||!i&&x(t[s])!==x(e[s]))&&n++;return n+o}function k(e){t.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function _(e,i){var s=!0;return h(function(){return null!=t.deprecationHandler&&t.deprecationHandler(null,e),s&&(k(e+"\nArguments: "+Array.prototype.slice.call(arguments).join(", ")+"\n"+(new Error).stack),s=!1),i.apply(this,arguments)},i)}function S(e,i){null!=t.deprecationHandler&&t.deprecationHandler(e,i),ds[e]||(k(i),ds[e]=!0)}function w(t){return t instanceof Function||"[object Function]"===Object.prototype.toString.call(t)}function D(t){return"[object Object]"===Object.prototype.toString.call(t)}function M(t){var e,i;for(i in t)e=t[i],w(e)?this[i]=e:this["_"+i]=e;this._config=t,this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function C(t,e){var i,s=h({},t);for(i in e)r(e,i)&&(D(t[i])&&D(e[i])?(s[i]={},h(s[i],t[i]),h(s[i],e[i])):null!=e[i]?s[i]=e[i]:delete s[i]);return s}function A(t){null!=t&&this.set(t)}function I(t){return t?t.toLowerCase().replace("_","-"):t}function P(t){for(var e,i,s,a,o=0;o<t.length;){for(a=I(t[o]).split("-"),e=a.length,i=I(t[o+1]),i=i?i.split("-"):null;e>0;){if(s=T(a.slice(0,e).join("-")))return s;if(i&&i.length>=e&&y(a,i,!0)>=e-1)break;e--}o++}return null}function T(t){var s=null;if(!ms[t]&&"undefined"!=typeof i&&i&&i.exports)try{s=fs._abbr,e("./locale/"+t),F(s)}catch(a){}return ms[t]}function F(t,e){var i;return t&&(i=g(e)?R(t):O(t,e),i&&(fs=i)),fs._abbr}function O(t,e){return null!==e?(e.abbr=t,null!=ms[t]?(S("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale"),e=C(ms[t]._config,e)):null!=e.parentLocale&&(null!=ms[e.parentLocale]?e=C(ms[e.parentLocale]._config,e):S("parentLocaleUndefined","specified parentLocale is not defined yet")),ms[t]=new A(e),F(t),ms[t]):(delete ms[t],null)}function V(t,e){if(null!=e){var i;null!=ms[t]&&(e=C(ms[t]._config,e)),i=new A(e),i.parentLocale=ms[t],ms[t]=i,F(t)}else null!=ms[t]&&(null!=ms[t].parentLocale?ms[t]=ms[t].parentLocale:null!=ms[t]&&delete ms[t]);return ms[t]}function R(t){var e;if(t&&t._locale&&t._locale._abbr&&(t=t._locale._abbr),!t)return fs;if(!a(t)){if(e=T(t))return e;t=[t]}return P(t)}function W(){return us(ms)}function L(t,e){var i=t.toLowerCase();ps[i]=ps[i+"s"]=ps[e]=t}function z(t){return"string"==typeof t?ps[t]||ps[t.toLowerCase()]:void 0}function B(t){var e,i,s={};for(i in t)r(t,i)&&(e=z(i),e&&(s[e]=t[i]));return s}function Y(e,i){return function(s){return null!=s?(N(this,e,s),t.updateOffset(this,i),this):H(this,e)}}function H(t,e){return t.isValid()?t._d["get"+(t._isUTC?"UTC":"")+e]():NaN}function N(t,e,i){t.isValid()&&t._d["set"+(t._isUTC?"UTC":"")+e](i)}function E(t,e){var i;if("object"==typeof t)for(i in t)this.set(i,t[i]);else if(t=z(t),w(this[t]))return this[t](e);return this}function U(t,e,i){var s=""+Math.abs(t),a=e-s.length,o=t>=0;return(o?i?"+":"":"-")+Math.pow(10,Math.max(0,a)).toString().substr(1)+s}function j(t,e,i,s){var a=s;"string"==typeof s&&(a=function(){return this[s]()}),t&&(ys[t]=a),e&&(ys[e[0]]=function(){return U(a.apply(this,arguments),e[1],e[2])}),i&&(ys[i]=function(){return this.localeData().ordinal(a.apply(this,arguments),t)})}function G(t){return t.match(/\[[\s\S]/)?t.replace(/^\[|\]$/g,""):t.replace(/\\/g,"")}function q(t){var e,i,s=t.match(bs);for(e=0,i=s.length;i>e;e++)ys[s[e]]?s[e]=ys[s[e]]:s[e]=G(s[e]);return function(e){var a,o="";for(a=0;i>a;a++)o+=s[a]instanceof Function?s[a].call(e,t):s[a];return o}}function Z(t,e){return t.isValid()?(e=Q(e,t.localeData()),xs[e]=xs[e]||q(e),xs[e](t)):t.localeData().invalidDate()}function Q(t,e){function i(t){return e.longDateFormat(t)||t}var s=5;for(vs.lastIndex=0;s>=0&&vs.test(t);)t=t.replace(vs,i),vs.lastIndex=0,s-=1;return t}function J(t,e,i){zs[t]=w(e)?e:function(t,s){return t&&i?i:e}}function X(t,e){return r(zs,t)?zs[t](e._strict,e._locale):new RegExp($(t))}function $(t){return K(t.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(t,e,i,s,a){return e||i||s||a}))}function K(t){return t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function tt(t,e){var i,s=e;for("string"==typeof t&&(t=[t]),"number"==typeof e&&(s=function(t,i){i[e]=x(t)}),i=0;i<t.length;i++)Bs[t[i]]=s}function et(t,e){tt(t,function(t,i,s,a){s._w=s._w||{},e(t,s._w,s,a)})}function it(t,e,i){null!=e&&r(Bs,t)&&Bs[t](e,i._a,i,t)}function st(t,e){return new Date(Date.UTC(t,e+1,0)).getUTCDate()}function at(t,e){return a(this._months)?this._months[t.month()]:this._months[Qs.test(e)?"format":"standalone"][t.month()]}function ot(t,e){return a(this._monthsShort)?this._monthsShort[t.month()]:this._monthsShort[Qs.test(e)?"format":"standalone"][t.month()]}function nt(t,e,i){var s,a,o,n=t.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;12>s;++s)o=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(o,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(o,"").toLocaleLowerCase();return i?"MMM"===e?(a=gs.call(this._shortMonthsParse,n),-1!==a?a:null):(a=gs.call(this._longMonthsParse,n),-1!==a?a:null):"MMM"===e?(a=gs.call(this._shortMonthsParse,n),-1!==a?a:(a=gs.call(this._longMonthsParse,n),-1!==a?a:null)):(a=gs.call(this._longMonthsParse,n),-1!==a?a:(a=gs.call(this._shortMonthsParse,n),-1!==a?a:null))}function rt(t,e,i){var s,a,o;if(this._monthsParseExact)return nt.call(this,t,e,i);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;12>s;s++){if(a=l([2e3,s]),i&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(a,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(a,"").replace(".","")+"$","i")),i||this._monthsParse[s]||(o="^"+this.months(a,"")+"|^"+this.monthsShort(a,""),this._monthsParse[s]=new RegExp(o.replace(".",""),"i")),i&&"MMMM"===e&&this._longMonthsParse[s].test(t))return s;if(i&&"MMM"===e&&this._shortMonthsParse[s].test(t))return s;if(!i&&this._monthsParse[s].test(t))return s}}function ht(t,e){var i;if(!t.isValid())return t;if("string"==typeof e)if(/^\d+$/.test(e))e=x(e);else if(e=t.localeData().monthsParse(e),"number"!=typeof e)return t;return i=Math.min(t.date(),st(t.year(),e)),t._d["set"+(t._isUTC?"UTC":"")+"Month"](e,i),t}function lt(e){return null!=e?(ht(this,e),t.updateOffset(this,!0),this):H(this,"Month")}function ct(){return st(this.year(),this.month())}function dt(t){return this._monthsParseExact?(r(this,"_monthsRegex")||ft.call(this),t?this._monthsShortStrictRegex:this._monthsShortRegex):this._monthsShortStrictRegex&&t?this._monthsShortStrictRegex:this._monthsShortRegex}function ut(t){return this._monthsParseExact?(r(this,"_monthsRegex")||ft.call(this),t?this._monthsStrictRegex:this._monthsRegex):this._monthsStrictRegex&&t?this._monthsStrictRegex:this._monthsRegex}function ft(){function t(t,e){return e.length-t.length}var e,i,s=[],a=[],o=[];for(e=0;12>e;e++)i=l([2e3,e]),s.push(this.monthsShort(i,"")),a.push(this.months(i,"")),o.push(this.months(i,"")),o.push(this.monthsShort(i,""));for(s.sort(t),a.sort(t),o.sort(t),e=0;12>e;e++)s[e]=K(s[e]),a[e]=K(a[e]),o[e]=K(o[e]);this._monthsRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function gt(t){var e,i=t._a;return i&&-2===d(t).overflow&&(e=i[Hs]<0||i[Hs]>11?Hs:i[Ns]<1||i[Ns]>st(i[Ys],i[Hs])?Ns:i[Es]<0||i[Es]>24||24===i[Es]&&(0!==i[Us]||0!==i[js]||0!==i[Gs])?Es:i[Us]<0||i[Us]>59?Us:i[js]<0||i[js]>59?js:i[Gs]<0||i[Gs]>999?Gs:-1,d(t)._overflowDayOfYear&&(Ys>e||e>Ns)&&(e=Ns),d(t)._overflowWeeks&&-1===e&&(e=qs),d(t)._overflowWeekday&&-1===e&&(e=Zs),d(t).overflow=e),t}function mt(t){var e,i,s,a,o,n,r=t._i,h=ta.exec(r)||ea.exec(r);if(h){for(d(t).iso=!0,e=0,i=sa.length;i>e;e++)if(sa[e][1].exec(h[1])){a=sa[e][0],s=sa[e][2]!==!1;break}if(null==a)return void(t._isValid=!1);if(h[3]){for(e=0,i=aa.length;i>e;e++)if(aa[e][1].exec(h[3])){o=(h[2]||" ")+aa[e][0];break}if(null==o)return void(t._isValid=!1)}if(!s&&null!=o)return void(t._isValid=!1);if(h[4]){if(!ia.exec(h[4]))return void(t._isValid=!1);n="Z"}t._f=a+(o||"")+(n||""),Pt(t)}else t._isValid=!1}function pt(e){var i=oa.exec(e._i);return null!==i?void(e._d=new Date(+i[1])):(mt(e),void(e._isValid===!1&&(delete e._isValid,t.createFromInputFallback(e))))}function bt(t,e,i,s,a,o,n){var r=new Date(t,e,i,s,a,o,n);return 100>t&&t>=0&&isFinite(r.getFullYear())&&r.setFullYear(t),r}function vt(t){var e=new Date(Date.UTC.apply(null,arguments));return 100>t&&t>=0&&isFinite(e.getUTCFullYear())&&e.setUTCFullYear(t),e}function xt(t){return yt(t)?366:365}function yt(t){return t%4===0&&t%100!==0||t%400===0}function kt(){return yt(this.year())}function _t(t,e,i){var s=7+e-i,a=(7+vt(t,0,s).getUTCDay()-e)%7;return-a+s-1}function St(t,e,i,s,a){var o,n,r=(7+i-s)%7,h=_t(t,s,a),l=1+7*(e-1)+r+h;return 0>=l?(o=t-1,n=xt(o)+l):l>xt(t)?(o=t+1,n=l-xt(t)):(o=t,n=l),{year:o,dayOfYear:n}}function wt(t,e,i){var s,a,o=_t(t.year(),e,i),n=Math.floor((t.dayOfYear()-o-1)/7)+1;return 1>n?(a=t.year()-1,s=n+Dt(a,e,i)):n>Dt(t.year(),e,i)?(s=n-Dt(t.year(),e,i),a=t.year()+1):(a=t.year(),s=n),{week:s,year:a}}function Dt(t,e,i){var s=_t(t,e,i),a=_t(t+1,e,i);return(xt(t)-s+a)/7}function Mt(t,e,i){return null!=t?t:null!=e?e:i}function Ct(e){var i=new Date(t.now());return e._useUTC?[i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()]:[i.getFullYear(),i.getMonth(),i.getDate()]}function At(t){var e,i,s,a,o=[];if(!t._d){for(s=Ct(t),t._w&&null==t._a[Ns]&&null==t._a[Hs]&&It(t),t._dayOfYear&&(a=Mt(t._a[Ys],s[Ys]),t._dayOfYear>xt(a)&&(d(t)._overflowDayOfYear=!0),i=vt(a,0,t._dayOfYear),t._a[Hs]=i.getUTCMonth(),t._a[Ns]=i.getUTCDate()),e=0;3>e&&null==t._a[e];++e)t._a[e]=o[e]=s[e];for(;7>e;e++)t._a[e]=o[e]=null==t._a[e]?2===e?1:0:t._a[e];24===t._a[Es]&&0===t._a[Us]&&0===t._a[js]&&0===t._a[Gs]&&(t._nextDay=!0,t._a[Es]=0),t._d=(t._useUTC?vt:bt).apply(null,o),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[Es]=24)}}function It(t){var e,i,s,a,o,n,r,h;e=t._w,null!=e.GG||null!=e.W||null!=e.E?(o=1,n=4,i=Mt(e.GG,t._a[Ys],wt(zt(),1,4).year),s=Mt(e.W,1),a=Mt(e.E,1),(1>a||a>7)&&(h=!0)):(o=t._locale._week.dow,n=t._locale._week.doy,i=Mt(e.gg,t._a[Ys],wt(zt(),o,n).year),s=Mt(e.w,1),null!=e.d?(a=e.d,(0>a||a>6)&&(h=!0)):null!=e.e?(a=e.e+o,(e.e<0||e.e>6)&&(h=!0)):a=o),1>s||s>Dt(i,o,n)?d(t)._overflowWeeks=!0:null!=h?d(t)._overflowWeekday=!0:(r=St(i,s,a,o,n),t._a[Ys]=r.year,t._dayOfYear=r.dayOfYear)}function Pt(e){if(e._f===t.ISO_8601)return void mt(e);e._a=[],d(e).empty=!0;var i,s,a,o,n,r=""+e._i,h=r.length,l=0;for(a=Q(e._f,e._locale).match(bs)||[],i=0;i<a.length;i++)o=a[i],s=(r.match(X(o,e))||[])[0],s&&(n=r.substr(0,r.indexOf(s)),n.length>0&&d(e).unusedInput.push(n),r=r.slice(r.indexOf(s)+s.length),l+=s.length),ys[o]?(s?d(e).empty=!1:d(e).unusedTokens.push(o),it(o,s,e)):e._strict&&!s&&d(e).unusedTokens.push(o);d(e).charsLeftOver=h-l,r.length>0&&d(e).unusedInput.push(r),d(e).bigHour===!0&&e._a[Es]<=12&&e._a[Es]>0&&(d(e).bigHour=void 0),d(e).parsedDateParts=e._a.slice(0),d(e).meridiem=e._meridiem,e._a[Es]=Tt(e._locale,e._a[Es],e._meridiem),At(e),gt(e)}function Tt(t,e,i){var s;return null==i?e:null!=t.meridiemHour?t.meridiemHour(e,i):null!=t.isPM?(s=t.isPM(i),s&&12>e&&(e+=12),s||12!==e||(e=0),e):e}function Ft(t){var e,i,s,a,o;if(0===t._f.length)return d(t).invalidFormat=!0,void(t._d=new Date(NaN));for(a=0;a<t._f.length;a++)o=0,e=m({},t),null!=t._useUTC&&(e._useUTC=t._useUTC),e._f=t._f[a],Pt(e),u(e)&&(o+=d(e).charsLeftOver,o+=10*d(e).unusedTokens.length,d(e).score=o,(null==s||s>o)&&(s=o,i=e));h(t,i||e)}function Ot(t){if(!t._d){var e=B(t._i);t._a=n([e.year,e.month,e.day||e.date,e.hour,e.minute,e.second,e.millisecond],function(t){return t&&parseInt(t,10)}),At(t)}}function Vt(t){var e=new p(gt(Rt(t)));return e._nextDay&&(e.add(1,"d"),e._nextDay=void 0),e}function Rt(t){var e=t._i,i=t._f;return t._locale=t._locale||R(t._l),null===e||void 0===i&&""===e?f({nullInput:!0}):("string"==typeof e&&(t._i=e=t._locale.preparse(e)),b(e)?new p(gt(e)):(a(i)?Ft(t):i?Pt(t):o(e)?t._d=e:Wt(t),u(t)||(t._d=null),t))}function Wt(e){var i=e._i;void 0===i?e._d=new Date(t.now()):o(i)?e._d=new Date(i.valueOf()):"string"==typeof i?pt(e):a(i)?(e._a=n(i.slice(0),function(t){return parseInt(t,10)}),At(e)):"object"==typeof i?Ot(e):"number"==typeof i?e._d=new Date(i):t.createFromInputFallback(e)}function Lt(t,e,i,s,a){var o={};return"boolean"==typeof i&&(s=i,i=void 0),o._isAMomentObject=!0,o._useUTC=o._isUTC=a,o._l=i,o._i=t,o._f=e,o._strict=s,Vt(o)}function zt(t,e,i,s){return Lt(t,e,i,s,!1)}function Bt(t,e){var i,s;if(1===e.length&&a(e[0])&&(e=e[0]),!e.length)return zt();for(i=e[0],s=1;s<e.length;++s)e[s].isValid()&&!e[s][t](i)||(i=e[s]);return i}function Yt(){var t=[].slice.call(arguments,0);return Bt("isBefore",t)}function Ht(){var t=[].slice.call(arguments,0);return Bt("isAfter",t)}function Nt(t){var e=B(t),i=e.year||0,s=e.quarter||0,a=e.month||0,o=e.week||0,n=e.day||0,r=e.hour||0,h=e.minute||0,l=e.second||0,c=e.millisecond||0;this._milliseconds=+c+1e3*l+6e4*h+1e3*r*60*60,this._days=+n+7*o,this._months=+a+3*s+12*i,this._data={},this._locale=R(),this._bubble()}function Et(t){return t instanceof Nt}function Ut(t,e){j(t,0,0,function(){var t=this.utcOffset(),i="+";return 0>t&&(t=-t,i="-"),i+U(~~(t/60),2)+e+U(~~t%60,2)})}function jt(t,e){var i=(e||"").match(t)||[],s=i[i.length-1]||[],a=(s+"").match(ca)||["-",0,0],o=+(60*a[1])+x(a[2]);return"+"===a[0]?o:-o}function Gt(e,i){var s,a;return i._isUTC?(s=i.clone(),a=(b(e)||o(e)?e.valueOf():zt(e).valueOf())-s.valueOf(),s._d.setTime(s._d.valueOf()+a),t.updateOffset(s,!1),s):zt(e).local()}function qt(t){return 15*-Math.round(t._d.getTimezoneOffset()/15)}function Zt(e,i){var s,a=this._offset||0;return this.isValid()?null!=e?("string"==typeof e?e=jt(Rs,e):Math.abs(e)<16&&(e=60*e),!this._isUTC&&i&&(s=qt(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),a!==e&&(!i||this._changeInProgress?de(this,oe(e-a,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,t.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?a:qt(this):null!=e?this:NaN}function Qt(t,e){return null!=t?("string"!=typeof t&&(t=-t),this.utcOffset(t,e),this):-this.utcOffset()}function Jt(t){return this.utcOffset(0,t)}function Xt(t){return this._isUTC&&(this.utcOffset(0,t),this._isUTC=!1,t&&this.subtract(qt(this),"m")),this}function $t(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(jt(Vs,this._i)),this}function Kt(t){return this.isValid()?(t=t?zt(t).utcOffset():0,(this.utcOffset()-t)%60===0):!1}function te(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function ee(){if(!g(this._isDSTShifted))return this._isDSTShifted;var t={};if(m(t,this),t=Rt(t),t._a){var e=t._isUTC?l(t._a):zt(t._a);this._isDSTShifted=this.isValid()&&y(t._a,e.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function ie(){return this.isValid()?!this._isUTC:!1}function se(){return this.isValid()?this._isUTC:!1}function ae(){return this.isValid()?this._isUTC&&0===this._offset:!1}function oe(t,e){var i,s,a,o=t,n=null;return Et(t)?o={ms:t._milliseconds,d:t._days,M:t._months}:"number"==typeof t?(o={},e?o[e]=t:o.milliseconds=t):(n=da.exec(t))?(i="-"===n[1]?-1:1,o={y:0,d:x(n[Ns])*i,h:x(n[Es])*i,m:x(n[Us])*i,s:x(n[js])*i,ms:x(n[Gs])*i}):(n=ua.exec(t))?(i="-"===n[1]?-1:1,o={y:ne(n[2],i),M:ne(n[3],i),w:ne(n[4],i),d:ne(n[5],i),h:ne(n[6],i),m:ne(n[7],i),s:ne(n[8],i)}):null==o?o={}:"object"==typeof o&&("from"in o||"to"in o)&&(a=he(zt(o.from),zt(o.to)),o={},o.ms=a.milliseconds,o.M=a.months),s=new Nt(o),Et(t)&&r(t,"_locale")&&(s._locale=t._locale),s}function ne(t,e){var i=t&&parseFloat(t.replace(",","."));return(isNaN(i)?0:i)*e}function re(t,e){var i={milliseconds:0,months:0};return i.months=e.month()-t.month()+12*(e.year()-t.year()),t.clone().add(i.months,"M").isAfter(e)&&--i.months,i.milliseconds=+e-+t.clone().add(i.months,"M"),i}function he(t,e){var i;return t.isValid()&&e.isValid()?(e=Gt(e,t),t.isBefore(e)?i=re(t,e):(i=re(e,t),i.milliseconds=-i.milliseconds,i.months=-i.months),i):{milliseconds:0,months:0}}function le(t){return 0>t?-1*Math.round(-1*t):Math.round(t)}function ce(t,e){return function(i,s){var a,o;return null===s||isNaN(+s)||(S(e,"moment()."+e+"(period, number) is deprecated. Please use moment()."+e+"(number, period)."),o=i,i=s,s=o),i="string"==typeof i?+i:i,a=oe(i,s),de(this,a,t),this}}function de(e,i,s,a){var o=i._milliseconds,n=le(i._days),r=le(i._months);e.isValid()&&(a=null==a?!0:a,o&&e._d.setTime(e._d.valueOf()+o*s),n&&N(e,"Date",H(e,"Date")+n*s),r&&ht(e,H(e,"Month")+r*s),a&&t.updateOffset(e,n||r))}function ue(t,e){var i=t||zt(),s=Gt(i,this).startOf("day"),a=this.diff(s,"days",!0),o=-6>a?"sameElse":-1>a?"lastWeek":0>a?"lastDay":1>a?"sameDay":2>a?"nextDay":7>a?"nextWeek":"sameElse",n=e&&(w(e[o])?e[o]():e[o]);return this.format(n||this.localeData().calendar(o,this,zt(i)))}function fe(){return new p(this)}function ge(t,e){var i=b(t)?t:zt(t);return this.isValid()&&i.isValid()?(e=z(g(e)?"millisecond":e),"millisecond"===e?this.valueOf()>i.valueOf():i.valueOf()<this.clone().startOf(e).valueOf()):!1}function me(t,e){var i=b(t)?t:zt(t);return this.isValid()&&i.isValid()?(e=z(g(e)?"millisecond":e),"millisecond"===e?this.valueOf()<i.valueOf():this.clone().endOf(e).valueOf()<i.valueOf()):!1}function pe(t,e,i,s){return s=s||"()",("("===s[0]?this.isAfter(t,i):!this.isBefore(t,i))&&(")"===s[1]?this.isBefore(e,i):!this.isAfter(e,i))}function be(t,e){var i,s=b(t)?t:zt(t);return this.isValid()&&s.isValid()?(e=z(e||"millisecond"),"millisecond"===e?this.valueOf()===s.valueOf():(i=s.valueOf(),this.clone().startOf(e).valueOf()<=i&&i<=this.clone().endOf(e).valueOf())):!1}function ve(t,e){return this.isSame(t,e)||this.isAfter(t,e)}function xe(t,e){return this.isSame(t,e)||this.isBefore(t,e)}function ye(t,e,i){var s,a,o,n;return this.isValid()?(s=Gt(t,this),s.isValid()?(a=6e4*(s.utcOffset()-this.utcOffset()),e=z(e),"year"===e||"month"===e||"quarter"===e?(n=ke(this,s),"quarter"===e?n/=3:"year"===e&&(n/=12)):(o=this-s,n="second"===e?o/1e3:"minute"===e?o/6e4:"hour"===e?o/36e5:"day"===e?(o-a)/864e5:"week"===e?(o-a)/6048e5:o),i?n:v(n)):NaN):NaN}function ke(t,e){var i,s,a=12*(e.year()-t.year())+(e.month()-t.month()),o=t.clone().add(a,"months");return 0>e-o?(i=t.clone().add(a-1,"months"),s=(e-o)/(o-i)):(i=t.clone().add(a+1,"months"),s=(e-o)/(i-o)),-(a+s)||0}function _e(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function Se(){var t=this.clone().utc();return 0<t.year()&&t.year()<=9999?w(Date.prototype.toISOString)?this.toDate().toISOString():Z(t,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):Z(t,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function we(e){e||(e=this.isUtc()?t.defaultFormatUtc:t.defaultFormat);var i=Z(this,e);return this.localeData().postformat(i)}function De(t,e){return this.isValid()&&(b(t)&&t.isValid()||zt(t).isValid())?oe({to:this,from:t}).locale(this.locale()).humanize(!e):this.localeData().invalidDate()}function Me(t){return this.from(zt(),t)}function Ce(t,e){return this.isValid()&&(b(t)&&t.isValid()||zt(t).isValid())?oe({from:this,to:t}).locale(this.locale()).humanize(!e):this.localeData().invalidDate()}function Ae(t){return this.to(zt(),t)}function Ie(t){var e;return void 0===t?this._locale._abbr:(e=R(t),null!=e&&(this._locale=e),this)}function Pe(){return this._locale}function Te(t){switch(t=z(t)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===t&&this.weekday(0),"isoWeek"===t&&this.isoWeekday(1),"quarter"===t&&this.month(3*Math.floor(this.month()/3)),this}function Fe(t){return t=z(t),void 0===t||"millisecond"===t?this:("date"===t&&(t="day"),this.startOf(t).add(1,"isoWeek"===t?"week":t).subtract(1,"ms"))}function Oe(){return this._d.valueOf()-6e4*(this._offset||0)}function Ve(){return Math.floor(this.valueOf()/1e3)}function Re(){return this._offset?new Date(this.valueOf()):this._d}function We(){var t=this;return[t.year(),t.month(),t.date(),t.hour(),t.minute(),t.second(),t.millisecond()]}function Le(){var t=this;return{years:t.year(),months:t.month(),date:t.date(),hours:t.hours(),minutes:t.minutes(),seconds:t.seconds(),milliseconds:t.milliseconds()}}function ze(){return this.isValid()?this.toISOString():null}function Be(){return u(this)}function Ye(){return h({},d(this))}function He(){return d(this).overflow}function Ne(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}function Ee(t,e){j(0,[t,t.length],0,e)}function Ue(t){return Ze.call(this,t,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function je(t){return Ze.call(this,t,this.isoWeek(),this.isoWeekday(),1,4)}function Ge(){return Dt(this.year(),1,4)}function qe(){var t=this.localeData()._week;return Dt(this.year(),t.dow,t.doy)}function Ze(t,e,i,s,a){var o;return null==t?wt(this,s,a).year:(o=Dt(t,s,a),e>o&&(e=o),Qe.call(this,t,e,i,s,a))}function Qe(t,e,i,s,a){var o=St(t,e,i,s,a),n=vt(o.year,0,o.dayOfYear);return this.year(n.getUTCFullYear()),this.month(n.getUTCMonth()),this.date(n.getUTCDate()),this}function Je(t){return null==t?Math.ceil((this.month()+1)/3):this.month(3*(t-1)+this.month()%3)}function Xe(t){return wt(t,this._week.dow,this._week.doy).week}function $e(){return this._week.dow}function Ke(){return this._week.doy}function ti(t){var e=this.localeData().week(this);return null==t?e:this.add(7*(t-e),"d")}function ei(t){var e=wt(this,1,4).week;return null==t?e:this.add(7*(t-e),"d")}function ii(t,e){return"string"!=typeof t?t:isNaN(t)?(t=e.weekdaysParse(t),"number"==typeof t?t:null):parseInt(t,10)}function si(t,e){return a(this._weekdays)?this._weekdays[t.day()]:this._weekdays[this._weekdays.isFormat.test(e)?"format":"standalone"][t.day()]}function ai(t){return this._weekdaysShort[t.day()]}function oi(t){return this._weekdaysMin[t.day()]}function ni(t,e,i){var s,a,o,n=t.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;7>s;++s)o=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(o,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(o,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(o,"").toLocaleLowerCase();return i?"dddd"===e?(a=gs.call(this._weekdaysParse,n),-1!==a?a:null):"ddd"===e?(a=gs.call(this._shortWeekdaysParse,n),-1!==a?a:null):(a=gs.call(this._minWeekdaysParse,n),-1!==a?a:null):"dddd"===e?(a=gs.call(this._weekdaysParse,n), -1!==a?a:(a=gs.call(this._shortWeekdaysParse,n),-1!==a?a:(a=gs.call(this._minWeekdaysParse,n),-1!==a?a:null))):"ddd"===e?(a=gs.call(this._shortWeekdaysParse,n),-1!==a?a:(a=gs.call(this._weekdaysParse,n),-1!==a?a:(a=gs.call(this._minWeekdaysParse,n),-1!==a?a:null))):(a=gs.call(this._minWeekdaysParse,n),-1!==a?a:(a=gs.call(this._weekdaysParse,n),-1!==a?a:(a=gs.call(this._shortWeekdaysParse,n),-1!==a?a:null)))}function ri(t,e,i){var s,a,o;if(this._weekdaysParseExact)return ni.call(this,t,e,i);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;7>s;s++){if(a=l([2e3,1]).day(s),i&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(a,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(a,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(a,"").replace(".",".?")+"$","i")),this._weekdaysParse[s]||(o="^"+this.weekdays(a,"")+"|^"+this.weekdaysShort(a,"")+"|^"+this.weekdaysMin(a,""),this._weekdaysParse[s]=new RegExp(o.replace(".",""),"i")),i&&"dddd"===e&&this._fullWeekdaysParse[s].test(t))return s;if(i&&"ddd"===e&&this._shortWeekdaysParse[s].test(t))return s;if(i&&"dd"===e&&this._minWeekdaysParse[s].test(t))return s;if(!i&&this._weekdaysParse[s].test(t))return s}}function hi(t){if(!this.isValid())return null!=t?this:NaN;var e=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=t?(t=ii(t,this.localeData()),this.add(t-e,"d")):e}function li(t){if(!this.isValid())return null!=t?this:NaN;var e=(this.day()+7-this.localeData()._week.dow)%7;return null==t?e:this.add(t-e,"d")}function ci(t){return this.isValid()?null==t?this.day()||7:this.day(this.day()%7?t:t-7):null!=t?this:NaN}function di(t){return this._weekdaysParseExact?(r(this,"_weekdaysRegex")||gi.call(this),t?this._weekdaysStrictRegex:this._weekdaysRegex):this._weekdaysStrictRegex&&t?this._weekdaysStrictRegex:this._weekdaysRegex}function ui(t){return this._weekdaysParseExact?(r(this,"_weekdaysRegex")||gi.call(this),t?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):this._weekdaysShortStrictRegex&&t?this._weekdaysShortStrictRegex:this._weekdaysShortRegex}function fi(t){return this._weekdaysParseExact?(r(this,"_weekdaysRegex")||gi.call(this),t?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):this._weekdaysMinStrictRegex&&t?this._weekdaysMinStrictRegex:this._weekdaysMinRegex}function gi(){function t(t,e){return e.length-t.length}var e,i,s,a,o,n=[],r=[],h=[],c=[];for(e=0;7>e;e++)i=l([2e3,1]).day(e),s=this.weekdaysMin(i,""),a=this.weekdaysShort(i,""),o=this.weekdays(i,""),n.push(s),r.push(a),h.push(o),c.push(s),c.push(a),c.push(o);for(n.sort(t),r.sort(t),h.sort(t),c.sort(t),e=0;7>e;e++)r[e]=K(r[e]),h[e]=K(h[e]),c[e]=K(c[e]);this._weekdaysRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+h.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+n.join("|")+")","i")}function mi(t){var e=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==t?e:this.add(t-e,"d")}function pi(){return this.hours()%12||12}function bi(){return this.hours()||24}function vi(t,e){j(t,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),e)})}function xi(t,e){return e._meridiemParse}function yi(t){return"p"===(t+"").toLowerCase().charAt(0)}function ki(t,e,i){return t>11?i?"pm":"PM":i?"am":"AM"}function _i(t,e){e[Gs]=x(1e3*("0."+t))}function Si(){return this._isUTC?"UTC":""}function wi(){return this._isUTC?"Coordinated Universal Time":""}function Di(t){return zt(1e3*t)}function Mi(){return zt.apply(null,arguments).parseZone()}function Ci(t,e,i){var s=this._calendar[t];return w(s)?s.call(e,i):s}function Ai(t){var e=this._longDateFormat[t],i=this._longDateFormat[t.toUpperCase()];return e||!i?e:(this._longDateFormat[t]=i.replace(/MMMM|MM|DD|dddd/g,function(t){return t.slice(1)}),this._longDateFormat[t])}function Ii(){return this._invalidDate}function Pi(t){return this._ordinal.replace("%d",t)}function Ti(t){return t}function Fi(t,e,i,s){var a=this._relativeTime[i];return w(a)?a(t,e,i,s):a.replace(/%d/i,t)}function Oi(t,e){var i=this._relativeTime[t>0?"future":"past"];return w(i)?i(e):i.replace(/%s/i,e)}function Vi(t,e,i,s){var a=R(),o=l().set(s,e);return a[i](o,t)}function Ri(t,e,i){if("number"==typeof t&&(e=t,t=void 0),t=t||"",null!=e)return Vi(t,e,i,"month");var s,a=[];for(s=0;12>s;s++)a[s]=Vi(t,s,i,"month");return a}function Wi(t,e,i,s){"boolean"==typeof t?("number"==typeof e&&(i=e,e=void 0),e=e||""):(e=t,i=e,t=!1,"number"==typeof e&&(i=e,e=void 0),e=e||"");var a=R(),o=t?a._week.dow:0;if(null!=i)return Vi(e,(i+o)%7,s,"day");var n,r=[];for(n=0;7>n;n++)r[n]=Vi(e,(n+o)%7,s,"day");return r}function Li(t,e){return Ri(t,e,"months")}function zi(t,e){return Ri(t,e,"monthsShort")}function Bi(t,e,i){return Wi(t,e,i,"weekdays")}function Yi(t,e,i){return Wi(t,e,i,"weekdaysShort")}function Hi(t,e,i){return Wi(t,e,i,"weekdaysMin")}function Ni(){var t=this._data;return this._milliseconds=Ba(this._milliseconds),this._days=Ba(this._days),this._months=Ba(this._months),t.milliseconds=Ba(t.milliseconds),t.seconds=Ba(t.seconds),t.minutes=Ba(t.minutes),t.hours=Ba(t.hours),t.months=Ba(t.months),t.years=Ba(t.years),this}function Ei(t,e,i,s){var a=oe(e,i);return t._milliseconds+=s*a._milliseconds,t._days+=s*a._days,t._months+=s*a._months,t._bubble()}function Ui(t,e){return Ei(this,t,e,1)}function ji(t,e){return Ei(this,t,e,-1)}function Gi(t){return 0>t?Math.floor(t):Math.ceil(t)}function qi(){var t,e,i,s,a,o=this._milliseconds,n=this._days,r=this._months,h=this._data;return o>=0&&n>=0&&r>=0||0>=o&&0>=n&&0>=r||(o+=864e5*Gi(Qi(r)+n),n=0,r=0),h.milliseconds=o%1e3,t=v(o/1e3),h.seconds=t%60,e=v(t/60),h.minutes=e%60,i=v(e/60),h.hours=i%24,n+=v(i/24),a=v(Zi(n)),r+=a,n-=Gi(Qi(a)),s=v(r/12),r%=12,h.days=n,h.months=r,h.years=s,this}function Zi(t){return 4800*t/146097}function Qi(t){return 146097*t/4800}function Ji(t){var e,i,s=this._milliseconds;if(t=z(t),"month"===t||"year"===t)return e=this._days+s/864e5,i=this._months+Zi(e),"month"===t?i:i/12;switch(e=this._days+Math.round(Qi(this._months)),t){case"week":return e/7+s/6048e5;case"day":return e+s/864e5;case"hour":return 24*e+s/36e5;case"minute":return 1440*e+s/6e4;case"second":return 86400*e+s/1e3;case"millisecond":return Math.floor(864e5*e)+s;default:throw new Error("Unknown unit "+t)}}function Xi(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*x(this._months/12)}function $i(t){return function(){return this.as(t)}}function Ki(t){return t=z(t),this[t+"s"]()}function ts(t){return function(){return this._data[t]}}function es(){return v(this.days()/7)}function is(t,e,i,s,a){return a.relativeTime(e||1,!!i,t,s)}function ss(t,e,i){var s=oe(t).abs(),a=eo(s.as("s")),o=eo(s.as("m")),n=eo(s.as("h")),r=eo(s.as("d")),h=eo(s.as("M")),l=eo(s.as("y")),c=a<io.s&&["s",a]||1>=o&&["m"]||o<io.m&&["mm",o]||1>=n&&["h"]||n<io.h&&["hh",n]||1>=r&&["d"]||r<io.d&&["dd",r]||1>=h&&["M"]||h<io.M&&["MM",h]||1>=l&&["y"]||["yy",l];return c[2]=e,c[3]=+t>0,c[4]=i,is.apply(null,c)}function as(t,e){return void 0===io[t]?!1:void 0===e?io[t]:(io[t]=e,!0)}function os(t){var e=this.localeData(),i=ss(this,!t,e);return t&&(i=e.pastFuture(+this,i)),e.postformat(i)}function ns(){var t,e,i,s=so(this._milliseconds)/1e3,a=so(this._days),o=so(this._months);t=v(s/60),e=v(t/60),s%=60,t%=60,i=v(o/12),o%=12;var n=i,r=o,h=a,l=e,c=t,d=s,u=this.asSeconds();return u?(0>u?"-":"")+"P"+(n?n+"Y":"")+(r?r+"M":"")+(h?h+"D":"")+(l||c||d?"T":"")+(l?l+"H":"")+(c?c+"M":"")+(d?d+"S":""):"P0D"}var rs,hs;hs=Array.prototype.some?Array.prototype.some:function(t){for(var e=Object(this),i=e.length>>>0,s=0;i>s;s++)if(s in e&&t.call(this,e[s],s,e))return!0;return!1};var ls=t.momentProperties=[],cs=!1,ds={};t.suppressDeprecationWarnings=!1,t.deprecationHandler=null;var us;us=Object.keys?Object.keys:function(t){var e,i=[];for(e in t)r(t,e)&&i.push(e);return i};var fs,gs,ms={},ps={},bs=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,vs=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,xs={},ys={},ks=/\d/,_s=/\d\d/,Ss=/\d{3}/,ws=/\d{4}/,Ds=/[+-]?\d{6}/,Ms=/\d\d?/,Cs=/\d\d\d\d?/,As=/\d\d\d\d\d\d?/,Is=/\d{1,3}/,Ps=/\d{1,4}/,Ts=/[+-]?\d{1,6}/,Fs=/\d+/,Os=/[+-]?\d+/,Vs=/Z|[+-]\d\d:?\d\d/gi,Rs=/Z|[+-]\d\d(?::?\d\d)?/gi,Ws=/[+-]?\d+(\.\d{1,3})?/,Ls=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,zs={},Bs={},Ys=0,Hs=1,Ns=2,Es=3,Us=4,js=5,Gs=6,qs=7,Zs=8;gs=Array.prototype.indexOf?Array.prototype.indexOf:function(t){var e;for(e=0;e<this.length;++e)if(this[e]===t)return e;return-1},j("M",["MM",2],"Mo",function(){return this.month()+1}),j("MMM",0,0,function(t){return this.localeData().monthsShort(this,t)}),j("MMMM",0,0,function(t){return this.localeData().months(this,t)}),L("month","M"),J("M",Ms),J("MM",Ms,_s),J("MMM",function(t,e){return e.monthsShortRegex(t)}),J("MMMM",function(t,e){return e.monthsRegex(t)}),tt(["M","MM"],function(t,e){e[Hs]=x(t)-1}),tt(["MMM","MMMM"],function(t,e,i,s){var a=i._locale.monthsParse(t,s,i._strict);null!=a?e[Hs]=a:d(i).invalidMonth=t});var Qs=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/,Js="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Xs="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),$s=Ls,Ks=Ls,ta=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,ea=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,ia=/Z|[+-]\d\d(?::?\d\d)?/,sa=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],aa=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],oa=/^\/?Date\((\-?\d+)/i;t.createFromInputFallback=_("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(t){t._d=new Date(t._i+(t._useUTC?" UTC":""))}),j("Y",0,0,function(){var t=this.year();return 9999>=t?""+t:"+"+t}),j(0,["YY",2],0,function(){return this.year()%100}),j(0,["YYYY",4],0,"year"),j(0,["YYYYY",5],0,"year"),j(0,["YYYYYY",6,!0],0,"year"),L("year","y"),J("Y",Os),J("YY",Ms,_s),J("YYYY",Ps,ws),J("YYYYY",Ts,Ds),J("YYYYYY",Ts,Ds),tt(["YYYYY","YYYYYY"],Ys),tt("YYYY",function(e,i){i[Ys]=2===e.length?t.parseTwoDigitYear(e):x(e)}),tt("YY",function(e,i){i[Ys]=t.parseTwoDigitYear(e)}),tt("Y",function(t,e){e[Ys]=parseInt(t,10)}),t.parseTwoDigitYear=function(t){return x(t)+(x(t)>68?1900:2e3)};var na=Y("FullYear",!0);t.ISO_8601=function(){};var ra=_("moment().min is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var t=zt.apply(null,arguments);return this.isValid()&&t.isValid()?this>t?this:t:f()}),ha=_("moment().max is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var t=zt.apply(null,arguments);return this.isValid()&&t.isValid()?t>this?this:t:f()}),la=function(){return Date.now?Date.now():+new Date};Ut("Z",":"),Ut("ZZ",""),J("Z",Rs),J("ZZ",Rs),tt(["Z","ZZ"],function(t,e,i){i._useUTC=!0,i._tzm=jt(Rs,t)});var ca=/([\+\-]|\d\d)/gi;t.updateOffset=function(){};var da=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/,ua=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;oe.fn=Nt.prototype;var fa=ce(1,"add"),ga=ce(-1,"subtract");t.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",t.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var ma=_("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(t){return void 0===t?this.localeData():this.locale(t)});j(0,["gg",2],0,function(){return this.weekYear()%100}),j(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Ee("gggg","weekYear"),Ee("ggggg","weekYear"),Ee("GGGG","isoWeekYear"),Ee("GGGGG","isoWeekYear"),L("weekYear","gg"),L("isoWeekYear","GG"),J("G",Os),J("g",Os),J("GG",Ms,_s),J("gg",Ms,_s),J("GGGG",Ps,ws),J("gggg",Ps,ws),J("GGGGG",Ts,Ds),J("ggggg",Ts,Ds),et(["gggg","ggggg","GGGG","GGGGG"],function(t,e,i,s){e[s.substr(0,2)]=x(t)}),et(["gg","GG"],function(e,i,s,a){i[a]=t.parseTwoDigitYear(e)}),j("Q",0,"Qo","quarter"),L("quarter","Q"),J("Q",ks),tt("Q",function(t,e){e[Hs]=3*(x(t)-1)}),j("w",["ww",2],"wo","week"),j("W",["WW",2],"Wo","isoWeek"),L("week","w"),L("isoWeek","W"),J("w",Ms),J("ww",Ms,_s),J("W",Ms),J("WW",Ms,_s),et(["w","ww","W","WW"],function(t,e,i,s){e[s.substr(0,1)]=x(t)});var pa={dow:0,doy:6};j("D",["DD",2],"Do","date"),L("date","D"),J("D",Ms),J("DD",Ms,_s),J("Do",function(t,e){return t?e._ordinalParse:e._ordinalParseLenient}),tt(["D","DD"],Ns),tt("Do",function(t,e){e[Ns]=x(t.match(Ms)[0],10)});var ba=Y("Date",!0);j("d",0,"do","day"),j("dd",0,0,function(t){return this.localeData().weekdaysMin(this,t)}),j("ddd",0,0,function(t){return this.localeData().weekdaysShort(this,t)}),j("dddd",0,0,function(t){return this.localeData().weekdays(this,t)}),j("e",0,0,"weekday"),j("E",0,0,"isoWeekday"),L("day","d"),L("weekday","e"),L("isoWeekday","E"),J("d",Ms),J("e",Ms),J("E",Ms),J("dd",function(t,e){return e.weekdaysMinRegex(t)}),J("ddd",function(t,e){return e.weekdaysShortRegex(t)}),J("dddd",function(t,e){return e.weekdaysRegex(t)}),et(["dd","ddd","dddd"],function(t,e,i,s){var a=i._locale.weekdaysParse(t,s,i._strict);null!=a?e.d=a:d(i).invalidWeekday=t}),et(["d","e","E"],function(t,e,i,s){e[s]=x(t)});var va="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),xa="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),ya="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),ka=Ls,_a=Ls,Sa=Ls;j("DDD",["DDDD",3],"DDDo","dayOfYear"),L("dayOfYear","DDD"),J("DDD",Is),J("DDDD",Ss),tt(["DDD","DDDD"],function(t,e,i){i._dayOfYear=x(t)}),j("H",["HH",2],0,"hour"),j("h",["hh",2],0,pi),j("k",["kk",2],0,bi),j("hmm",0,0,function(){return""+pi.apply(this)+U(this.minutes(),2)}),j("hmmss",0,0,function(){return""+pi.apply(this)+U(this.minutes(),2)+U(this.seconds(),2)}),j("Hmm",0,0,function(){return""+this.hours()+U(this.minutes(),2)}),j("Hmmss",0,0,function(){return""+this.hours()+U(this.minutes(),2)+U(this.seconds(),2)}),vi("a",!0),vi("A",!1),L("hour","h"),J("a",xi),J("A",xi),J("H",Ms),J("h",Ms),J("HH",Ms,_s),J("hh",Ms,_s),J("hmm",Cs),J("hmmss",As),J("Hmm",Cs),J("Hmmss",As),tt(["H","HH"],Es),tt(["a","A"],function(t,e,i){i._isPm=i._locale.isPM(t),i._meridiem=t}),tt(["h","hh"],function(t,e,i){e[Es]=x(t),d(i).bigHour=!0}),tt("hmm",function(t,e,i){var s=t.length-2;e[Es]=x(t.substr(0,s)),e[Us]=x(t.substr(s)),d(i).bigHour=!0}),tt("hmmss",function(t,e,i){var s=t.length-4,a=t.length-2;e[Es]=x(t.substr(0,s)),e[Us]=x(t.substr(s,2)),e[js]=x(t.substr(a)),d(i).bigHour=!0}),tt("Hmm",function(t,e,i){var s=t.length-2;e[Es]=x(t.substr(0,s)),e[Us]=x(t.substr(s))}),tt("Hmmss",function(t,e,i){var s=t.length-4,a=t.length-2;e[Es]=x(t.substr(0,s)),e[Us]=x(t.substr(s,2)),e[js]=x(t.substr(a))});var wa=/[ap]\.?m?\.?/i,Da=Y("Hours",!0);j("m",["mm",2],0,"minute"),L("minute","m"),J("m",Ms),J("mm",Ms,_s),tt(["m","mm"],Us);var Ma=Y("Minutes",!1);j("s",["ss",2],0,"second"),L("second","s"),J("s",Ms),J("ss",Ms,_s),tt(["s","ss"],js);var Ca=Y("Seconds",!1);j("S",0,0,function(){return~~(this.millisecond()/100)}),j(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),j(0,["SSS",3],0,"millisecond"),j(0,["SSSS",4],0,function(){return 10*this.millisecond()}),j(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),j(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),j(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),j(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),j(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),L("millisecond","ms"),J("S",Is,ks),J("SS",Is,_s),J("SSS",Is,Ss);var Aa;for(Aa="SSSS";Aa.length<=9;Aa+="S")J(Aa,Fs);for(Aa="S";Aa.length<=9;Aa+="S")tt(Aa,_i);var Ia=Y("Milliseconds",!1);j("z",0,0,"zoneAbbr"),j("zz",0,0,"zoneName");var Pa=p.prototype;Pa.add=fa,Pa.calendar=ue,Pa.clone=fe,Pa.diff=ye,Pa.endOf=Fe,Pa.format=we,Pa.from=De,Pa.fromNow=Me,Pa.to=Ce,Pa.toNow=Ae,Pa.get=E,Pa.invalidAt=He,Pa.isAfter=ge,Pa.isBefore=me,Pa.isBetween=pe,Pa.isSame=be,Pa.isSameOrAfter=ve,Pa.isSameOrBefore=xe,Pa.isValid=Be,Pa.lang=ma,Pa.locale=Ie,Pa.localeData=Pe,Pa.max=ha,Pa.min=ra,Pa.parsingFlags=Ye,Pa.set=E,Pa.startOf=Te,Pa.subtract=ga,Pa.toArray=We,Pa.toObject=Le,Pa.toDate=Re,Pa.toISOString=Se,Pa.toJSON=ze,Pa.toString=_e,Pa.unix=Ve,Pa.valueOf=Oe,Pa.creationData=Ne,Pa.year=na,Pa.isLeapYear=kt,Pa.weekYear=Ue,Pa.isoWeekYear=je,Pa.quarter=Pa.quarters=Je,Pa.month=lt,Pa.daysInMonth=ct,Pa.week=Pa.weeks=ti,Pa.isoWeek=Pa.isoWeeks=ei,Pa.weeksInYear=qe,Pa.isoWeeksInYear=Ge,Pa.date=ba,Pa.day=Pa.days=hi,Pa.weekday=li,Pa.isoWeekday=ci,Pa.dayOfYear=mi,Pa.hour=Pa.hours=Da,Pa.minute=Pa.minutes=Ma,Pa.second=Pa.seconds=Ca,Pa.millisecond=Pa.milliseconds=Ia,Pa.utcOffset=Zt,Pa.utc=Jt,Pa.local=Xt,Pa.parseZone=$t,Pa.hasAlignedHourOffset=Kt,Pa.isDST=te,Pa.isDSTShifted=ee,Pa.isLocal=ie,Pa.isUtcOffset=se,Pa.isUtc=ae,Pa.isUTC=ae,Pa.zoneAbbr=Si,Pa.zoneName=wi,Pa.dates=_("dates accessor is deprecated. Use date instead.",ba),Pa.months=_("months accessor is deprecated. Use month instead",lt),Pa.years=_("years accessor is deprecated. Use year instead",na),Pa.zone=_("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Qt);var Ta=Pa,Fa={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Oa={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},Va="Invalid date",Ra="%d",Wa=/\d{1,2}/,La={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},za=A.prototype;za._calendar=Fa,za.calendar=Ci,za._longDateFormat=Oa,za.longDateFormat=Ai,za._invalidDate=Va,za.invalidDate=Ii,za._ordinal=Ra,za.ordinal=Pi,za._ordinalParse=Wa,za.preparse=Ti,za.postformat=Ti,za._relativeTime=La,za.relativeTime=Fi,za.pastFuture=Oi,za.set=M,za.months=at,za._months=Js,za.monthsShort=ot,za._monthsShort=Xs,za.monthsParse=rt,za._monthsRegex=Ks,za.monthsRegex=ut,za._monthsShortRegex=$s,za.monthsShortRegex=dt,za.week=Xe,za._week=pa,za.firstDayOfYear=Ke,za.firstDayOfWeek=$e,za.weekdays=si,za._weekdays=va,za.weekdaysMin=oi,za._weekdaysMin=ya,za.weekdaysShort=ai,za._weekdaysShort=xa,za.weekdaysParse=ri,za._weekdaysRegex=ka,za.weekdaysRegex=di,za._weekdaysShortRegex=_a,za.weekdaysShortRegex=ui,za._weekdaysMinRegex=Sa,za.weekdaysMinRegex=fi,za.isPM=yi,za._meridiemParse=wa,za.meridiem=ki,F("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(t){var e=t%10,i=1===x(t%100/10)?"th":1===e?"st":2===e?"nd":3===e?"rd":"th";return t+i}}),t.lang=_("moment.lang is deprecated. Use moment.locale instead.",F),t.langData=_("moment.langData is deprecated. Use moment.localeData instead.",R);var Ba=Math.abs,Ya=$i("ms"),Ha=$i("s"),Na=$i("m"),Ea=$i("h"),Ua=$i("d"),ja=$i("w"),Ga=$i("M"),qa=$i("y"),Za=ts("milliseconds"),Qa=ts("seconds"),Ja=ts("minutes"),Xa=ts("hours"),$a=ts("days"),Ka=ts("months"),to=ts("years"),eo=Math.round,io={s:45,m:45,h:22,d:26,M:11},so=Math.abs,ao=Nt.prototype;ao.abs=Ni,ao.add=Ui,ao.subtract=ji,ao.as=Ji,ao.asMilliseconds=Ya,ao.asSeconds=Ha,ao.asMinutes=Na,ao.asHours=Ea,ao.asDays=Ua,ao.asWeeks=ja,ao.asMonths=Ga,ao.asYears=qa,ao.valueOf=Xi,ao._bubble=qi,ao.get=Ki,ao.milliseconds=Za,ao.seconds=Qa,ao.minutes=Ja,ao.hours=Xa,ao.days=$a,ao.weeks=es,ao.months=Ka,ao.years=to,ao.humanize=os,ao.toISOString=ns,ao.toString=ns,ao.toJSON=ns,ao.locale=Ie,ao.localeData=Pe,ao.toIsoString=_("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",ns),ao.lang=ma,j("X",0,0,"unix"),j("x",0,0,"valueOf"),J("x",Os),J("X",Ws),tt("X",function(t,e,i){i._d=new Date(1e3*parseFloat(t,10))}),tt("x",function(t,e,i){i._d=new Date(x(t))}),t.version="2.13.0",s(zt),t.fn=Ta,t.min=Yt,t.max=Ht,t.now=la,t.utc=l,t.unix=Di,t.months=Li,t.isDate=o,t.locale=F,t.invalid=f,t.duration=oe,t.isMoment=b,t.weekdays=Bi,t.parseZone=Mi,t.localeData=R,t.isDuration=Et,t.monthsShort=zi,t.weekdaysMin=Hi,t.defineLocale=O,t.updateLocale=V,t.locales=W,t.weekdaysShort=Yi,t.normalizeUnits=z,t.relativeTimeThreshold=as,t.prototype=Ta;var oo=t;return oo})},{}],43:[function(t,e,i){function s(t){return t=t||7,Math.random().toString(35).substr(2,t)}e.exports=s},{}],44:[function(t,e,i){(function(e){"use strict";function s(t){return t&&t.__esModule?t:{"default":t}}function a(t){return u["default"].createElement(x,c({},t,{type:"doughnut"}))}function o(t){return u["default"].createElement(x,c({},t,{type:"pie"}))}function n(t){return u["default"].createElement(x,c({},t,{type:"line"}))}function r(t){return u["default"].createElement(x,c({},t,{type:"bar"}))}function h(t){return u["default"].createElement(x,c({},t,{type:"radar"}))}function l(t){return u["default"].createElement(x,c({},t,{type:"polarArea"}))}Object.defineProperty(i,"__esModule",{value:!0});var c=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t};i.Doughnut=a,i.Pie=o,i.Line=n,i.Bar=r,i.Radar=h,i.Polar=l;var d="undefined"!=typeof window?window.React:"undefined"!=typeof e?e.React:null,u=s(d),f=t("react-dom"),g=s(f),m=t("chart.js"),p=s(m),b=t("uid"),v=s(b),x=u["default"].createClass({displayName:"ChartComponent",propTypes:{data:d.PropTypes.object.isRequired,height:d.PropTypes.number,legend:d.PropTypes.object,options:d.PropTypes.object,redraw:d.PropTypes.bool,type:d.PropTypes.oneOf(["doughnut","pie","line","bar","radar","polarArea"]),width:d.PropTypes.number},getDefaultProps:function(){return{legend:{display:!0,position:"bottom"},type:"doughnut",height:200,width:200,redraw:!0}},componentWillMount:function(){this.chart_instance=void 0,this.chart_uid=(0,v["default"])(10)},componentDidMount:function(){this.renderChart()},componentDidUpdate:function(){this.props.redraw&&(this.chart_instance.destroy(),this.renderChart())},shouldComponentUpdate:function(t){return this.props!==t},componentWillUnmount:function(){this.chart_instance.destroy()},renderChart:function(){var t=this.props,e=t.data,i=t.options,s=(t.legend,t.type),a=g["default"].findDOMNode(this.refs[this.getRefKey()]);this.chart_instance=new p["default"](a,{type:s,data:e,options:i})},getRefKey:function(){return"chart-"+this.chart_uid},render:function(){var t=this.props,e=t.height,i=t.width;return u["default"].createElement("canvas",{height:e,width:i,ref:this.getRefKey(),key:this.chart_uid})}});i["default"]=x}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"chart.js":1,"react-dom":void 0,uid:43}]},{},[44])(44)});
app/containers/HomePage/index.js
will-hitchcock/styled-components-example
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react' import Container from 'components/Container' import ButtonLink from 'components/ButtonLink' export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Container> <ButtonLink href="/grid">Grid Demo</ButtonLink> <ButtonLink href="/example">Demo</ButtonLink> </Container> ) } }
Paths/React/05.Building Scalable React Apps/8-react-boilerplate-building-scalable-apps-m8-exercise-files/After/app/components/TextInput/index.js
phiratio/Pluralsight-materials
/** * * TextInput * */ import React from 'react'; import styles from './styles.css'; import classNames from 'classnames'; class TextInput extends React.Component { // eslint-disable-line react/prefer-stateless-function value() { return this.field.value; } render() { const { errorText } = this.props; const fieldError = errorText ? ( <div className={styles.errorMessage} > {errorText} </div> ) : null; return ( <div> <input className={classNames(styles.input, this.props.className, { [styles.inputError]: errorText })} placeholder={this.props.placeholder} ref={(f) => { this.field = f; }} type="text" /> {fieldError} </div> ); } } TextInput.propTypes = { errorText: React.PropTypes.string, placeholder: React.PropTypes.string, className: React.PropTypes.string, }; export default TextInput;
packages/react/src/components/CopyButton/CopyButton-story.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { action } from '@storybook/addon-actions'; import { withKnobs, number, text } from '@storybook/addon-knobs'; import CopyButton from '../CopyButton'; import mdx from './CopyButton.mdx'; const props = () => ({ feedback: text('The text shown upon clicking (feedback)', 'Copied!'), feedbackTimeout: number( 'How long the text is shown upon clicking (feedbackTimeout)', 3000 ), iconDescription: text( 'Feedback icon description (iconDescription)', 'Copy to clipboard' ), onClick: action('onClick'), }); export default { title: 'Components/CopyButton', decorators: [withKnobs], parameters: { component: CopyButton, docs: { page: mdx, }, }, }; export const _Default = () => <CopyButton />; _Default.story = { name: 'Copy Button', }; export const Playground = () => <CopyButton {...props()} />;
sites/all/modules/jquery_update/replace/jquery/1.8/jquery.min.js
renata-co/drupal
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.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%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},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(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.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(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.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(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={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,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[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","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
src/app/components/loading.js
fakelbst/my-lastfm
import React from 'react'; import CircularProgress from 'material-ui/lib/circular-progress'; const Loading = React.createClass({ render() { let containerStyle = { textAlign: 'center', paddingTop: '200px', }; return ( <div style={containerStyle}> <CircularProgress mode="indeterminate" /> </div> ) }, }); module.exports = Loading;
step7-unittest/node_modules/react-router/modules/Route.js
jintoppy/react-training
import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { component, components } from './PropTypes' const { string, func } = React.PropTypes /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ const Route = React.createClass({ statics: { createRouteFromReactElement }, propTypes: { path: string, component, components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<Route> elements are for router configuration only and should not be rendered' ) } }) export default Route
ajax/libs/react-data-grid/0.14.6/react-data-grid-with-addons.js
iwdmb/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactDataGrid"] = factory(require("react"), require("react-dom")); else root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(1); module.exports.Editors = __webpack_require__(39); module.exports.Formatters = __webpack_require__(43); module.exports.Toolbar = __webpack_require__(45); module.exports.Row = __webpack_require__(22); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var BaseGrid = __webpack_require__(4); var Row = __webpack_require__(22); var ExcelColumn = __webpack_require__(15); var KeyboardHandlerMixin = __webpack_require__(25); var CheckboxEditor = __webpack_require__(34); var FilterableHeaderCell = __webpack_require__(35); var DOMMetrics = __webpack_require__(32); var ColumnMetricsMixin = __webpack_require__(36); var RowUtils = __webpack_require__(38); var ColumnUtils = __webpack_require__(10); if (!Object.assign) { Object.assign = __webpack_require__(37); } var ReactDataGrid = React.createClass({ displayName: 'ReactDataGrid', mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin], propTypes: { rowHeight: React.PropTypes.number.isRequired, headerRowHeight: React.PropTypes.number, minHeight: React.PropTypes.number.isRequired, minWidth: React.PropTypes.number, enableRowSelect: React.PropTypes.bool, onRowUpdated: React.PropTypes.func, rowGetter: React.PropTypes.func.isRequired, rowsCount: React.PropTypes.number.isRequired, toolbar: React.PropTypes.element, enableCellSelect: React.PropTypes.bool, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, onFilter: React.PropTypes.func, onCellCopyPaste: React.PropTypes.func, onCellsDragged: React.PropTypes.func, onAddFilter: React.PropTypes.func, onGridSort: React.PropTypes.func, onDragHandleDoubleClick: React.PropTypes.func, onRowSelect: React.PropTypes.func, rowKey: React.PropTypes.string }, getDefaultProps: function getDefaultProps() { return { enableCellSelect: false, tabIndex: -1, rowHeight: 35, enableRowSelect: false, minHeight: 350, rowKey: 'id' }; }, getInitialState: function getInitialState() { var columnMetrics = this.createColumnMetrics(); var initialState = { columnMetrics: columnMetrics, selectedRows: [], copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0 }; if (this.props.enableCellSelect) { initialState.selected = { rowIdx: 0, idx: 0 }; } else { initialState.selected = { rowIdx: -1, idx: -1 }; } return initialState; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount === this.props.rowsCount + 1) { this.onAfterAddRow(nextProps.rowsCount + 1); } }, onSelect: function onSelect(selected) { if (this.props.enableCellSelect) { if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) { var _idx = selected.idx; var _rowIdx = selected.rowIdx; if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) { this.setState({ selected: selected }); } } } }, onCellClick: function onCellClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); }, onCellDoubleClick: function onCellDoubleClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); this.setActive('Enter'); }, onViewportDoubleClick: function onViewportDoubleClick() { this.setActive(); }, onPressArrowUp: function onPressArrowUp(e) { this.moveSelectedCell(e, -1, 0); }, onPressArrowDown: function onPressArrowDown(e) { this.moveSelectedCell(e, 1, 0); }, onPressArrowLeft: function onPressArrowLeft(e) { this.moveSelectedCell(e, 0, -1); }, onPressArrowRight: function onPressArrowRight(e) { this.moveSelectedCell(e, 0, 1); }, onPressTab: function onPressTab(e) { this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1); }, onPressEnter: function onPressEnter(e) { this.setActive(e.key); }, onPressDelete: function onPressDelete(e) { this.setActive(e.key); }, onPressEscape: function onPressEscape(e) { this.setInactive(e.key); }, onPressBackspace: function onPressBackspace(e) { this.setActive(e.key); }, onPressChar: function onPressChar(e) { if (this.isKeyPrintable(e.keyCode)) { this.setActive(e.keyCode); } }, onPressKeyWithCtrl: function onPressKeyWithCtrl(e) { var keys = { KeyCode_c: 99, KeyCode_C: 67, KeyCode_V: 86, KeyCode_v: 118 }; var idx = this.state.selected.idx; if (this.canEdit(idx)) { if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) { var _value = this.getSelectedValue(); this.handleCopy({ value: _value }); } else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) { this.handlePaste(); } } }, onCellCommit: function onCellCommit(commit) { var selected = Object.assign({}, this.state.selected); selected.active = false; if (commit.key === 'Tab') { selected.idx += 1; } var expandedRows = this.state.expandedRows; // if(commit.changed && commit.changed.expandedHeight){ // expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight); // } this.setState({ selected: selected, expandedRows: expandedRows }); this.props.onRowUpdated(commit); }, onDragStart: function onDragStart(e) { var value = this.getSelectedValue(); this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: value }); // need to set dummy data for FF if (e && e.dataTransfer) { if (e.dataTransfer.setData) { e.dataTransfer.dropEffect = 'move'; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', 'dummy'); } } }, onAfterAddRow: function onAfterAddRow(numberOfRows) { this.setState({ selected: { idx: 1, rowIdx: numberOfRows - 2 } }); }, onToggleFilter: function onToggleFilter() { this.setState({ canFilter: !this.state.canFilter }); }, onDragHandleDoubleClick: function onDragHandleDoubleClick(e) { if (this.props.onDragHandleDoubleClick) { this.props.onDragHandleDoubleClick(e); } }, handleDragStart: function handleDragStart(dragged) { if (!this.dragEnabled()) { return; } var idx = dragged.idx; var rowIdx = dragged.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) { this.setState({ dragged: dragged }); } }, handleDragEnd: function handleDragEnd() { if (!this.dragEnabled()) { return; } var fromRow = undefined; var toRow = undefined; var selected = this.state.selected; var dragged = this.state.dragged; var cellKey = this.getColumn(this.state.selected.idx).key; fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; if (this.props.onCellsDragged) { this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value }); } this.setState({ dragged: { complete: true } }); }, handleDragEnter: function handleDragEnter(row) { if (!this.dragEnabled()) { return; } var dragged = this.state.dragged; dragged.overRowIdx = row; this.setState({ dragged: dragged }); }, handleTerminateDrag: function handleTerminateDrag() { if (!this.dragEnabled()) { return; } this.setState({ dragged: null }); }, handlePaste: function handlePaste() { if (!this.copyPasteEnabled()) { return; } var selected = this.state.selected; var cellKey = this.getColumn(this.state.selected.idx).key; if (this.props.onCellCopyPaste) { this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: selected.rowIdx, value: this.state.textToCopy, fromRow: this.state.copied.rowIdx, toRow: selected.rowIdx }); } this.setState({ copied: null }); }, handleCopy: function handleCopy(args) { if (!this.copyPasteEnabled()) { return; } var textToCopy = args.value; var selected = this.state.selected; var copied = { idx: selected.idx, rowIdx: selected.rowIdx }; this.setState({ textToCopy: textToCopy, copied: copied }); }, handleSort: function handleSort(columnKey, direction) { this.setState({ sortDirection: direction, sortColumn: columnKey }, function () { this.props.onGridSort(columnKey, direction); }); }, getSelectedRow: function getSelectedRow(rows, key) { var _this = this; var selectedRow = rows.filter(function (r) { if (r[_this.props.rowKey] === key) { return true; } return false; }); if (selectedRow.length > 0) { return selectedRow[0]; } }, // columnKey not used here as this function will select the whole row, // but needed to match the function signature in the CheckboxEditor handleRowSelect: function handleRowSelect(rowIdx, columnKey, rowData, e) { e.stopPropagation(); var selectedRows = this.props.enableRowSelect === 'single' ? [] : this.state.selectedRows.slice(0); var selectedRow = this.getSelectedRow(selectedRows, rowData[this.props.rowKey]); if (selectedRow) { selectedRow.isSelected = !selectedRow.isSelected; } else { rowData.isSelected = true; selectedRows.push(rowData); } this.setState({ selectedRows: selectedRows }); if (this.props.onRowSelect) { this.props.onRowSelect(selectedRows.filter(function (r) { return r.isSelected === true; })); } }, handleCheckboxChange: function handleCheckboxChange(e) { var allRowsSelected = undefined; if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) { allRowsSelected = true; } else { allRowsSelected = false; } var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { var row = Object.assign({}, this.props.rowGetter(i), { isSelected: allRowsSelected }); selectedRows.push(row); } this.setState({ selectedRows: selectedRows }); if (typeof this.props.onRowSelect === 'function') { this.props.onRowSelect(selectedRows.filter(function (r) { return r.isSelected === true; })); } }, getScrollOffSet: function getScrollOffSet() { var scrollOffset = 0; var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas'); if (canvas) { scrollOffset = canvas.offsetWidth - canvas.clientWidth; } this.setState({ scrollOffset: scrollOffset }); }, getRowOffsetHeight: function getRowOffsetHeight() { var offsetHeight = 0; this.getHeaderRows().forEach(function (row) { return offsetHeight += parseFloat(row.height, 10); }); return offsetHeight; }, getHeaderRows: function getHeaderRows() { var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight }]; if (this.state.canFilter === true) { rows.push({ ref: 'filterRow', headerCellRenderer: React.createElement(FilterableHeaderCell, { onChange: this.props.onAddFilter }), height: 45 }); } return rows; }, getInitialSelectedRows: function getInitialSelectedRows() { var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(false); } return selectedRows; }, getSelectedValue: function getSelectedValue() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; var cellKey = this.getColumn(idx).key; var row = this.props.rowGetter(rowIdx); return RowUtils.get(row, cellKey); }, moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) { // we need to prevent default as we control grid scroll // otherwise it moves every time you left/right which is janky e.preventDefault(); var rowIdx = this.state.selected.rowIdx + rowDelta; var idx = this.state.selected.idx + cellDelta; this.onSelect({ idx: idx, rowIdx: rowIdx }); }, setActive: function setActive(keyPressed) { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && !this.isActive()) { var _selected = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed }); this.setState({ selected: _selected }); } }, setInactive: function setInactive() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && this.isActive()) { var _selected2 = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false }); this.setState({ selected: _selected2 }); } }, canEdit: function canEdit(idx) { var col = this.getColumn(idx); return this.props.enableCellSelect === true && (col.editor != null || col.editable); }, isActive: function isActive() { return this.state.selected.active === true; }, setupGridColumns: function setupGridColumns() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var cols = props.columns.slice(0); var unshiftedCols = {}; if (props.enableRowSelect) { var headerRenderer = props.enableRowSelect === 'single' ? null : React.createElement('input', { type: 'checkbox', onChange: this.handleCheckboxChange }); var selectColumn = { key: 'select-row', name: '', formatter: React.createElement(CheckboxEditor, null), onCellChange: this.handleRowSelect, filterable: false, headerRenderer: headerRenderer, width: 60, locked: true, getRowMetaData: function getRowMetaData(rowData) { return rowData; } }; unshiftedCols = cols.unshift(selectColumn); cols = unshiftedCols > 0 ? cols : unshiftedCols; } return cols; }, copyPasteEnabled: function copyPasteEnabled() { return this.props.onCellCopyPaste !== null; }, dragEnabled: function dragEnabled() { return this.props.onCellsDragged !== null; }, renderToolbar: function renderToolbar() { var Toolbar = this.props.toolbar; if (React.isValidElement(Toolbar)) { return React.cloneElement(Toolbar, { onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount }); } }, render: function render() { var cellMetaData = { selected: this.state.selected, dragged: this.state.dragged, onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCommit: this.onCellCommit, onCommitCancel: this.setInactive, copied: this.state.copied, handleDragEnterRow: this.handleDragEnter, handleTerminateDrag: this.handleTerminateDrag, onDragHandleDoubleClick: this.onDragHandleDoubleClick }; var toolbar = this.renderToolbar(); var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth(); var gridWidth = containerWidth - this.state.scrollOffset; // depending on the current lifecycle stage, gridWidth() may not initialize correctly // this also handles cases where it always returns undefined -- such as when inside a div with display:none // eg Bootstrap tabs and collapses if (typeof containerWidth === 'undefined' || isNaN(containerWidth)) { containerWidth = '100%'; } if (typeof gridWidth === 'undefined' || isNaN(gridWidth)) { gridWidth = '100%'; } return React.createElement( 'div', { className: 'react-grid-Container', style: { width: containerWidth } }, toolbar, React.createElement( 'div', { className: 'react-grid-Main' }, React.createElement(BaseGrid, _extends({ ref: 'base' }, this.props, { rowKey: this.props.rowKey, headerRows: this.getHeaderRows(), columnMetrics: this.state.columnMetrics, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, rowHeight: this.props.rowHeight, cellMetaData: cellMetaData, selectedRows: this.state.selectedRows.filter(function (r) { return r.isSelected === true; }), expandedRows: this.state.expandedRows, rowOffsetHeight: this.getRowOffsetHeight(), sortColumn: this.state.sortColumn, sortDirection: this.state.sortDirection, onSort: this.handleSort, minHeight: this.props.minHeight, totalWidth: gridWidth, onViewportKeydown: this.onKeyDown, onViewportDragStart: this.onDragStart, onViewportDragEnd: this.handleDragEnd, onViewportDoubleClick: this.onViewportDoubleClick, onColumnResize: this.onColumnResize })) ) ); } }); module.exports = ReactDataGrid; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var PropTypes = React.PropTypes; var Header = __webpack_require__(5); var Viewport = __webpack_require__(19); var GridScrollMixin = __webpack_require__(33); var DOMMetrics = __webpack_require__(32); var cellMetaDataShape = __webpack_require__(29); var Grid = React.createClass({ displayName: 'Grid', propTypes: { rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), columnMetrics: PropTypes.object, minHeight: PropTypes.number, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowHeight: PropTypes.number, rowRenderer: PropTypes.func, emptyRowsView: PropTypes.func, expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowsCount: PropTypes.number, onRows: PropTypes.func, sortColumn: React.PropTypes.string, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']), rowOffsetHeight: PropTypes.number.isRequired, onViewportKeydown: PropTypes.func.isRequired, onViewportDragStart: PropTypes.func.isRequired, onViewportDragEnd: PropTypes.func.isRequired, onViewportDoubleClick: PropTypes.func.isRequired, onColumnResize: PropTypes.func, onSort: PropTypes.func, cellMetaData: PropTypes.shape(cellMetaDataShape), rowKey: PropTypes.string.isRequired }, mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin], getDefaultProps: function getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; }, getStyle: function getStyle() { return { overflow: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight }; }, render: function render() { var headerRows = this.props.headerRows || [{ ref: 'row' }]; var EmptyRowsView = this.props.emptyRowsView; return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }), React.createElement(Header, { ref: 'header', columnMetrics: this.props.columnMetrics, onColumnResize: this.props.onColumnResize, height: this.props.rowHeight, totalWidth: this.props.totalWidth, headerRows: headerRows, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort }), this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement( 'div', { ref: 'viewPortContainer', onKeyDown: this.props.onViewportKeydown, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd }, React.createElement(Viewport, { ref: 'viewport', rowKey: this.props.rowKey, width: this.props.columnMetrics.width, rowHeight: this.props.rowHeight, rowRenderer: this.props.rowRenderer, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columnMetrics: this.props.columnMetrics, totalWidth: this.props.totalWidth, onScroll: this.onScroll, onRows: this.props.onRows, cellMetaData: this.props.cellMetaData, rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length, minHeight: this.props.minHeight }) ) : React.createElement( 'div', { ref: 'emptyView', className: 'react-grid-Empty' }, React.createElement(EmptyRowsView, null) ) ); } }); module.exports = Grid; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var shallowCloneObject = __webpack_require__(7); var ColumnMetrics = __webpack_require__(8); var ColumnUtils = __webpack_require__(10); var HeaderRow = __webpack_require__(12); var PropTypes = React.PropTypes; var Header = React.createClass({ displayName: 'Header', propTypes: { columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, headerRows: PropTypes.array.isRequired, sortColumn: PropTypes.string, sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']), onSort: PropTypes.func, onColumnResize: PropTypes.func }, getInitialState: function getInitialState() { return { resizing: null }; }, componentWillReceiveProps: function componentWillReceiveProps() { this.setState({ resizing: null }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection; return update; }, onColumnResize: function onColumnResize(column, width) { var state = this.state.resizing || this.props; var pos = this.getColumnPosition(column); if (pos != null) { var _resizing = { columnMetrics: shallowCloneObject(state.columnMetrics) }; _resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width); // we don't want to influence scrollLeft while resizing if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) { _resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth; } _resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos); this.setState({ resizing: _resizing }); } }, onColumnResizeEnd: function onColumnResizeEnd(column, width) { var pos = this.getColumnPosition(column); if (pos !== null && this.props.onColumnResize) { this.props.onColumnResize(pos, width || column.width); } }, getHeaderRows: function getHeaderRows() { var _this = this; var columnMetrics = this.getColumnMetrics(); var resizeColumn = undefined; if (this.state.resizing) { resizeColumn = this.state.resizing.column; } var headerRows = []; this.props.headerRows.forEach(function (row, index) { var headerRowStyle = { position: 'absolute', top: _this.getCombinedHeaderHeights(index), left: 0, width: _this.props.totalWidth, overflow: 'hidden' }; headerRows.push(React.createElement(HeaderRow, { key: row.ref, ref: row.ref, style: headerRowStyle, onColumnResize: _this.onColumnResize, onColumnResizeEnd: _this.onColumnResizeEnd, width: columnMetrics.width, height: row.height || _this.props.height, columns: columnMetrics.columns, resizing: resizeColumn, headerCellRenderer: row.headerCellRenderer, sortColumn: _this.props.sortColumn, sortDirection: _this.props.sortDirection, onSort: _this.props.onSort })); }); return headerRows; }, getColumnMetrics: function getColumnMetrics() { var columnMetrics = undefined; if (this.state.resizing) { columnMetrics = this.state.resizing.columnMetrics; } else { columnMetrics = this.props.columnMetrics; } return columnMetrics; }, getColumnPosition: function getColumnPosition(column) { var columnMetrics = this.getColumnMetrics(); var pos = -1; columnMetrics.columns.forEach(function (c, idx) { if (c.key === column.key) { pos = idx; } }); return pos === -1 ? null : pos; }, getCombinedHeaderHeights: function getCombinedHeaderHeights(until) { var stopAt = this.props.headerRows.length; if (typeof until !== 'undefined') { stopAt = until; } var height = 0; for (var index = 0; index < stopAt; index++) { height += this.props.headerRows[index].height || this.props.height; } return height; }, getStyle: function getStyle() { return { position: 'relative', height: this.getCombinedHeaderHeights(), overflow: 'hidden' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = ReactDOM.findDOMNode(this.refs.row); node.scrollLeft = scrollLeft; this.refs.row.setScrollLeft(scrollLeft); if (this.refs.filterRow) { var nodeFilters = ReactDOM.findDOMNode(this.refs.filterRow); nodeFilters.scrollLeft = scrollLeft; this.refs.filterRow.setScrollLeft(scrollLeft); } }, render: function render() { var className = joinClasses({ 'react-grid-Header': true, 'react-grid-Header--resizing': !!this.state.resizing }); var headerRows = this.getHeaderRows(); return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: className }), headerRows ); } }); module.exports = Header; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 7 */ /***/ function(module, exports) { "use strict"; function shallowCloneObject(obj) { var result = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } return result; } module.exports = shallowCloneObject; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var shallowCloneObject = __webpack_require__(7); var sameColumn = __webpack_require__(9); var ColumnUtils = __webpack_require__(10); var getScrollbarSize = __webpack_require__(11); function setColumnWidths(columns, totalWidth) { return columns.map(function (column) { var colInfo = Object.assign({}, column); if (column.width) { if (/^([0-9]+)%$/.exec(column.width.toString())) { colInfo.width = Math.floor(column.width / 100 * totalWidth); } } return colInfo; }); } function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) { var defferedColumns = columns.filter(function (c) { return !c.width; }); return columns.map(function (column) { if (!column.width) { if (unallocatedWidth <= 0) { column.width = minColumnWidth; } else { column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns)); } } return column; }); } function setColumnOffsets(columns) { var left = 0; return columns.map(function (column) { column.left = left; left += column.width; return column; }); } /** * Update column metrics calculation. * * @param {ColumnMetricsType} metrics */ function recalculate(metrics) { // compute width for columns which specify width var columns = setColumnWidths(metrics.columns, metrics.totalWidth); var unallocatedWidth = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w - column.width; }, metrics.totalWidth); unallocatedWidth -= getScrollbarSize(); var width = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w + column.width; }, 0); // compute width for columns which doesn't specify width columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth); // compute left offset columns = setColumnOffsets(columns); return { columns: columns, width: width, totalWidth: metrics.totalWidth, minColumnWidth: metrics.minColumnWidth }; } /** * Update column metrics calculation by resizing a column. * * @param {ColumnMetricsType} metrics * @param {Column} column * @param {number} width */ function resizeColumn(metrics, index, width) { var column = ColumnUtils.getColumn(metrics.columns, index); var metricsClone = shallowCloneObject(metrics); metricsClone.columns = metrics.columns.slice(0); var updatedColumn = shallowCloneObject(column); updatedColumn.width = Math.max(width, metricsClone.minColumnWidth); metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn); return recalculate(metricsClone); } function areColumnsImmutable(prevColumns, nextColumns) { return typeof Immutable !== 'undefined' && prevColumns instanceof Immutable.List && nextColumns instanceof Immutable.List; } function compareEachColumn(prevColumns, nextColumns, isSameColumn) { var i = undefined; var len = undefined; var column = undefined; var prevColumnsByKey = {}; var nextColumnsByKey = {}; if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) { return false; } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; prevColumnsByKey[column.key] = column; } for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) { column = nextColumns[i]; nextColumnsByKey[column.key] = column; var prevColumn = prevColumnsByKey[column.key]; if (prevColumn === undefined || !isSameColumn(prevColumn, column)) { return false; } } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; var nextColumn = nextColumnsByKey[column.key]; if (nextColumn === undefined) { return false; } } return true; } function sameColumns(prevColumns, nextColumns, isSameColumn) { if (areColumnsImmutable(prevColumns, nextColumns)) { return prevColumns === nextColumns; } return compareEachColumn(prevColumns, nextColumns, isSameColumn); } module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isValidElement = __webpack_require__(2).isValidElement; module.exports = function sameColumn(a, b) { var k = undefined; for (k in a) { if (a.hasOwnProperty(k)) { if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) { continue; } if (!b.hasOwnProperty(k) || a[k] !== b[k]) { return false; } } } for (k in b) { if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) { return false; } } return true; }; /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; module.exports = { getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, spliceColumn: function spliceColumn(metrics, idx, column) { if (Array.isArray(metrics.columns)) { metrics.columns.splice(idx, 1, column); } else if (typeof Immutable !== 'undefined') { metrics.columns = metrics.columns.splice(idx, 1, column); } return metrics; }, getSize: function getSize(columns) { if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } } }; /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict'; var size = undefined; function getScrollbarSize() { if (size === undefined) { var outer = document.createElement('div'); outer.style.width = '50px'; outer.style.height = '50px'; outer.style.position = 'absolute'; outer.style.top = '-200px'; outer.style.left = '-200px'; var inner = document.createElement('div'); inner.style.height = '100px'; inner.style.width = '100%'; outer.appendChild(inner); document.body.appendChild(outer); var outerWidth = outer.clientWidth; outer.style.overflowY = 'scroll'; var innerWidth = inner.clientWidth; document.body.removeChild(outer); size = outerWidth - innerWidth; } return size; } module.exports = getScrollbarSize; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var shallowEqual = __webpack_require__(13); var HeaderCell = __webpack_require__(14); var getScrollbarSize = __webpack_require__(11); var ExcelColumn = __webpack_require__(15); var ColumnUtilsMixin = __webpack_require__(10); var SortableHeaderCell = __webpack_require__(18); var PropTypes = React.PropTypes; var HeaderRowStyle = { overflow: React.PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: React.PropTypes.number, position: React.PropTypes.string }; var DEFINE_SORT = ['ASC', 'DESC', 'NONE']; var HeaderRow = React.createClass({ displayName: 'HeaderRow', propTypes: { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), onColumnResize: PropTypes.func, onSort: PropTypes.func.isRequired, onColumnResizeEnd: PropTypes.func, style: PropTypes.shape(HeaderRowStyle), sortColumn: PropTypes.string, sortDirection: React.PropTypes.oneOf(DEFINE_SORT), cellRenderer: PropTypes.func, headerCellRenderer: PropTypes.func, resizing: PropTypes.func }, mixins: [ColumnUtilsMixin], shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection; }, getHeaderRenderer: function getHeaderRenderer(column) { if (column.sortable) { var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE; return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection }); } return this.props.headerCellRenderer || column.headerRenderer || this.props.cellRenderer; }, getStyle: function getStyle() { return { overflow: 'hidden', width: '100%', height: this.props.height, position: 'absolute' }; }, getCells: function getCells() { var cells = []; var lockedCells = []; for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) { var column = this.getColumn(this.props.columns, i); var cell = React.createElement(HeaderCell, { ref: i, key: i, height: this.props.height, column: column, renderer: this.getHeaderRenderer(column), resizing: this.props.resizing === column, onResize: this.props.onColumnResize, onResizeEnd: this.props.onColumnResizeEnd }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } } return cells.concat(lockedCells); }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this = this; this.props.columns.forEach(function (column, i) { if (column.locked) { _this.refs[i].setScrollLeft(scrollLeft); } }); }, render: function render() { var cellsStyle = { width: this.props.width ? this.props.width + getScrollbarSize() : '100%', height: this.props.height, whiteSpace: 'nowrap', overflowX: 'hidden', overflowY: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: 'react-grid-HeaderRow' }), React.createElement( 'div', { style: cellsStyle }, cells ) ); } }); module.exports = HeaderRow; /***/ }, /* 13 */ /***/ function(module, exports) { /** * 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 shallowEqual * @typechecks * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var ExcelColumn = __webpack_require__(15); var ResizeHandle = __webpack_require__(16); var PropTypes = React.PropTypes; function simpleCellRenderer(objArgs) { return React.createElement( 'div', { className: 'widget-HeaderCell__value' }, objArgs.column.name ); } var HeaderCell = React.createClass({ displayName: 'HeaderCell', propTypes: { renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired, column: PropTypes.shape(ExcelColumn).isRequired, onResize: PropTypes.func.isRequired, height: PropTypes.number.isRequired, onResizeEnd: PropTypes.func.isRequired, className: PropTypes.string }, getDefaultProps: function getDefaultProps() { return { renderer: simpleCellRenderer }; }, getInitialState: function getInitialState() { return { resizing: false }; }, onDragStart: function onDragStart(e) { this.setState({ resizing: true }); // need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onDrag: function onDrag(e) { var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct if (resize) { var _width = this.getWidthFromMouseEvent(e); if (_width > 0) { resize(this.props.column, _width); } } }, onDragEnd: function onDragEnd(e) { var width = this.getWidthFromMouseEvent(e); this.props.onResizeEnd(this.props.column, width); this.setState({ resizing: false }); }, getWidthFromMouseEvent: function getWidthFromMouseEvent(e) { var right = e.pageX; var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left; return right - left; }, getCell: function getCell() { if (React.isValidElement(this.props.renderer)) { return React.cloneElement(this.props.renderer, { column: this.props.column }); } return this.props.renderer({ column: this.props.column }); }, getStyle: function getStyle() { return { width: this.props.column.width, left: this.props.column.left, display: 'inline-block', position: 'absolute', overflow: 'hidden', height: this.props.height, margin: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = ReactDOM.findDOMNode(this); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }, render: function render() { var resizeHandle = undefined; if (this.props.column.resizable) { resizeHandle = React.createElement(ResizeHandle, { onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd }); } var className = joinClasses({ 'react-grid-HeaderCell': true, 'react-grid-HeaderCell--resizing': this.state.resizing, 'react-grid-HeaderCell--locked': this.props.column.locked }); className = joinClasses(className, this.props.className, this.props.column.cellClass); var cell = this.getCell(); return React.createElement( 'div', { className: className, style: this.getStyle() }, cell, resizeHandle ); } }); module.exports = HeaderCell; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ExcelColumnShape = { name: React.PropTypes.string.isRequired, key: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired }; module.exports = ExcelColumnShape; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var Draggable = __webpack_require__(17); var ResizeHandle = React.createClass({ displayName: 'ResizeHandle', style: { position: 'absolute', top: 0, right: 0, width: 6, height: '100%' }, render: function render() { return React.createElement(Draggable, _extends({}, this.props, { className: 'react-grid-HeaderCell__resizeHandle', style: this.style })); } }); module.exports = ResizeHandle; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var PropTypes = React.PropTypes; var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]) }, getDefaultProps: function getDefaultProps() { return { onDragStart: function onDragStart() { return true; }, onDragEnd: function onDragEnd() {}, onDrag: function onDrag() {} }; }, getInitialState: function getInitialState() { return { drag: null }; }, componentWillUnmount: function componentWillUnmount() { this.cleanUp(); }, onMouseDown: function onMouseDown(e) { var drag = this.props.onDragStart(e); if (drag === null && e.button !== 0) { return; } window.addEventListener('mouseup', this.onMouseUp); window.addEventListener('mousemove', this.onMouseMove); this.setState({ drag: drag }); }, onMouseMove: function onMouseMove(e) { if (this.state.drag === null) { return; } if (e.preventDefault) { e.preventDefault(); } this.props.onDrag(e); }, onMouseUp: function onMouseUp(e) { this.cleanUp(); this.props.onDragEnd(e, this.state.drag); this.setState({ drag: null }); }, cleanUp: function cleanUp() { window.removeEventListener('mouseup', this.onMouseUp); window.removeEventListener('mousemove', this.onMouseMove); }, render: function render() { return React.createElement('div', _extends({}, this.props, { onMouseDown: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); } }); module.exports = Draggable; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var joinClasses = __webpack_require__(6); var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var SortableHeaderCell = React.createClass({ displayName: 'SortableHeaderCell', propTypes: { columnKey: React.PropTypes.string.isRequired, column: React.PropTypes.shape({ name: React.PropTypes.string }), onSort: React.PropTypes.func.isRequired, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']) }, onClick: function onClick() { var direction = undefined; switch (this.props.sortDirection) { default: case null: case undefined: case DEFINE_SORT.NONE: direction = DEFINE_SORT.ASC; break; case DEFINE_SORT.ASC: direction = DEFINE_SORT.DESC; break; case DEFINE_SORT.DESC: direction = DEFINE_SORT.NONE; break; } this.props.onSort(this.props.columnKey, direction); }, getSortByText: function getSortByText() { var unicodeKeys = { ASC: '9650', DESC: '9660', NONE: '' }; return String.fromCharCode(unicodeKeys[this.props.sortDirection]); }, render: function render() { var className = joinClasses({ 'react-grid-HeaderCell-sortable': true, 'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC', 'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC' }); return React.createElement( 'div', { className: className, onClick: this.onClick, style: { cursor: 'pointer' } }, this.props.column.name, React.createElement( 'span', { className: 'pull-right' }, this.getSortByText() ) ); } }); module.exports = SortableHeaderCell; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var Canvas = __webpack_require__(20); var ViewportScroll = __webpack_require__(31); var cellMetaDataShape = __webpack_require__(29); var PropTypes = React.PropTypes; var Viewport = React.createClass({ displayName: 'Viewport', mixins: [ViewportScroll], propTypes: { rowOffsetHeight: PropTypes.number.isRequired, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, columnMetrics: PropTypes.object.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, selectedRows: PropTypes.array, expandedRows: PropTypes.array, rowRenderer: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowHeight: PropTypes.number.isRequired, onRows: PropTypes.func, onScroll: PropTypes.func, minHeight: PropTypes.number, cellMetaData: PropTypes.shape(cellMetaDataShape), rowKey: PropTypes.string.isRequired }, onScroll: function onScroll(scroll) { this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount); if (this.props.onScroll) { this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft }); } }, getScroll: function getScroll() { return this.refs.canvas.getScroll(); }, setScrollLeft: function setScrollLeft(scrollLeft) { this.refs.canvas.setScrollLeft(scrollLeft); }, render: function render() { var style = { padding: 0, bottom: 0, left: 0, right: 0, overflow: 'hidden', position: 'absolute', top: this.props.rowOffsetHeight }; return React.createElement( 'div', { className: 'react-grid-Viewport', style: style }, React.createElement(Canvas, { ref: 'canvas', rowKey: this.props.rowKey, totalWidth: this.props.totalWidth, width: this.props.columnMetrics.width, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columns: this.props.columnMetrics.columns, rowRenderer: this.props.rowRenderer, visibleStart: this.state.visibleStart, visibleEnd: this.state.visibleEnd, displayStart: this.state.displayStart, displayEnd: this.state.displayEnd, cellMetaData: this.props.cellMetaData, height: this.state.height, rowHeight: this.props.rowHeight, onScroll: this.onScroll, onRows: this.props.onRows }) ); } }); module.exports = Viewport; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var PropTypes = React.PropTypes; var shallowEqual = __webpack_require__(13); var ScrollShim = __webpack_require__(21); var Row = __webpack_require__(22); var cellMetaDataShape = __webpack_require__(29); var Canvas = React.createClass({ displayName: 'Canvas', mixins: [ScrollShim], propTypes: { rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), rowHeight: PropTypes.number.isRequired, height: PropTypes.number.isRequired, width: PropTypes.number, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), style: PropTypes.string, className: PropTypes.string, displayStart: PropTypes.number.isRequired, displayEnd: PropTypes.number.isRequired, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]), expandedRows: PropTypes.array, onRows: PropTypes.func, onScroll: PropTypes.func, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired, selectedRows: PropTypes.array, rowKey: React.PropTypes.string }, getDefaultProps: function getDefaultProps() { return { rowRenderer: Row, onRows: function onRows() {}, selectedRows: [] }; }, getInitialState: function getInitialState() { return { shouldUpdate: true, displayStart: this.props.displayStart, displayEnd: this.props.displayEnd, scrollbarWidth: 0 }; }, componentWillMount: function componentWillMount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidMount: function componentDidMount() { this.onRows(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var scrollbarWidth = this.getScrollbarWidth(); var shouldUpdate = !(nextProps.visibleStart > this.state.displayStart && nextProps.visibleEnd < this.state.displayEnd) || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !shallowEqual(nextProps.style, this.props.style); if (shouldUpdate) { this.setState({ shouldUpdate: true, displayStart: nextProps.displayStart, displayEnd: nextProps.displayEnd, scrollbarWidth: scrollbarWidth }); } else { this.setState({ shouldUpdate: false, scrollbarWidth: scrollbarWidth }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !nextState || nextState.shouldUpdate; }, componentWillUnmount: function componentWillUnmount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidUpdate: function componentDidUpdate() { if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) { this.setScrollLeft(this._scroll.scrollLeft); } this.onRows(); }, onRows: function onRows() { if (this._currentRowsRange !== { start: 0, end: 0 }) { this.props.onRows(this._currentRowsRange); this._currentRowsRange = { start: 0, end: 0 }; } }, onScroll: function onScroll(e) { this.appendScrollShim(); var _e$target = e.target; var scrollTop = _e$target.scrollTop; var scrollLeft = _e$target.scrollLeft; var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft }; this._scroll = scroll; this.props.onScroll(scroll); }, getRows: function getRows(displayStart, displayEnd) { this._currentRowsRange = { start: displayStart, end: displayEnd }; if (Array.isArray(this.props.rowGetter)) { return this.props.rowGetter.slice(displayStart, displayEnd); } var rows = []; for (var i = displayStart; i < displayEnd; i++) { rows.push(this.props.rowGetter(i)); } return rows; }, getScrollbarWidth: function getScrollbarWidth() { var scrollbarWidth = 0; // Get the scrollbar width var canvas = ReactDOM.findDOMNode(this); scrollbarWidth = canvas.offsetWidth - canvas.clientWidth; return scrollbarWidth; }, getScroll: function getScroll() { var _ReactDOM$findDOMNode = ReactDOM.findDOMNode(this); var scrollTop = _ReactDOM$findDOMNode.scrollTop; var scrollLeft = _ReactDOM$findDOMNode.scrollLeft; return { scrollTop: scrollTop, scrollLeft: scrollLeft }; }, isRowSelected: function isRowSelected(row) { var _this = this; var selectedRows = this.props.selectedRows.filter(function (r) { var rowKeyValue = row.get ? row.get(_this.props.rowKey) : row[_this.props.rowKey]; return r[_this.props.rowKey] === rowKeyValue; }); return selectedRows.length > 0 && selectedRows[0].isSelected; }, _currentRowsLength: 0, _currentRowsRange: { start: 0, end: 0 }, _scroll: { scrollTop: 0, scrollLeft: 0 }, setScrollLeft: function setScrollLeft(scrollLeft) { if (this._currentRowsLength !== 0) { if (!this.refs) return; for (var i = 0, len = this._currentRowsLength; i < len; i++) { if (this.refs[i] && this.refs[i].setScrollLeft) { this.refs[i].setScrollLeft(scrollLeft); } } } }, renderRow: function renderRow(props) { var RowsRenderer = this.props.rowRenderer; if (typeof RowsRenderer === 'function') { return React.createElement(RowsRenderer, props); } if (React.isValidElement(this.props.rowRenderer)) { return React.cloneElement(this.props.rowRenderer, props); } }, renderPlaceholder: function renderPlaceholder(key, height) { return React.createElement( 'div', { key: key, style: { height: height } }, this.props.columns.map(function (column, idx) { return React.createElement('div', { style: { width: column.width }, key: idx }); }) ); }, render: function render() { var _this2 = this; var displayStart = this.state.displayStart; var displayEnd = this.state.displayEnd; var rowHeight = this.props.rowHeight; var length = this.props.rowsCount; var rows = this.getRows(displayStart, displayEnd).map(function (row, idx) { return _this2.renderRow({ key: displayStart + idx, ref: idx, idx: displayStart + idx, row: row, height: rowHeight, columns: _this2.props.columns, isSelected: _this2.isRowSelected(row), expandedRows: _this2.props.expandedRows, cellMetaData: _this2.props.cellMetaData }); }); this._currentRowsLength = rows.length; if (displayStart > 0) { rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight)); } if (length - displayEnd > 0) { rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight)); } var style = { position: 'absolute', top: 0, left: 0, overflowX: 'auto', overflowY: 'scroll', width: this.props.totalWidth, height: this.props.height, transform: 'translate3d(0, 0, 0)' }; return React.createElement( 'div', { style: style, onScroll: this.onScroll, className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) }, React.createElement( 'div', { style: { width: this.props.width, overflow: 'hidden' } }, rows ) ); } }); module.exports = Canvas; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScrollShim = { appendScrollShim: function appendScrollShim() { if (!this._scrollShim) { var size = this._scrollShimSize(); var shim = document.createElement('div'); if (shim.classList) { shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement } else { shim.className += ' react-grid-ScrollShim'; } shim.style.position = 'absolute'; shim.style.top = 0; shim.style.left = 0; shim.style.width = size.width + 'px'; shim.style.height = size.height + 'px'; _reactDom2.default.findDOMNode(this).appendChild(shim); this._scrollShim = shim; } this._scheduleRemoveScrollShim(); }, _scrollShimSize: function _scrollShimSize() { return { width: this.props.width, height: this.props.length * this.props.rowHeight }; }, _scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() { if (this._scheduleRemoveScrollShimTimer) { clearTimeout(this._scheduleRemoveScrollShimTimer); } this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200); }, _removeScrollShim: function _removeScrollShim() { if (this._scrollShim) { this._scrollShim.parentNode.removeChild(this._scrollShim); this._scrollShim = undefined; } } }; module.exports = ScrollShim; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var joinClasses = __webpack_require__(6); var Cell = __webpack_require__(23); var ColumnMetrics = __webpack_require__(8); var ColumnUtilsMixin = __webpack_require__(10); var cellMetaDataShape = __webpack_require__(29); var PropTypes = React.PropTypes; var Row = React.createClass({ displayName: 'Row', propTypes: { height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, row: PropTypes.any.isRequired, cellRenderer: PropTypes.func, cellMetaData: PropTypes.shape(cellMetaDataShape), isSelected: PropTypes.bool, idx: PropTypes.number.isRequired, key: PropTypes.string, expandedRows: PropTypes.arrayOf(PropTypes.object) }, mixins: [ColumnUtilsMixin], getDefaultProps: function getDefaultProps() { return { cellRenderer: Cell, isSelected: false, height: 35 }; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height; }, handleDragEnter: function handleDragEnter() { var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow; if (handleDragEnterRow) { handleDragEnterRow(this.props.idx); } }, getSelectedColumn: function getSelectedColumn() { var selected = this.props.cellMetaData.selected; if (selected && selected.idx) { return this.getColumn(this.props.columns, selected.idx); } }, getCells: function getCells() { var _this = this; var cells = []; var lockedCells = []; var selectedColumn = this.getSelectedColumn(); this.props.columns.forEach(function (column, i) { var CellRenderer = _this.props.cellRenderer; var cell = React.createElement(CellRenderer, { ref: i, key: column.key + '-' + i, idx: i, rowIdx: _this.props.idx, value: _this.getCellValue(column.key || i), column: column, height: _this.getRowHeight(), formatter: column.formatter, cellMetaData: _this.props.cellMetaData, rowData: _this.props.row, selectedColumn: selectedColumn, isRowSelected: _this.props.isSelected }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } }); return cells.concat(lockedCells); }, getRowHeight: function getRowHeight() { var rows = this.props.expandedRows || null; if (rows && this.props.key) { var row = rows[this.props.key] || null; if (row) { return row.height; } } return this.props.height; }, getCellValue: function getCellValue(key) { var val = undefined; if (key === 'select-row') { return this.props.isSelected; } else if (typeof this.props.row.get === 'function') { val = this.props.row.get(key); } else { val = this.props.row[key]; } return val; }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this2 = this; this.props.columns.forEach(function (column, i) { if (column.locked) { if (!_this2.refs[i]) return; _this2.refs[i].setScrollLeft(scrollLeft); } }); }, doesRowContainSelectedCell: function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } return false; }, willRowBeDraggedOver: function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); }, hasRowBeenCopied: function hasRowBeenCopied() { var copied = this.props.cellMetaData.copied; return copied != null && copied.rowIdx === this.props.idx; }, renderCell: function renderCell(props) { if (typeof this.props.cellRenderer === 'function') { this.props.cellRenderer.call(this, props); } if (React.isValidElement(this.props.cellRenderer)) { return React.cloneElement(this.props.cellRenderer, props); } return this.props.cellRenderer(props); }, render: function render() { var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd'), { 'row-selected': this.props.isSelected }); var style = { height: this.getRowHeight(this.props), overflow: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }), React.isValidElement(this.props.row) ? this.props.row : cells ); } }); module.exports = Row; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var EditorContainer = __webpack_require__(24); var ExcelColumn = __webpack_require__(15); var isFunction = __webpack_require__(28); var CellMetaDataShape = __webpack_require__(29); var SimpleCellFormatter = __webpack_require__(30); var Cell = React.createClass({ displayName: 'Cell', propTypes: { rowIdx: React.PropTypes.number.isRequired, idx: React.PropTypes.number.isRequired, selected: React.PropTypes.shape({ idx: React.PropTypes.number.isRequired }), selectedColumn: React.PropTypes.object, height: React.PropTypes.number, tabIndex: React.PropTypes.number, ref: React.PropTypes.string, column: React.PropTypes.shape(ExcelColumn).isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, isExpanded: React.PropTypes.bool, isRowSelected: React.PropTypes.bool, cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired, handleDragStart: React.PropTypes.func, className: React.PropTypes.string, cellControls: React.PropTypes.any, rowData: React.PropTypes.object.isRequired }, getDefaultProps: function getDefaultProps() { return { tabIndex: -1, ref: 'cell', isExpanded: false }; }, getInitialState: function getInitialState() { return { isRowChanging: false, isCellValueChanging: false }; }, componentDidMount: function componentDidMount() { this.checkFocus(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ isRowChanging: this.props.rowData !== nextProps.rowData, isCellValueChanging: this.props.value !== nextProps.value }); }, componentDidUpdate: function componentDidUpdate() { this.checkFocus(); var dragged = this.props.cellMetaData.dragged; if (dragged && dragged.complete === true) { this.props.cellMetaData.handleTerminateDrag(); } if (this.state.isRowChanging && this.props.selectedColumn != null) { this.applyUpdateClass(); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.rowData !== nextProps.rowData || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected(); }, onCellClick: function onCellClick() { var meta = this.props.cellMetaData; if (meta != null && meta.onCellClick != null) { meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onCellDoubleClick: function onCellDoubleClick() { var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onDragHandleDoubleClick: function onDragHandleDoubleClick(e) { e.stopPropagation(); var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onDragHandleDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.getRowData() }); } }, onDragOver: function onDragOver(e) { e.preventDefault(); }, getStyle: function getStyle() { var style = { position: 'absolute', width: this.props.column.width, height: this.props.height, left: this.props.column.left }; return style; }, getFormatter: function getFormatter() { var col = this.props.column; if (this.isActive()) { return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height }); } return this.props.column.formatter; }, getRowData: function getRowData() { return this.props.rowData.toJSON ? this.props.rowData.toJSON() : this.props.rowData; }, getFormatterDependencies: function getFormatterDependencies() { // convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.getRowData(), this.props.column); } }, getCellClass: function getCellClass() { var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null); var extraClasses = joinClasses({ 'row-selected': this.props.isRowSelected, selected: this.isSelected() && !this.isActive(), editing: this.isActive(), copied: this.isCopied() || this.wasDraggedOver() || this.isDraggedOverUpwards() || this.isDraggedOverDownwards(), 'active-drag-cell': this.isSelected() || this.isDraggedOver(), 'is-dragged-over-up': this.isDraggedOverUpwards(), 'is-dragged-over-down': this.isDraggedOverDownwards(), 'was-dragged-over': this.wasDraggedOver() }); return joinClasses(className, extraClasses); }, getUpdateCellClass: function getUpdateCellClass() { return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : ''; }, isColumnSelected: function isColumnSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.idx === this.props.idx; }, isSelected: function isSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx; }, isActive: function isActive() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return this.isSelected() && meta.selected.active === true; }, isCellSelectionChanging: function isCellSelectionChanging(nextProps) { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } var nextSelected = nextProps.cellMetaData.selected; if (meta.selected && nextSelected) { return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx; } return true; }, applyUpdateClass: function applyUpdateClass() { var updateCellClass = this.getUpdateCellClass(); // -> removing the class if (updateCellClass != null && updateCellClass !== '') { var cellDOMNode = ReactDOM.findDOMNode(this); if (cellDOMNode.classList) { cellDOMNode.classList.remove(updateCellClass); // -> and re-adding the class cellDOMNode.classList.add(updateCellClass); } else if (cellDOMNode.className.indexOf(updateCellClass) === -1) { // IE9 doesn't support classList, nor (I think) altering element.className // without replacing it wholesale. cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass; } } }, setScrollLeft: function setScrollLeft(scrollLeft) { var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this if (ctrl.isMounted()) { var node = ReactDOM.findDOMNode(this); var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.webkitTransform = transform; node.style.transform = transform; } }, isCopied: function isCopied() { var copied = this.props.cellMetaData.copied; return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx; }, isDraggedOver: function isDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx; }, wasDraggedOver: function wasDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx; }, isDraggedCellChanging: function isDraggedCellChanging(nextProps) { var isChanging = undefined; var dragged = this.props.cellMetaData.dragged; var nextDragged = nextProps.cellMetaData.dragged; if (dragged) { isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx; return isChanging; } return false; }, isCopyCellChanging: function isCopyCellChanging(nextProps) { var isChanging = undefined; var copied = this.props.cellMetaData.copied; var nextCopied = nextProps.cellMetaData.copied; if (copied) { isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx; return isChanging; } return false; }, isDraggedOverUpwards: function isDraggedOverUpwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx; }, isDraggedOverDownwards: function isDraggedOverDownwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx; }, checkFocus: function checkFocus() { if (this.isSelected() && !this.isActive()) { ReactDOM.findDOMNode(this).focus(); } }, canEdit: function canEdit() { return this.props.column.editor != null || this.props.column.editable; }, renderCellContent: function renderCellContent(props) { var CellContent = undefined; var Formatter = this.getFormatter(); if (React.isValidElement(Formatter)) { props.dependentValues = this.getFormatterDependencies(); CellContent = React.cloneElement(Formatter, props); } else if (isFunction(Formatter)) { CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() }); } else { CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value }); } return React.createElement( 'div', { ref: 'cell', className: 'react-grid-Cell__value' }, CellContent, ' ', this.props.cellControls ); }, render: function render() { var style = this.getStyle(); var className = this.getCellClass(); var cellContent = this.renderCellContent({ value: this.props.value, column: this.props.column, rowIdx: this.props.rowIdx, isExpanded: this.props.isExpanded }); var dragHandle = !this.isActive() && this.canEdit() ? React.createElement( 'div', { className: 'drag-handle', draggable: 'true', onDoubleClick: this.onDragHandleDoubleClick }, React.createElement('span', { style: { display: 'none' } }) ) : null; return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onClick: this.onCellClick, onDoubleClick: this.onCellDoubleClick, onDragOver: this.onDragOver }), cellContent, dragHandle ); } }); module.exports = Cell; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var joinClasses = __webpack_require__(6); var keyboardHandlerMixin = __webpack_require__(25); var SimpleTextEditor = __webpack_require__(26); var isFunction = __webpack_require__(28); var EditorContainer = React.createClass({ displayName: 'EditorContainer', mixins: [keyboardHandlerMixin], propTypes: { rowIdx: React.PropTypes.number, rowData: React.PropTypes.object.isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, cellMetaData: React.PropTypes.shape({ selected: React.PropTypes.object.isRequired, copied: React.PropTypes.object, dragged: React.PropTypes.object, onCellClick: React.PropTypes.func, onCellDoubleClick: React.PropTypes.func, onCommitCancel: React.PropTypes.func, onCommit: React.PropTypes.func }).isRequired, column: React.PropTypes.object.isRequired, height: React.PropTypes.number.isRequired }, changeCommitted: false, getInitialState: function getInitialState() { return { isInvalid: false }; }, componentDidMount: function componentDidMount() { var inputNode = this.getInputNode(); if (inputNode !== undefined) { this.setTextInputFocus(); if (!this.getEditor().disableContainerStyles) { inputNode.className += ' editor-main'; inputNode.style.height = this.props.height - 1 + 'px'; } } }, componentWillUnmount: function componentWillUnmount() { if (!this.changeCommitted && !this.hasEscapeBeenPressed()) { this.commit({ key: 'Enter' }); } }, createEditor: function createEditor() { var _this = this; var editorRef = function editorRef(c) { return _this.editor = c; }; var editorProps = { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onCommit: this.commit, rowMetaData: this.getRowMetaData(), height: this.props.height, onBlur: this.commit, onOverrideKeyDown: this.onKeyDown }; var customEditor = this.props.column.editor; if (customEditor && React.isValidElement(customEditor)) { // return custom column editor or SimpleEditor if none specified return React.cloneElement(customEditor, editorProps); } return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function onKeyDown() {}, commit: function commit() {} }); }, onPressEnter: function onPressEnter() { this.commit({ key: 'Enter' }); }, onPressTab: function onPressTab() { this.commit({ key: 'Tab' }); }, onPressEscape: function onPressEscape(e) { if (!this.editorIsSelectOpen()) { this.props.cellMetaData.onCommitCancel(); } else { // prevent event from bubbling if editor has results to select e.stopPropagation(); } }, onPressArrowDown: function onPressArrowDown(e) { if (this.editorHasResults()) { // dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowUp: function onPressArrowUp(e) { if (this.editorHasResults()) { // dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowLeft: function onPressArrowLeft(e) { // prevent event propogation. this disables left cell navigation if (!this.isCaretAtBeginningOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, onPressArrowRight: function onPressArrowRight(e) { // prevent event propogation. this disables right cell navigation if (!this.isCaretAtEndOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, editorHasResults: function editorHasResults() { if (isFunction(this.getEditor().hasResults)) { return this.getEditor().hasResults(); } return false; }, editorIsSelectOpen: function editorIsSelectOpen() { if (isFunction(this.getEditor().isSelectOpen)) { return this.getEditor().isSelectOpen(); } return false; }, getRowMetaData: function getRowMetaData() { // clone row data so editor cannot actually change this // convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.props.rowData, this.props.column); } }, getEditor: function getEditor() { return this.editor; }, getInputNode: function getInputNode() { return this.getEditor().getInputNode(); }, getInitialValue: function getInitialValue() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; if (keyCode === 'Delete' || keyCode === 'Backspace') { return ''; } else if (keyCode === 'Enter') { return this.props.value; } var text = keyCode ? String.fromCharCode(keyCode) : this.props.value; return text; }, getContainerClass: function getContainerClass() { return joinClasses({ 'has-error': this.state.isInvalid === true }); }, commit: function commit(args) { var opts = args || {}; var updated = this.getEditor().getValue(); if (this.isNewValueValid(updated)) { var cellKey = this.props.column.key; this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key }); } this.changeCommitted = true; }, isNewValueValid: function isNewValueValid(value) { if (isFunction(this.getEditor().validate)) { var isValid = this.getEditor().validate(value); this.setState({ isInvalid: !isValid }); return isValid; } return true; }, setCaretAtEndOfInput: function setCaretAtEndOfInput() { var input = this.getInputNode(); // taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element var txtLength = input.value.length; if (input.setSelectionRange) { input.setSelectionRange(txtLength, txtLength); } else if (input.createTextRange) { var fieldRange = input.createTextRange(); fieldRange.moveStart('character', txtLength); fieldRange.collapse(); fieldRange.select(); } }, isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0; }, isCaretAtEndOfInput: function isCaretAtEndOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.value.length; }, setTextInputFocus: function setTextInputFocus() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; var inputNode = this.getInputNode(); inputNode.focus(); if (inputNode.tagName === 'INPUT') { if (!this.isKeyPrintable(keyCode)) { inputNode.focus(); inputNode.select(); } else { inputNode.select(); } } }, hasEscapeBeenPressed: function hasEscapeBeenPressed() { var pressed = false; var escapeKey = 27; if (window.event) { if (window.event.keyCode === escapeKey) { pressed = true; } else if (window.event.which === escapeKey) { pressed = true; } } return pressed; }, renderStatusIcon: function renderStatusIcon() { if (this.state.isInvalid === true) { return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' }); } }, render: function render() { return React.createElement( 'div', { className: this.getContainerClass(), onKeyDown: this.onKeyDown, commit: this.commit }, this.createEditor(), this.renderStatusIcon() ); } }); module.exports = EditorContainer; /***/ }, /* 25 */ /***/ function(module, exports) { 'use strict'; var KeyboardHandlerMixin = { onKeyDown: function onKeyDown(e) { if (this.isCtrlKeyHeldDown(e)) { this.checkAndCall('onPressKeyWithCtrl', e); } else if (this.isKeyExplicitlyHandled(e.key)) { // break up individual keyPress events to have their own specific callbacks // this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing var callBack = 'onPress' + e.key; this.checkAndCall(callBack, e); } else if (this.isKeyPrintable(e.keyCode)) { this.checkAndCall('onPressChar', e); } }, // taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character isKeyPrintable: function isKeyPrintable(keycode) { var valid = keycode > 47 && keycode < 58 || // number keys keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns) keycode > 64 && keycode < 91 || // letter keys keycode > 95 && keycode < 112 || // numpad keys keycode > 185 && keycode < 193 || // ;=,-./` (in order) keycode > 218 && keycode < 223; // [\]' (in order) return valid; }, isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) { return typeof this['onPress' + key] === 'function'; }, isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) { return e.ctrlKey === true && e.key !== 'Control'; }, checkAndCall: function checkAndCall(methodName, args) { if (typeof this[methodName] === 'function') { this[methodName](args); } } }; module.exports = KeyboardHandlerMixin; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 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; } var React = __webpack_require__(2); var EditorBase = __webpack_require__(27); var SimpleTextEditor = function (_EditorBase) { _inherits(SimpleTextEditor, _EditorBase); function SimpleTextEditor() { _classCallCheck(this, SimpleTextEditor); return _possibleConstructorReturn(this, Object.getPrototypeOf(SimpleTextEditor).apply(this, arguments)); } _createClass(SimpleTextEditor, [{ key: 'render', value: function render() { return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value }); } }]); return SimpleTextEditor; }(EditorBase); module.exports = SimpleTextEditor; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 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; } var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var ExcelColumn = __webpack_require__(15); var EditorBase = function (_React$Component) { _inherits(EditorBase, _React$Component); function EditorBase() { _classCallCheck(this, EditorBase); return _possibleConstructorReturn(this, Object.getPrototypeOf(EditorBase).apply(this, arguments)); } _createClass(EditorBase, [{ key: 'getStyle', value: function getStyle() { return { width: '100%' }; } }, { key: 'getValue', value: function getValue() { var updated = {}; updated[this.props.column.key] = this.getInputNode().value; return updated; } }, { key: 'getInputNode', value: function getInputNode() { var domNode = ReactDOM.findDOMNode(this); if (domNode.tagName === 'INPUT') { return domNode; } return domNode.querySelector('input:not([type=hidden])'); } }, { key: 'inheritContainerStyles', value: function inheritContainerStyles() { return true; } }]); return EditorBase; }(React.Component); EditorBase.propTypes = { onKeyDown: React.PropTypes.func.isRequired, value: React.PropTypes.any.isRequired, onBlur: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired, commit: React.PropTypes.func.isRequired }; module.exports = EditorBase; /***/ }, /* 28 */ /***/ function(module, exports) { 'use strict'; var isFunction = function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; module.exports = isFunction; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var PropTypes = __webpack_require__(2).PropTypes; module.exports = { selected: PropTypes.object.isRequired, copied: PropTypes.object, dragged: PropTypes.object, onCellClick: PropTypes.func.isRequired, onCellDoubleClick: PropTypes.func.isRequired, onCommit: PropTypes.func.isRequired, onCommitCancel: PropTypes.func.isRequired, handleDragEnterRow: PropTypes.func.isRequired, handleTerminateDrag: PropTypes.func.isRequired }; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var SimpleCellFormatter = React.createClass({ displayName: 'SimpleCellFormatter', propTypes: { value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value; }, render: function render() { return React.createElement( 'span', null, this.props.value ); } }); module.exports = SimpleCellFormatter; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var DOMMetrics = __webpack_require__(32); var min = Math.min; var max = Math.max; var floor = Math.floor; var ceil = Math.ceil; module.exports = { mixins: [DOMMetrics.MetricsMixin], DOMMetrics: { viewportHeight: function viewportHeight() { return ReactDOM.findDOMNode(this).offsetHeight; } }, propTypes: { rowHeight: React.PropTypes.number, rowsCount: React.PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() { return { rowHeight: 30 }; }, getInitialState: function getInitialState() { return this.getGridState(this.props); }, getGridState: function getGridState(props) { var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight); var totalRowCount = min(renderedRowsCount * 2, props.rowsCount); return { displayStart: 0, displayEnd: totalRowCount, height: props.minHeight, scrollTop: 0, scrollLeft: 0 }; }, updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) { var renderedRowsCount = ceil(height / rowHeight); var visibleStart = floor(scrollTop / rowHeight); var visibleEnd = min(visibleStart + renderedRowsCount, length); var displayStart = max(0, visibleStart - renderedRowsCount * 2); var displayEnd = min(visibleStart + renderedRowsCount * 2, length); var nextScrollState = { visibleStart: visibleStart, visibleEnd: visibleEnd, displayStart: displayStart, displayEnd: displayEnd, height: height, scrollTop: scrollTop, scrollLeft: scrollLeft }; this.setState(nextScrollState); }, metricsUpdated: function metricsUpdated() { var height = this.DOMMetrics.viewportHeight(); if (height) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight) { this.setState(this.getGridState(nextProps)); } else if (this.props.rowsCount !== nextProps.rowsCount) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount); } } }; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var shallowCloneObject = __webpack_require__(7); var contextTypes = { metricsComputator: React.PropTypes.object }; var MetricsComputatorMixin = { childContextTypes: contextTypes, getChildContext: function getChildContext() { return { metricsComputator: this }; }, getMetricImpl: function getMetricImpl(name) { return this._DOMMetrics.metrics[name].value; }, registerMetricsImpl: function registerMetricsImpl(component, metrics) { var getters = {}; var s = this._DOMMetrics; for (var name in metrics) { if (s.metrics[name] !== undefined) { throw new Error('DOM metric ' + name + ' is already defined'); } s.metrics[name] = { component: component, computator: metrics[name].bind(component) }; getters[name] = this.getMetricImpl.bind(null, name); } if (s.components.indexOf(component) === -1) { s.components.push(component); } return getters; }, unregisterMetricsFor: function unregisterMetricsFor(component) { var s = this._DOMMetrics; var idx = s.components.indexOf(component); if (idx > -1) { s.components.splice(idx, 1); var name = undefined; var metricsToDelete = {}; for (name in s.metrics) { if (s.metrics[name].component === component) { metricsToDelete[name] = true; } } for (name in metricsToDelete) { if (metricsToDelete.hasOwnProperty(name)) { delete s.metrics[name]; } } } }, updateMetrics: function updateMetrics() { var s = this._DOMMetrics; var needUpdate = false; for (var name in s.metrics) { if (!s.metrics.hasOwnProperty(name)) continue; var newMetric = s.metrics[name].computator(); if (newMetric !== s.metrics[name].value) { needUpdate = true; } s.metrics[name].value = newMetric; } if (needUpdate) { for (var i = 0, len = s.components.length; i < len; i++) { if (s.components[i].metricsUpdated) { s.components[i].metricsUpdated(); } } } }, componentWillMount: function componentWillMount() { this._DOMMetrics = { metrics: {}, components: [] }; }, componentDidMount: function componentDidMount() { if (window.addEventListener) { window.addEventListener('resize', this.updateMetrics); } else { window.attachEvent('resize', this.updateMetrics); } this.updateMetrics(); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.updateMetrics); } }; var MetricsMixin = { contextTypes: contextTypes, componentWillMount: function componentWillMount() { if (this.DOMMetrics) { this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics); this.DOMMetrics = {}; for (var name in this._DOMMetricsDefs) { if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue; this.DOMMetrics[name] = function () {}; } } }, componentDidMount: function componentDidMount() { if (this.DOMMetrics) { this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs); } }, componentWillUnmount: function componentWillUnmount() { if (!this.registerMetricsImpl) { return this.context.metricsComputator.unregisterMetricsFor(this); } if (this.hasOwnProperty('DOMMetrics')) { delete this.DOMMetrics; } }, registerMetrics: function registerMetrics(metrics) { if (this.registerMetricsImpl) { return this.registerMetricsImpl(this, metrics); } return this.context.metricsComputator.registerMetricsImpl(this, metrics); }, getMetric: function getMetric(name) { if (this.getMetricImpl) { return this.getMetricImpl(name); } return this.context.metricsComputator.getMetricImpl(name); } }; module.exports = { MetricsComputatorMixin: MetricsComputatorMixin, MetricsMixin: MetricsMixin }; /***/ }, /* 33 */ /***/ function(module, exports) { "use strict"; module.exports = { componentDidMount: function componentDidMount() { this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0; this._onScroll(); }, componentDidUpdate: function componentDidUpdate() { this._onScroll(); }, componentWillMount: function componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount: function componentWillUnmount() { this._scrollLeft = undefined; }, onScroll: function onScroll(props) { if (this._scrollLeft !== props.scrollLeft) { this._scrollLeft = props.scrollLeft; this._onScroll(); } }, _onScroll: function _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); if (this.refs.viewport) { this.refs.viewport.setScrollLeft(this._scrollLeft); } } } }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var CheckboxEditor = React.createClass({ displayName: 'CheckboxEditor', propTypes: { value: React.PropTypes.bool.isRequired, rowIdx: React.PropTypes.number.isRequired, column: React.PropTypes.shape({ key: React.PropTypes.string.isRequired, onCellChange: React.PropTypes.func.isRequired }).isRequired, dependentValues: React.PropTypes.object }, handleChange: function handleChange(e) { this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e); }, render: function render() { var checked = this.props.value != null ? this.props.value : false; var checkboxName = 'checkbox' + this.props.rowIdx; return React.createElement( 'div', { className: 'react-grid-checkbox-container', onClick: this.handleChange }, React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }), React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' }) ); } }); module.exports = CheckboxEditor; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ExcelColumn = __webpack_require__(15); var FilterableHeaderCell = React.createClass({ displayName: 'FilterableHeaderCell', propTypes: { onChange: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn) }, getInitialState: function getInitialState() { return { filterTerm: '' }; }, handleChange: function handleChange(e) { var val = e.target.value; this.setState({ filterTerm: val }); this.props.onChange({ filterTerm: val, columnKey: this.props.column.key }); }, renderInput: function renderInput() { if (this.props.column.filterable === false) { return React.createElement('span', null); } var inputKey = 'header-filter-' + this.props.column.key; return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange }); }, render: function render() { return React.createElement( 'div', null, React.createElement( 'div', { className: 'form-group' }, this.renderInput() ) ); } }); module.exports = FilterableHeaderCell; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ColumnMetrics = __webpack_require__(8); var DOMMetrics = __webpack_require__(32); Object.assign = __webpack_require__(37); var PropTypes = __webpack_require__(2).PropTypes; var ColumnUtils = __webpack_require__(10); var Column = function Column() { _classCallCheck(this, Column); }; module.exports = { mixins: [DOMMetrics.MetricsMixin], propTypes: { columns: PropTypes.arrayOf(Column), minColumnWidth: PropTypes.number, columnEquality: PropTypes.func }, DOMMetrics: { gridWidth: function gridWidth() { return _reactDom2.default.findDOMNode(this).parentElement.offsetWidth; } }, getDefaultProps: function getDefaultProps() { return { minColumnWidth: 80, columnEquality: ColumnMetrics.sameColumn }; }, componentWillMount: function componentWillMount() { this._mounted = true; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.columns) { if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) { var columnMetrics = this.createColumnMetrics(nextProps); this.setState({ columnMetrics: columnMetrics }); } } }, getTotalWidth: function getTotalWidth() { var totalWidth = 0; if (this._mounted) { totalWidth = this.DOMMetrics.gridWidth(); } else { totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth; } return totalWidth; }, getColumnMetricsType: function getColumnMetricsType(metrics) { var totalWidth = metrics.totalWidth || this.getTotalWidth(); var currentMetrics = { columns: metrics.columns, totalWidth: totalWidth, minColumnWidth: metrics.minColumnWidth }; var updatedMetrics = ColumnMetrics.recalculate(currentMetrics); return updatedMetrics; }, getColumn: function getColumn(idx) { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, getSize: function getSize() { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } }, metricsUpdated: function metricsUpdated() { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); }, createColumnMetrics: function createColumnMetrics() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var gridColumns = this.setupGridColumns(props); return this.getColumnMetricsType({ columns: gridColumns, minColumnWidth: this.props.minColumnWidth, totalWidth: props.minWidth }); }, onColumnResize: function onColumnResize(index, width) { var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width); this.setState({ columnMetrics: columnMetrics }); } }; /***/ }, /* 37 */ /***/ function(module, exports) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 38 */ /***/ function(module, exports) { 'use strict'; var RowUtils = { get: function get(row, property) { if (typeof row.get === 'function') { return row.get(property); } return row[property]; } }; module.exports = RowUtils; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Editors = { AutoComplete: __webpack_require__(40), DropDownEditor: __webpack_require__(42), SimpleTextEditor: __webpack_require__(26), CheckboxEditor: __webpack_require__(34) }; module.exports = Editors; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactAutocomplete = __webpack_require__(41); var ExcelColumn = __webpack_require__(15); var optionPropType = React.PropTypes.shape({ id: React.PropTypes.required, title: React.PropTypes.string }); var AutoCompleteEditor = React.createClass({ displayName: 'AutoCompleteEditor', propTypes: { onCommit: React.PropTypes.func.isRequired, options: React.PropTypes.arrayOf(optionPropType).isRequired, label: React.PropTypes.any, value: React.PropTypes.any.isRequired, height: React.PropTypes.number, valueParams: React.PropTypes.arrayOf(React.PropTypes.string), column: React.PropTypes.shape(ExcelColumn).isRequired, resultIdentifier: React.PropTypes.string, search: React.PropTypes.string, onKeyDown: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { resultIdentifier: 'id' }; }, handleChange: function handleChange() { this.props.onCommit(); }, getValue: function getValue() { var value = undefined; var updated = {}; if (this.hasResults() && this.isFocusedOnSuggestion()) { value = this.getLabel(this.refs.autoComplete.state.focusedValue); if (this.props.valueParams) { value = this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue, this.props.valueParams); } } else { value = this.refs.autoComplete.state.searchTerm; } updated[this.props.column.key] = value; return updated; }, getInputNode: function getInputNode() { return ReactDOM.findDOMNode(this).getElementsByTagName('input')[0]; }, getLabel: function getLabel(item) { var label = this.props.label != null ? this.props.label : 'title'; if (typeof label === 'function') { return label(item); } else if (typeof label === 'string') { return item[label]; } }, hasResults: function hasResults() { return this.refs.autoComplete.state.results.length > 0; }, isFocusedOnSuggestion: function isFocusedOnSuggestion() { var autoComplete = this.refs.autoComplete; return autoComplete.state.focusedValue != null; }, constuctValueFromParams: function constuctValueFromParams(obj, props) { if (!props) { return ''; } var ret = []; for (var i = 0, ii = props.length; i < ii; i++) { ret.push(obj[props[i]]); } return ret.join('|'); }, render: function render() { var label = this.props.label != null ? this.props.label : 'title'; return React.createElement( 'div', { height: this.props.height, onKeyDown: this.props.onKeyDown }, React.createElement(ReactAutocomplete, { search: this.props.search, ref: 'autoComplete', label: label, onChange: this.handleChange, resultIdentifier: this.props.resultIdentifier, options: this.props.options, value: { title: this.props.value } }) ); } }); module.exports = AutoCompleteEditor; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__webpack_require__(2)); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactAutocomplete"] = factory(require("react")); else root["ReactAutocomplete"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(1); var joinClasses = __webpack_require__(2); var Autocomplete = React.createClass({ displayName: "Autocomplete", propTypes: { options: React.PropTypes.any, search: React.PropTypes.func, resultRenderer: React.PropTypes.oneOfType([React.PropTypes.component, React.PropTypes.func]), value: React.PropTypes.object, onChange: React.PropTypes.func, onError: React.PropTypes.func }, getDefaultProps: function () { return { search: searchArray }; }, getInitialState: function () { var searchTerm = this.props.searchTerm ? this.props.searchTerm : this.props.value ? this.props.value.title : ""; return { results: [], showResults: false, showResultsInProgress: false, searchTerm: searchTerm, focusedValue: null }; }, getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var className = joinClasses(this.props.className, "react-autocomplete-Autocomplete", this.state.showResults ? "react-autocomplete-Autocomplete--resultsShown" : undefined); var style = { position: "relative", outline: "none" }; return React.createElement("div", { tabIndex: "1", className: className, onFocus: this.onFocus, onBlur: this.onBlur, style: style }, React.createElement("input", { ref: "search", className: "react-autocomplete-Autocomplete__search", style: { width: "100%" }, onClick: this.showAllResults, onChange: this.onQueryChange, onFocus: this.showAllResults, onBlur: this.onQueryBlur, onKeyDown: this.onQueryKeyDown, value: this.state.searchTerm }), React.createElement(Results, { className: "react-autocomplete-Autocomplete__results", onSelect: this.onValueChange, onFocus: this.onValueFocus, results: this.state.results, focusedValue: this.state.focusedValue, show: this.state.showResults, renderer: this.props.resultRenderer, label: this.props.label, resultIdentifier: this.props.resultIdentifier })); }, componentWillReceiveProps: function (nextProps) { var searchTerm = nextProps.searchTerm ? nextProps.searchTerm : nextProps.value ? nextProps.value.title : ""; this.setState({ searchTerm: searchTerm }); }, componentWillMount: function () { this.blurTimer = null; }, /** * Show results for a search term value. * * This method doesn't update search term value itself. * * @param {Search} searchTerm */ showResults: function (searchTerm) { this.setState({ showResultsInProgress: true }); this.props.search(this.props.options, searchTerm.trim(), this.onSearchComplete); }, showAllResults: function () { if (!this.state.showResultsInProgress && !this.state.showResults) { this.showResults(""); } }, onValueChange: function (value) { var state = { value: value, showResults: false }; if (value) { state.searchTerm = value.title; } this.setState(state); if (this.props.onChange) { this.props.onChange(value); } }, onSearchComplete: function (err, results) { if (err) { if (this.props.onError) { this.props.onError(err); } else { throw err; } } this.setState({ showResultsInProgress: false, showResults: true, results: results }); }, onValueFocus: function (value) { this.setState({ focusedValue: value }); }, onQueryChange: function (e) { var searchTerm = e.target.value; this.setState({ searchTerm: searchTerm, focusedValue: null }); this.showResults(searchTerm); }, onFocus: function () { if (this.blurTimer) { clearTimeout(this.blurTimer); this.blurTimer = null; } this.refs.search.getDOMNode().focus(); }, onBlur: function () { // wrap in setTimeout so we can catch a click on results this.blurTimer = setTimeout((function () { if (this.isMounted()) { this.setState({ showResults: false }); } }).bind(this), 100); }, onQueryKeyDown: function (e) { if (e.key === "Enter") { e.preventDefault(); if (this.state.focusedValue) { this.onValueChange(this.state.focusedValue); } } else if (e.key === "ArrowUp" && this.state.showResults) { e.preventDefault(); var prevIdx = Math.max(this.focusedValueIndex() - 1, 0); this.setState({ focusedValue: this.state.results[prevIdx] }); } else if (e.key === "ArrowDown") { e.preventDefault(); if (this.state.showResults) { var nextIdx = Math.min(this.focusedValueIndex() + (this.state.showResults ? 1 : 0), this.state.results.length - 1); this.setState({ showResults: true, focusedValue: this.state.results[nextIdx] }); } else { this.showAllResults(); } } }, focusedValueIndex: function () { if (!this.state.focusedValue) { return -1; } for (var i = 0, len = this.state.results.length; i < len; i++) { if (this.getResultIdentifier(this.state.results[i]) === this.getResultIdentifier(this.state.focusedValue)) { return i; } } return -1; } }); var Results = React.createClass({ displayName: "Results", getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { if (!result.id) { throw "id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component"; } return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var style = { display: this.props.show ? "block" : "none", position: "absolute", listStyleType: "none" }; var $__0 = this.props, className = $__0.className, props = (function (source, exclusion) { var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) { throw new TypeError(); }for (var key in source) { if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) { rest[key] = source[key]; } }return rest; })($__0, { className: 1 }); return React.createElement("ul", React.__spread({}, props, { style: style, className: className + " react-autocomplete-Results" }), this.props.results.map(this.renderResult)); }, renderResult: function (result) { var focused = this.props.focusedValue && this.getResultIdentifier(this.props.focusedValue) === this.getResultIdentifier(result); var Renderer = this.props.renderer || Result; return React.createElement(Renderer, { ref: focused ? "focused" : undefined, key: this.getResultIdentifier(result), result: result, focused: focused, onMouseEnter: this.onMouseEnterResult, onClick: this.props.onSelect, label: this.props.label }); }, componentDidUpdate: function () { this.scrollToFocused(); }, componentDidMount: function () { this.scrollToFocused(); }, componentWillMount: function () { this.ignoreFocus = false; }, scrollToFocused: function () { var focused = this.refs && this.refs.focused; if (focused) { var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = focused.getDOMNode(); var top = node.offsetTop; var bottom = top + node.offsetHeight; // we update ignoreFocus to true if we change the scroll position so // the mouseover event triggered because of that won't have an // effect if (top < scroll) { this.ignoreFocus = true; containerNode.scrollTop = top; } else if (bottom - scroll > height) { this.ignoreFocus = true; containerNode.scrollTop = bottom - height; } } }, onMouseEnterResult: function (e, result) { // check if we need to prevent the next onFocus event because it was // probably caused by a mouseover due to scroll position change if (this.ignoreFocus) { this.ignoreFocus = false; } else { // we need to make sure focused node is visible // for some reason mouse events fire on visible nodes due to // box-shadow var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = e.target; var top = node.offsetTop; var bottom = top + node.offsetHeight; if (bottom > scroll && top < scroll + height) { this.props.onFocus(result); } } } }); var Result = React.createClass({ displayName: "Result", getDefaultProps: function () { return { label: function (result) { return result.title; } }; }, getLabel: function (result) { if (typeof this.props.label === "function") { return this.props.label(result); } else if (typeof this.props.label === "string") { return result[this.props.label]; } }, render: function () { var className = joinClasses({ "react-autocomplete-Result": true, "react-autocomplete-Result--active": this.props.focused }); return React.createElement("li", { style: { listStyleType: "none" }, className: className, onClick: this.onClick, onMouseEnter: this.onMouseEnter }, React.createElement("a", null, this.getLabel(this.props.result))); }, onClick: function () { this.props.onClick(this.props.result); }, onMouseEnter: function (e) { if (this.props.onMouseEnter) { this.props.onMouseEnter(e, this.props.result); } }, shouldComponentUpdate: function (nextProps) { return nextProps.result.id !== this.props.result.id || nextProps.focused !== this.props.focused; } }); /** * Search options using specified search term treating options as an array * of candidates. * * @param {Array.<Object>} options * @param {String} searchTerm * @param {Callback} cb */ function searchArray(options, searchTerm, cb) { if (!options) { return cb(null, []); } searchTerm = new RegExp(searchTerm, "i"); var results = []; for (var i = 0, len = options.length; i < len; i++) { if (searchTerm.exec(options[i].title)) { results.push(options[i]); } } cb(null, results); } module.exports = Autocomplete; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ } /******/ ]) }); ; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _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; } var React = __webpack_require__(2); var EditorBase = __webpack_require__(27); var DropDownEditor = function (_EditorBase) { _inherits(DropDownEditor, _EditorBase); function DropDownEditor() { _classCallCheck(this, DropDownEditor); return _possibleConstructorReturn(this, Object.getPrototypeOf(DropDownEditor).apply(this, arguments)); } _createClass(DropDownEditor, [{ key: 'getInputNode', value: function getInputNode() { return _reactDom2.default.findDOMNode(this); } }, { key: 'onClick', value: function onClick() { this.getInputNode().focus(); } }, { key: 'onDoubleClick', value: function onDoubleClick() { this.getInputNode().focus(); } }, { key: 'render', value: function render() { return React.createElement( 'select', { style: this.getStyle(), defaultValue: this.props.value, onBlur: this.props.onBlur, onChange: this.onChange }, this.renderOptions() ); } }, { key: 'renderOptions', value: function renderOptions() { var options = []; this.props.options.forEach(function (name) { options.push(React.createElement( 'option', { key: name, value: name }, name )); }, this); return options; } }]); return DropDownEditor; }(EditorBase); DropDownEditor.propTypes = { options: React.PropTypes.arrayOf(React.PropTypes.string).isRequired }; module.exports = DropDownEditor; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // not including this // it currently requires the whole of moment, which we dont want to take as a dependency var ImageFormatter = __webpack_require__(44); var Formatters = { ImageFormatter: ImageFormatter }; module.exports = Formatters; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var PendingPool = {}; var ReadyPool = {}; var ImageFormatter = React.createClass({ displayName: 'ImageFormatter', propTypes: { value: React.PropTypes.string.isRequired }, getInitialState: function getInitialState() { return { ready: false }; }, componentWillMount: function componentWillMount() { this._load(this.props.value); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState({ value: null }); this._load(nextProps.value); } }, _load: function _load(src) { var imageSrc = src; if (ReadyPool[imageSrc]) { this.setState({ value: imageSrc }); return; } if (PendingPool[imageSrc]) { PendingPool[imageSrc].push(this._onLoad); return; } PendingPool[imageSrc] = [this._onLoad]; var img = new Image(); img.onload = function () { PendingPool[imageSrc].forEach(function (callback) { callback(imageSrc); }); delete PendingPool[imageSrc]; img.onload = null; imageSrc = undefined; }; img.src = imageSrc; }, _onLoad: function _onLoad(src) { if (this.isMounted() && src === this.props.value) { this.setState({ value: src }); } }, render: function render() { var style = this.state.value ? { backgroundImage: 'url(' + this.state.value + ')' } : undefined; return React.createElement('div', { className: 'react-grid-image', style: style }); } }); module.exports = ImageFormatter; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(2); var Toolbar = React.createClass({ displayName: "Toolbar", propTypes: { onAddRow: React.PropTypes.func, onToggleFilter: React.PropTypes.func.isRequired, enableFilter: React.PropTypes.bool, numberOfRows: React.PropTypes.number.isRequired }, onAddRow: function onAddRow() { if (this.props.onAddRow !== null && this.props.onAddRow instanceof Function) { this.props.onAddRow({ newRowIndex: this.props.numberOfRows }); } }, getDefaultProps: function getDefaultProps() { return { enableAddRow: true }; }, renderAddRowButton: function renderAddRowButton() { if (this.props.onAddRow) { return React.createElement( "button", { type: "button", className: "btn", onClick: this.onAddRow }, "Add Row" ); } }, renderToggleFilterButton: function renderToggleFilterButton() { if (this.props.enableFilter) { return React.createElement( "button", { type: "button", className: "btn", onClick: this.props.onToggleFilter }, "Filter Rows" ); } }, render: function render() { return React.createElement( "div", { className: "react-grid-Toolbar" }, React.createElement( "div", { className: "tools" }, this.renderAddRowButton(), this.renderToggleFilterButton() ) ); } }); module.exports = Toolbar; /***/ } /******/ ]) }); ;
src/HouseNumbers.js
nickooms/racing-webgl2
import React, { Component } from 'react'; import { List, ListItem } from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import muiThemeable from 'material-ui/styles/muiThemeable'; class HouseNumbers extends Component { render() { const { houseNumbers, muiTheme } = this.props; return ( <List style={{ backgroundColor: muiTheme.palette.canvasColor }}> <Subheader style={{ color: muiTheme.palette.accent1Color }}>HouseNumbers [{houseNumbers.length}]</Subheader> { houseNumbers && houseNumbers.map(({ id, number }, index) => ( <ListItem key={index} primaryText={number} style={{ color: muiTheme.palette.textColor }}/> )) } </List> ); } } export default muiThemeable()(HouseNumbers);
actor-apps/app-web/src/app/components/common/Favicon.react.js
ONode/actor-platform
import React from 'react'; export default class Fav extends React.Component { static propTypes = { path: React.PropTypes.string } constructor(props) { super(props); //// Create link element and it's attributes //let favicon = document.createElement('link'); //let rel = document.createAttribute('rel'); //let type = document.createAttribute('type'); //let href = document.createAttribute('href'); //let id = document.createAttribute('id'); // //// Set attributes values //rel.value = 'icon'; //type.value = 'image/png'; //href.value = props.path; //id.value = 'favicon'; // //// Set attributes to favicon element //favicon.setAttributeNode(rel); //favicon.setAttributeNode(type); //favicon.setAttributeNode(href); //favicon.setAttributeNode(id); // //// Append favicon to head //document.head.appendChild(favicon); } componentDidUpdate() { // Clone created element and create href attribute let updatedFavicon = document.getElementById('favicon').cloneNode(true); let href = document.createAttribute('href'); // Set new href attribute href.value = this.props.path; updatedFavicon.setAttributeNode(href); // Remove old and add new favicon document.getElementById('favicon').remove(); document.head.appendChild(updatedFavicon); } render() { return null; } }
sites/all/libraries/highcharts/exporting-server/phantomjs/jquery.1.9.1.min.js
PCD/drupalglobal1
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,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%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},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(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.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(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
index.ios.js
yarikgenza/WhereToGo-Lviv
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class WhereToGo extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('WhereToGo', () => WhereToGo);
src/components/connect-bar.js
CrispyBacon12/facebook-chat
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { addComments } from '../actions'; import facebookConnector from '../services/facebook'; const facebook = facebookConnector(); class ConnectBar extends Component { constructor(props) { super(props); this.state = {videoId: ''}; this.facebook = facebookConnector(); this.onInputChange = this.onInputChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } render() { return ( <form className="form-inline" onSubmit={this.onSubmit}> <input className="form-control mr-2" type="text" value={this.state.videoId} onChange={this.onInputChange}/> <button type="submit" className="btn btn-primary">Connect!</button> </form> ); } onInputChange(event) { this.setState({videoId: event.target.value}); } onSubmit(event) { event.preventDefault(); const connection = this.facebook.connectToStream(this.state.videoId, (comments) => { this.props.addComments(comments); }); } } function mapDispatchToProps(dispatch) { return bindActionCreators({addComments}, dispatch); } export default connect(null, mapDispatchToProps)(ConnectBar)
src/components/FormButton.js
bartonhammond/snowflake
/** * # FormButton.js * * Display a button that responds to onPress and is colored appropriately */ 'use strict' /** * ## Imports * * React */ import React from 'react' import { StyleSheet, View } from 'react-native' /** * The platform neutral button */ const Button = require('apsl-react-native-button') /** * ## Styles */ var styles = StyleSheet.create({ signin: { marginLeft: 10, marginRight: 10 }, button: { backgroundColor: '#FF3366', borderColor: '#FF3366' } }) var FormButton = React.createClass({ /** * ### render * * Display the Button */ render () { return ( <View style={styles.signin}> <Button style={styles.button} textStyle={{fontSize: 18}} isDisabled={this.props.isDisabled} onPress={this.props.onPress} > {this.props.buttonText} </Button> </View> ) } }) module.exports = FormButton
apps/lc101/src/mario3-react/src/index.js
reggieroby/devpack
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/widgets/NodeLayerWidget.js
woodenconsulting/react-js-diagrams
import React from 'react'; import _ from 'lodash'; import { NodeWidget } from './NodeWidget'; export class NodeLayerWidget extends React.Component { render() { const { diagramEngine } = this.props; const diagramModel = diagramEngine.getDiagramModel(); const props = { className:'node-view', style:{ transform: `scale(${diagramModel.getZoomLevel() / 100.0}) translate(${diagramModel.getOffsetX()}px, ${diagramModel.getOffsetY()}px)`, // eslint-disable-line width: '100%', height: '100%' } }; // Create children const children = _.map(diagramModel.getNodes(), node => { return ( <NodeWidget key={node.id} node={node} diagramEngine={diagramEngine} > {this.props.diagramEngine.generateWidgetForNode(node)} </NodeWidget> ); }); return ( <div {...props}> {children} </div> ); } }
src/containers/RecipeList.js
efloden/open-recipes
import React from 'react' import PropTypes from 'prop-types' import '../App.css' import * as firebase from 'firebase' import TriCheckbox from '../components/TriCheckbox' import { Button, Form, FormGroup, Col, ListGroup, ListGroupItem, InputGroup, Input } from 'reactstrap' import { SortableContainer, // SortableElement, arrayMove } from 'react-sortable-hoc' class Item extends React.Component { static propTypes = { item: PropTypes.object.isRequired } removeItem = () => { const shopListRef = firebase.database().ref().child('shopList') shopListRef.child(this.props.item.key).remove() } onCheckItemChange = (event) => { const checked = event.target.checked var updates = {} updates['shopList/' + this.props.item.key + '/ticked'] = checked return firebase.database().ref().update(updates) } render () { return ( <ListGroupItem> <div className='RecipeList--left'> <label> <TriCheckbox onChange={this.onCheckItemChange} checked={this.props.item.ticked} /> {' ' + this.props.item.name} </label> </div> <span className='RecipeList--center' /> <div className='RecipeList--right'> <Button bsSize='xsmall' bsStyle='danger' onClick={this.removeItem}> x </Button> </div> </ListGroupItem> ) } } // Disabling draggable sorting // const SortableItem = SortableElement(Item) class Items extends React.Component { static propTypes = { items: PropTypes.array.isRequired } render () { const checkedItems = this.props.items.filter(function (item) { return item.ticked === true }) const unCheckedItems = this.props.items.filter(function (item) { return item.ticked === false }) return ( <div> <ListGroup> {unCheckedItems.map((value, index) => ( <Item key={`item-${index}`} index={index} value={value.name} item={value} /> ))} {checkedItems.map((value, index) => ( <Item key={`item-${index}`} index={index} value={value.name} item={value} /> ))} </ListGroup> </div> ) } } const SortableList = SortableContainer(Items) class RecipeList extends React.Component { constructor () { super() this.state = { items: undefined, itemName: '' } } componentDidMount () { const rootRef = firebase.database().ref() const itemsRef = rootRef.child('shopList') itemsRef.on('value', snap => { this.setState({ items: Object.values(snap.val()).map((item) => { return item }) }) }, function (errorObject) { console.error('The read failed: ' + errorObject.code) }) } onSortEnd = ({oldIndex, newIndex}) => { this.setState({ items: arrayMove(this.state.items, oldIndex, newIndex) }) } sortableList = (items) => { return items ? <SortableList items={items} onSortEnd={this.onSortEnd} /> : 'Nothing here but us chickens' } addItem = (e) => { // e.preventDefault() // Get a key for a new Post. var newItemKey = firebase.database().ref().child('shopList').push().key // An item entry. const itemData = { key: newItemKey, name: this.state.itemName, cost: 1, ticked: false } var updates = {} updates['/shopList/' + newItemKey] = itemData return firebase.database().ref().update(updates) } removeItem = (item) => { const shopListRef = firebase.database().ref().child('shopList') shopListRef.child(item.key).remove() } handleChange = (event) => { this.setState({ itemName: event.target.value }) } render () { return ( <div> <Col xs={3} md={3} /> <Col xs={12} md={6}> <Form inline onSubmit={this.addItem}> <FormGroup controlId='formBasicText'> Add an Item {' '} <InputGroup> <Input type='text' value={this.state.itemName} placeholder='Enter item name' onChange={this.handleChange} /> <Button type='submit'>+</Button> </InputGroup> </FormGroup> </Form> {this.sortableList(this.state.items)} </Col> <Col xs={3} md={3} /> </div> ) } } export default RecipeList
packages/material-ui-icons/src/RestaurantSharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M16 6v8h3v8h2V2c-2.76 0-5 2.24-5 4zM11 9H9V2H7v7H5V2H3v7c0 2.21 1.79 4 4 4v9h2v-9c2.21 0 4-1.79 4-4V2h-2v7z" /></React.Fragment> , 'RestaurantSharp');
docs/src/examples/collections/Form/Usage/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Message, Icon } from 'semantic-ui-react' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' const FormFormUsageExamples = () => ( <ExampleSection title='Usage'> <Message info icon> <Icon name='pointing right' /> <Message.Content> <Message.Header>Tip</Message.Header> <p> Our <code>{'<Form />'}</code> handles data just like a vanilla React{' '} <code>{'<form />'}</code>. See React's <a href='https://facebook.github.io/react/docs/forms.html#controlled-components' rel='noopener noreferrer' target='_blank' > {' '} controlled components{' '} </a> docs for more. </p> </Message.Content> </Message> <ComponentExample title='Capture Values' description='You can capture form data on change or on submit.' examplePath='collections/Form/Usage/FormExampleCaptureValues' /> <ComponentExample title='Clear On Submit' description='You can clear form values on submit.' examplePath='collections/Form/Usage/FormExampleClearOnSubmit' /> </ExampleSection> ) export default FormFormUsageExamples
src/components/Editor/components/Creator/index.js
jacobwindsor/pathway-presenter
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import EmptyState from './components/EmptyState'; import PreviewPanel from './components/PreviewPanel'; import EditorPanel from './components/EditorPanel'; import Paper from 'material-ui/Paper'; import FloatingActionButton from 'material-ui/FloatingActionButton'; import SettingsDialog from './components/SettingsDialog'; import ContentAdd from 'material-ui/svg-icons/content/add'; import { cloneDeep, isEqual } from 'lodash'; import Toolbar from './components/Toolbar'; import Slide from './components/Slide'; import Joyride from 'react-joyride'; import { setCookie, checkCookie } from '../../../../utils/cookies'; import 'react-joyride/lib/react-joyride-compiled.css'; import './index.css'; const onboardingCookieName = 'pathwayPresenterShownOnboarding'; class Creator extends Component { constructor(props) { super(props); const copy = cloneDeep(props.presentation); this.state = { activeSlideIndex: 0, selectedEntity: null, presentation: copy, settingsDialogOpen: false, hasSlideChanged: true, diagramLocked: !!( copy.slides[0].panCoordinates && copy.slides[0].zoomLevel ) }; window.onbeforeunload = this.beforeUnload; } beforeUnload = e => { if (!isEqual(this.props.presentation, this.state.presentation)) { const confirmationMessage = 'Your presentation has unsaved changed! Are you sure you want to leave?'; // Use both for cross browser // See: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload e.returnValue = confirmationMessage; return confirmationMessage; } }; handlePreviewClick = slideIndex => { this.setState(state => { return { activeSlideIndex: slideIndex, selectedEntity: null, hasSlideChanged: state.activeSlideIndex !== slideIndex, diagramLocked: !!( state.presentation.slides[slideIndex].panCoordinates && state.presentation.slides[slideIndex].zoomLevel ) }; }); }; handleEntityClick = entity => { // For now we only allow entities with text (nodes) if (!entity.textContent) return; this.setState({ selectedEntity: entity }); }; handleSingleSlideUpdate = slide => { const { activeSlideIndex } = this.state; this.setState(state => { let newSlides = state.presentation.slides.slice(); newSlides[activeSlideIndex] = Object.assign( {}, newSlides[activeSlideIndex], slide ); return { presentation: Object.assign({}, state.presentation, { slides: newSlides }), selectedEntity: null, // This may seem counter-intuitive. The slide has changed because the in-state slide differs // from the in-props slide hasSlideChanged: true }; }); }; handlePanZoomChanged = ({ x, y, zoomLevel }) => { // Use properties not state since there is no need for the component to re-render this.panCoordinates = { x, y }; this.zoomLevel = zoomLevel; }; handleLock = () => { this.setState(state => { const copy = cloneDeep(state.presentation); copy.slides[state.activeSlideIndex].panCoordinates = this.panCoordinates; copy.slides[state.activeSlideIndex].zoomLevel = this.zoomLevel; return { diagramLocked: true, presentation: copy }; }); }; handleUnlock = () => { this.setState(state => { const copy = cloneDeep(state.presentation); copy.slides[state.activeSlideIndex].panCoordinates = null; copy.slides[state.activeSlideIndex].zoomLevel = null; return { presentation: copy, diagramLocked: false }; }); }; onSlideAdd = () => { this.setState(state => { return { presentation: Object.assign({}, state.presentation, { slides: state.presentation.slides.concat({ targets: [], title: null }) }), // Since added one slide, new index is the length activeSlideIndex: state.presentation.slides.length, hasSlideChanged: true, selectedEntity: null }; }); }; handleSlidesUpdate = ({ slides, newActiveIndex }) => { this.setState(state => { const copy = cloneDeep(state.presentation); copy.slides = slides; return { presentation: copy, selectedEntity: null, activeSlideIndex: newActiveIndex, hasSlideChanged: state.activeSlideIndex !== newActiveIndex }; }); }; handleSave = () => { const { presentation } = this.state; const { handleSave } = this.props; handleSave(presentation); }; handleSettingsClick = () => { this.setState({ settingsDialogOpen: true }); }; handleSettingsSave = ({ title, authorName, wpId, version }) => { const toUpdate = cloneDeep(this.state.presentation); const updated = Object.assign(toUpdate, { title, authorName, wpId, version }); this.setState( { presentation: updated }, this.handleSave ); }; handlePresentClick = () => { if (!isEqual(this.props.presentation, this.state.presentation)) { alert( 'Unsaved changes! Save before presenting to present your latest changes.' ); return; } const { presentation } = this.state; const href = `${window.location .href}?present=true&presId=${presentation.id}`; window.open(href, '_blank'); }; renderNonEmptyComps() { const { activeSlideIndex, selectedEntity, presentation, hasSlideChanged, diagramLocked } = this.state; if (presentation.slides.length < 1) return null; const slide = presentation.slides[activeSlideIndex]; return ( <span> <div className="left-section"> <EditorPanel slide={slide} slideIndex={activeSlideIndex} activeEntity={selectedEntity} onUpdate={this.handleSingleSlideUpdate} hasSlideChanged={hasSlideChanged} handleCancelTarget={() => this.setState({ selectedEntity: null })} handleTargetChipClick={entity => this.setState({ selectedEntity: entity })} /> </div> <div className="right-section"> <div className="previewer"> <div className="slide-wrapper"> <Slide slide={slide} wpId={presentation.wpId} version={presentation.version} handleEntityClick={this.handleEntityClick} diagramLocked={diagramLocked} handlePanZoomChanged={this.handlePanZoomChanged} handleLock={this.handleLock} handleUnlock={this.handleUnlock} /> </div> </div> <Paper className="footer"> <PreviewPanel slides={presentation.slides} wpId={presentation.wpId} version={presentation.version} onClick={this.handlePreviewClick} handleUpdate={this.handleSlidesUpdate} width={'calc(100% - 10rem)'} height="100%" activeSlideIndex={activeSlideIndex} /> <FloatingActionButton id="add-slide-button" className="add-slide-button" onTouchTap={this.onSlideAdd} > <ContentAdd /> </FloatingActionButton> </Paper> </div> </span> ); } render() { const { presentation, settingsDialogOpen } = this.state; const { handleDelete } = this.props; const EmptyComps = () => { if (presentation.slides.length > 0) return null; return <EmptyState handleClick={this.onSlideAdd} />; }; const joyrideSteps = [ { title: 'Your slide', text: 'This is a preview of how your slide will look when you present it.', selector: '#slide', trigger: '#slide' }, { title: 'Position the diagram', text: "Drag the diagram and use the controls to position the diagram the way you'd like to present it.", selector: '#svg-pan-zoom-controls' }, { title: 'Lock it', text: 'Lock the diagram in place to save the positioning.', selector: '#slide-lock' }, { title: 'Highlight and hide', text: 'Click on a node in the diagram to show the controls for highlighting and hiding.', name: 'diagram-click', selector: '.diagram-wrapper' }, { title: 'Add a title', selector: '#editor-title-field' }, { title: 'Add a new slide', selector: '#add-slide-button' }, { title: 'Reorder slides', text: 'You can reorder the slides simply by dragging them.', selector: '.preview-panel' }, { title: 'Save your work!', selector: '#save-button' }, { title: 'Show the audience', text: "Once you're happy, hit present to show an audience", selector: '#present-button' } ]; const joyrideCallback = ({ type }) => { if (type === 'finished') { setCookie(onboardingCookieName); } }; const shouldShowJoyride = checkCookie(onboardingCookieName); return ( <div className="creator-wrapper"> <Joyride ref="joyride" steps={joyrideSteps} run={shouldShowJoyride} showSkipButton={true} autoStart={true} type="continuous" callback={joyrideCallback} /> <Toolbar authorName={presentation.authorName} title={presentation.title} handleSave={this.handleSave} handlePresentClick={this.handlePresentClick} handleSettingsClick={this.handleSettingsClick} /> <SettingsDialog handleDelete={handleDelete} isOpen={settingsDialogOpen} handleClose={() => this.setState({ settingsDialogOpen: false })} handleSave={this.handleSettingsSave} version={presentation.version} wpId={presentation.wpId} authorName={presentation.authorName} title={presentation.title} /> <EmptyComps /> {this.renderNonEmptyComps()} </div> ); } } Creator.propTypes = { presentation: PropTypes.object.isRequired, handleSave: PropTypes.func.isRequired, handleDelete: PropTypes.func.isRequired }; export default Creator;
src/svg-icons/maps/local-laundry-service.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalLaundryService = (props) => ( <SvgIcon {...props}> <path d="M9.17 16.83c1.56 1.56 4.1 1.56 5.66 0 1.56-1.56 1.56-4.1 0-5.66l-5.66 5.66zM18 2.01L6 2c-1.11 0-2 .89-2 2v16c0 1.11.89 2 2 2h12c1.11 0 2-.89 2-2V4c0-1.11-.89-1.99-2-1.99zM10 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM7 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm5 16c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/> </SvgIcon> ); MapsLocalLaundryService = pure(MapsLocalLaundryService); MapsLocalLaundryService.displayName = 'MapsLocalLaundryService'; MapsLocalLaundryService.muiName = 'SvgIcon'; export default MapsLocalLaundryService;
components/Animate/Circle.js
rdjpalmer/bloom
import PropTypes from 'prop-types'; import React from 'react'; import { Motion, spring } from 'react-motion'; import cx from 'classnames'; import css from './Circle.css'; const Circle = ({ percent }) => ( <svg className={ css.root } viewBox="0 0 34 34"> <circle className={ cx(css.circle, css.circleTrack) } cx="17" cy="17" r="15.9154943092"/> <Motion defaultStyle={ { x: 0, } } style={ { x: spring(percent, { stiffness: 35, damping: 10 }), } } > { ({ x }) => ( <circle className={ cx(css.circle, css.circleFilled) } cx="17" cy="17" r="15.9154943092" strokeDasharray={`${x}, 100`} /> ) } </Motion> </svg> ); Circle.propTypes = { percent: PropTypes.number, }; Circle.defaultProps = { percent: 0, }; export default Circle;
src/svg-icons/communication/live-help.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationLiveHelp = (props) => ( <SvgIcon {...props}> <path d="M19 2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-6 16h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 11.9 13 12.5 13 14h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/> </SvgIcon> ); CommunicationLiveHelp = pure(CommunicationLiveHelp); CommunicationLiveHelp.displayName = 'CommunicationLiveHelp'; CommunicationLiveHelp.muiName = 'SvgIcon'; export default CommunicationLiveHelp;
client/pages/Home/Home.js
jkettmann/universal-react-relay-starter-kit
import React from 'react' import PropTypes from 'prop-types' import { graphql } from 'react-relay' import { fragment } from 'relay-compose' import { compose, flattenProp } from 'recompose' import Wrapper from './Wrapper' const HomePage = ({ isLoggedIn }) => ( <Wrapper> <h1>Universal React Relay Starter Kit</h1> <div> You are currently {!isLoggedIn && 'not'} logged in. </div> </Wrapper> ) HomePage.propTypes = { isLoggedIn: PropTypes.bool.isRequired, } const enhance = compose( fragment(graphql` fragment Home on Query { permission { isLoggedIn } } `), flattenProp('data'), flattenProp('permission'), ) export default enhance(HomePage)
src/Shapes.js
rsamec/react-shapes
import React from 'react'; import _ from 'lodash'; import styleSvg from './utils/styleSvg'; export class SVGComponent extends React.Component { render() { return <svg {...this.props}>{this.props.children}</svg> } } export class Rectangle extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var height = (this.props.height || 0) + 2 * strokeWidth; var width = (this.props.width || 0) + 2 * strokeWidth; var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={height} width={width}> <rect {...props} x={strokeWidth / 2} y={strokeWidth / 2}>{this.props.children}</rect> </SVGComponent>) } } export class Circle extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var r = this.props.r || 0; var height = (r * 2) + 2 * strokeWidth; var width = (r * 2) + 2 * strokeWidth; var cx = r + (strokeWidth / 2); var cy = r + (strokeWidth / 2); var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={height} width={width}> <circle {...props} cx={cx} cy={cy}>{this.props.children}</circle> </SVGComponent>) } } export class Ellipse extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var rx = this.props.rx || 0; var ry = this.props.ry || 0; var height = (ry * 2) + 2 * strokeWidth; var width = (rx * 2) + 2 * strokeWidth; var cx = rx + (strokeWidth / 2); var cy = ry + (strokeWidth / 2); var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={height} width={width}> <ellipse {...props} cx={cx} cy={cy}>{this.props.children}</ellipse> </SVGComponent>) } } export class Line extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var x = _.max([this.props.x1, this.props.x2]); var y = _.max([this.props.y1, this.props.y2]); var height = y + (2 * strokeWidth); var width = x + (2 * strokeWidth); var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={height} width={width}> <line {...props}>{this.props.children}</line> </SVGComponent>) } } export class Polyline extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var points = _.map(this.props.points.split(' '),function(point){ var xy = point.split(','); return {x:parseInt(xy[0],10),y:parseInt(xy[1],10)}; }); var x = _.max(_.map(points,function(point){return point.x})); var y = _.max(_.map(points,function(point){return point.y})); var height = y + (2 * strokeWidth); var width = x + (2 * strokeWidth); var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={height} width={width}> <polyline {...props}>{this.props.children}</polyline> </SVGComponent>) } } export class Triangle extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var height = this.props.height || 0; var width = this.props.width || 0; var innerHeight = height - strokeWidth / 2; var innerWidth = width - strokeWidth / 2; var points = ['0,' + innerHeight, innerWidth / 2 + ',0', innerWidth + ',' + innerHeight]; var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={height + strokeWidth} width={width + strokeWidth}> <polygon transform={'translate(' + 3 * strokeWidth / 4 + ',' + 11 * strokeWidth / 10 + ')'} points={points.join(' ')} {...props}> {this.props.children} </polygon> </SVGComponent>) } } export class CornerLine extends React.Component { render() { var size = this.props.size || 150; var cornerWidth = this.props.width || 50; var strokeWidth = this.props.strokeWidth || 0; //var height = _.max([this.props.style.height, size]); //var width = _.max([this.props.style.width, size]); var max = size; var min = 0; var diff = max - cornerWidth; var up = this.props.up ? true : false; var point = up ? [[max, min], [min, max], [min, diff], [diff, min], [max, min]] : [[max, max], [min, min], [cornerWidth, min], [max, diff], [max, max]]; var points = _.reduce(point, function (memo, num) { return memo + " " + num[0] + "," + num[1]; }, ""); var text = this.props.text; var x = this.props.x || max; var y = this.props.y || max; var rotate = up ? 315 : 45; var transform = "rotate(" + rotate.toString() + ")"; var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <SVGComponent height={size} width={size}> <polyline points={points} {...props}></polyline> <text x={x} y={y} transform={transform}>{this.props.text}</text> </SVGComponent>) } } export class CornerBox extends React.Component { render() { var type = this.props.orientation; var up = (type === 'topLeft' || type === 'bottomRight') ? true : false; // var right = (type === 'topRight' || type == 'bottomRight')?true:false; var size = this.props.size; var cornerWidth = this.props.width; if (type === 'bottomLeft' || type === 'bottomRight') cornerWidth = -1 * cornerWidth; var offset = 20; var x = offset; var y = -1 * (cornerWidth / 2) if (up) { x = -1 * (cornerWidth / 2); y = size - offset; } var text = this.props.text; //var props = styleSvg(_.omit(this.props, 'style'),this.props); return ( <CornerLine {...this.props} size={this.props.size} width={cornerWidth} text={this.props.text} x={x} y={y} up={up}/>) } } export class Dimension extends React.Component { render() { var strokeWidth = this.props.strokeWidth || 0; var height = (this.props.height || 0) + 2 * strokeWidth; var width = (this.props.width || 0) + 2 * strokeWidth; //var viewBox = [0,0,20,20].join(' '); //var markerArrow = <marker viewBox={viewBox} id="markerArrow" markerWidth={5} markerHeight={5} // orient="auto"> // <path d="M2,2 L2,11 L10,6 L2,2" style={{fill: '#000000'}} /> //</marker>; //var markerSquare = <marker viewBox={viewBox} id="markerSquare" markerWidth={markerWidth} markerHeight={markerHeight} // orient="auto"> // <rect x="0" y="0" width={markerWidth} height={markerHeight} style={{stroke: 'none', fill:'#000000'}}/> //</marker>; var l = [strokeWidth,this.props.height]; var x = [strokeWidth,strokeWidth]; var y = [this.props.width,strokeWidth]; var r = [this.props.width,this.props.height]; var d= "M" + l.join(',') + " L" + x.join(',') + " L" + y.join(', ') + " L" + r.join(', '); //console.log(d); var props = styleSvg(_.omit(this.props, 'style'),this.props); var style = { strokeWidth: this.props.strokeWidth, fill:'none', stroke:this.props.stroke }; return ( <SVGComponent height={height} width={width}> <path {...props} style={style} d={d}></path> </SVGComponent>) } } var sharedFields = { fill: {type: 'colorPicker'}, stroke: {type: 'colorPicker'}, strokeWidth: {type: 'number'} } var sharedShapeMetaData = { defaultColors: { fill: {color:'#2409ba'}, stroke: {color:'#E65243'}, strokeWidth: 20 } } export default { SVGComponent: SVGComponent, Rectangle: _.extend(Rectangle, { metaData: { props: _.extend({ width: 500, height: 300 }, sharedShapeMetaData.defaultColors), settings:{fields:_.extend({ width:{type:'number'}, height:{type:'number'} },sharedFields)} } }), Circle: _.extend(Circle, { metaData: { props: _.extend({ r: 200 }, sharedShapeMetaData.defaultColors), settings:{fields:_.extend({ r:{type:'number'}, },sharedFields)} } }), Ellipse: _.extend(Ellipse, { metaData: { props: _.extend({ rx: 300, ry: 100 }, sharedShapeMetaData.defaultColors), settings:{fields:_.extend({ rx:{type:'number'}, ry:{type:'number'}, },sharedFields)} } }), Line: _.extend(Line, { metaData: { props: _.omit(_.extend({ x1: 25, y1: 25, x2: 350, y2: 350 }, sharedShapeMetaData.defaultColors),'fill'), settings:{fields:_.extend({ x1:{type:'number'}, y1:{type:'number'}, x2:{type:'number'}, y2:{type:'number'}, },sharedFields)} } }), Polyline: _.extend(Polyline, { metaData: { props: _.extend({ points: '25,25 25,350 500,350 500,500 305,250 20,15' }, sharedShapeMetaData.defaultColors), settings:{fields:sharedFields} } }), Triangle: _.extend(Triangle, { metaData: { props: _.extend({ width: 200, height: 200, }, sharedShapeMetaData.defaultColors), settings:{fields:_.extend({ width:{type:'number'}, height:{type:'number'} },sharedFields)} } }), CornerBox: _.extend(CornerBox, { metaData: { props: _.extend({ size: 400, width: 150, text: 'type your text', orientation: 'topLeft' }, sharedShapeMetaData.defaultColors), settings:{fields:_.extend({ width:{type:'number'}, size:{type:'number'}, orientation: { type: 'select', settings: {options: ['topRight', 'topLeft', 'bottomRight', 'bottomLeft']} } },sharedFields)} } }), CornerLine: _.extend(CornerLine, { metaData: { props: _.extend({ size: 150, width: 50, text: 'type your text', x: 25, y: 25, up: false, }, sharedShapeMetaData.defaultColors), settings: {fields:_.extend({ width:{type:'number'}, size:{type:'number'}, x:{type:'number'}, y:{type:'number'}, up:{type:'boolean'}, },sharedFields)} } }), Dimension: _.extend(Dimension, { metaData: { props: _.omit(_.extend({ width: 250, height:100, }, sharedShapeMetaData.defaultColors),'fill'), settings:{fields:_.extend({ width:{type:'number'}, height:{type:'number'}, },sharedFields)} } }), };
ajax/libs/yui/3.9.0pr2/scrollview-base/scrollview-base-debug.js
pvnr0082t/cdnjs
YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ var getClassName = Y.ClassNameManager.getClassName, DOCUMENT = Y.config.doc, IE = Y.UA.ie, NATIVE_TRANSITIONS = Y.Transition.useNative, vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated SCROLLVIEW = 'scrollview', CLASS_NAMES = { vertical: getClassName(SCROLLVIEW, 'vert'), horizontal: getClassName(SCROLLVIEW, 'horiz') }, EV_SCROLL_END = 'scrollEnd', FLICK = 'flick', DRAG = 'drag', MOUSEWHEEL = 'mousewheel', UI = 'ui', TOP = 'top', LEFT = 'left', PX = 'px', AXIS = 'axis', SCROLL_Y = 'scrollY', SCROLL_X = 'scrollX', BOUNCE = 'bounce', DISABLED = 'disabled', DECELERATION = 'deceleration', DIM_X = 'x', DIM_Y = 'y', BOUNDING_BOX = 'boundingBox', CONTENT_BOX = 'contentBox', GESTURE_MOVE = 'gesturemove', START = 'start', END = 'end', EMPTY = '', ZERO = '0s', SNAP_DURATION = 'snapDuration', SNAP_EASING = 'snapEasing', EASING = 'easing', FRAME_DURATION = 'frameDuration', BOUNCE_RANGE = 'bounceRange', _constrain = function (val, min, max) { return Math.min(Math.max(val, min), max); }; /** * ScrollView provides a scrollable widget, supporting flick gestures, * across both touch and mouse based devices. * * @class ScrollView * @param config {Object} Object literal with initial attribute values * @extends Widget * @constructor */ function ScrollView() { ScrollView.superclass.constructor.apply(this, arguments); } Y.ScrollView = Y.extend(ScrollView, Y.Widget, { // *** Y.ScrollView prototype /** * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit. * Used by the _transform method. * * @property _forceHWTransforms * @type boolean * @protected */ _forceHWTransforms: Y.UA.webkit ? true : false, /** * <p>Used to control whether or not ScrollView's internal * gesturemovestart, gesturemove and gesturemoveend * event listeners should preventDefault. The value is an * object, with "start", "move" and "end" properties used to * specify which events should preventDefault and which shouldn't:</p> * * <pre> * { * start: false, * move: true, * end: false * } * </pre> * * <p>The default values are set up in order to prevent panning, * on touch devices, while allowing click listeners on elements inside * the ScrollView to be notified as expected.</p> * * @property _prevent * @type Object * @protected */ _prevent: { start: false, move: true, end: false }, /** * Contains the distance (postive or negative) in pixels by which * the scrollview was last scrolled. This is useful when setting up * click listeners on the scrollview content, which on mouse based * devices are always fired, even after a drag/flick. * * <p>Touch based devices don't currently fire a click event, * if the finger has been moved (beyond a threshold) so this * check isn't required, if working in a purely touch based environment</p> * * @property lastScrolledAmt * @type Number * @public * @default 0 */ lastScrolledAmt: 0, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { var sv = this; // Cache these values, since they aren't going to change. sv._bb = sv.get(BOUNDING_BOX); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes sv._cAxis = sv.get(AXIS); sv._cBounce = sv.get(BOUNCE); sv._cBounceRange = sv.get(BOUNCE_RANGE); sv._cDeceleration = sv.get(DECELERATION); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { var sv = this; // Bind interaction listers sv._bindFlick(sv.get(FLICK)); sv._bindDrag(sv.get(DRAG)); sv._bindMousewheel(true); // Bind change events sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. if (IE) { sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties if (ScrollView.SNAP_DURATION) { sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } if (ScrollView.SNAP_EASING) { sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } if (ScrollView.EASING) { sv.set(EASING, ScrollView.EASING); } if (ScrollView.FRAME_STEP) { sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } if (ScrollView.BOUNCE_RANGE) { sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE); } // Recalculate dimension properties // TODO: This should be throttled. // Y.one(WINDOW).after('resize', sv._afterDimChange, sv); }, /** * Bind event listeners * * @method _bindAttrs * @private */ _bindAttrs: function () { var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners sv.after({ 'scrollEnd': sv._afterScrollEnd, 'disabledChange': sv._afterDisabledChange, 'flickChange': sv._afterFlickChange, 'dragChange': sv._afterDragChange, 'axisChange': sv._afterAxisChange, 'scrollYChange': scrollChangeHandler, 'scrollXChange': scrollChangeHandler, 'heightChange': dimChangeHandler, 'widthChange': dimChangeHandler }); }, /** * Bind (or unbind) gesture move listeners required for drag support * * @method _bindDrag * @param drag {boolean} If true, the method binds listener to enable * drag (gesturemovestart). If false, the method unbinds gesturemove * listeners for drag support. * @private */ _bindDrag: function (drag) { var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners bb.detach(DRAG + '|*'); if (drag) { bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv)); } }, /** * Bind (or unbind) flick listeners. * * @method _bindFlick * @param flick {Object|boolean} If truthy, the method binds listeners for * flick support. If false, the method unbinds flick listeners. * @private */ _bindFlick: function (flick) { var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners bb.detach(FLICK + '|*'); if (flick) { bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick sv._bindDrag(sv.get(DRAG)); } }, /** * Bind (or unbind) mousewheel listeners. * * @method _bindMousewheel * @param mousewheel {Object|boolean} If truthy, the method binds listeners for * mousewheel support. If false, the method unbinds mousewheel listeners. * @private */ _bindMousewheel: function (mousewheel) { var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv)); } }, /** * syncUI implementation. * * Update the scroll position, based on the current value of scrollX/scrollY. * * @method syncUI */ syncUI: function () { var sv = this, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight; // If the axis is undefined, auto-calculate it if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value sv._cDisabled = sv.get(DISABLED); // Run this to set initial values sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. if (sv._isOutOfBounds()) { sv._snapBack(); } }, /** * Utility method to obtain widget dimensions * * @method _getScrollDims * @return {Object} The offsetWidth, offsetHeight, scrollWidth and * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth, * scrollHeight] * @private */ _getScrollDims: function () { var sv = this, cb = sv._cb, bb = sv._bb, TRANS = ScrollView._TRANSITION, // Ideally using CSSMatrix - don't think we have it normalized yet though. // origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e, // origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f, origX = sv.get(SCROLL_X), origY = sv.get(SCROLL_Y), origHWTransform, dims; // TODO: Is this OK? Just in case it's called 'during' a transition. if (NATIVE_TRANSITIONS) { cb.setStyle(TRANS.DURATION, ZERO); cb.setStyle(TRANS.PROPERTY, EMPTY); } origHWTransform = sv._forceHWTransforms; sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. sv._moveTo(cb, 0, 0); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; sv._moveTo(cb, -(origX), -(origY)); sv._forceHWTransforms = origHWTransform; return dims; }, /** * This method gets invoked whenever the height or width attributes change, * allowing us to determine which scrolling axes need to be enabled. * * @method _uiDimensionsChange * @protected */ _uiDimensionsChange: function () { var sv = this, bb = sv._bb, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight, rtl = sv.rtl, svAxis = sv._cAxis; if (svAxis && svAxis.x) { bb.addClass(CLASS_NAMES.horizontal); } if (svAxis && svAxis.y) { bb.addClass(CLASS_NAMES.vertical); } /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ sv._minScrollX = (rtl) ? Math.min(0, -(scrollWidth - width)) : 0; /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ sv._maxScrollX = (rtl) ? 0 : Math.max(0, scrollWidth - width); /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ sv._minScrollY = 0; /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ sv._maxScrollY = Math.max(0, scrollHeight - height); }, /** * Scroll the element to a given xy coordinate * * @method scrollTo * @param x {Number} The x-position to scroll to. (null for no movement) * @param y {Number} The y-position to scroll to. (null for no movement) * @param {Number} [duration] ms of the scroll animation. (default is 0) * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute) * @param {String} [node] The node to transform. Setting this can be useful in * dual-axis paginated instances. (default is the instance's contentBox) */ scrollTo: function (x, y, duration, easing, node) { // Check to see if widget is disabled if (this._cDisabled) { return; } var sv = this, cb = sv._cb, TRANS = ScrollView._TRANSITION, callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this newX = 0, newY = 0, transition = {}, transform; // default the optional arguments duration = duration || 0; easing = easing || sv.get(EASING); // @TODO: Cache this node = node || cb; if (x !== null) { sv.set(SCROLL_X, x, {src:UI}); newX = -(x); } if (y !== null) { sv.set(SCROLL_Y, y, {src:UI}); newY = -(y); } transform = sv._transform(newX, newY); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move if (duration === 0) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', transform); } else { // TODO: If both set, batch them in the same update // Update: Nope, setStyles() just loops through each property and applies it. if (x !== null) { node.setStyle(LEFT, newX + PX); } if (y !== null) { node.setStyle(TOP, newY + PX); } } } // Animate else { transition.easing = easing; transition.duration = duration / 1000; if (NATIVE_TRANSITIONS) { transition.transform = transform; } else { transition.left = newX + PX; transition.top = newY + PX; } node.transition(transition, callback); } }, /** * Utility method, to create the translate transform string with the * x, y translation amounts provided. * * @method _transform * @param {Number} x Number of pixels to translate along the x axis * @param {Number} y Number of pixels to translate along the y axis * @private */ _transform: function (x, y) { // TODO: Would we be better off using a Matrix for this? var prop = 'translate(' + x + 'px, ' + y + 'px)'; if (this._forceHWTransforms) { prop += ' translateZ(0)'; } return prop; }, /** * Utility method, to move the given element to the given xy position * * @method _moveTo * @param node {Node} The node to move * @param x {Number} The x-position to move to * @param y {Number} The y-position to move to * @private */ _moveTo : function(node, x, y) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', this._transform(x, y)); } else { node.setStyle(LEFT, x + PX); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { var sv = this; /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ sv.fire(EV_SCROLL_END); }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { if (this._cDisabled) { return false; } var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; if (sv._prevent.start) { e.preventDefault(); } // if a flick animation is in progress, cancel it if (sv._flickAnim) { // Cancel and delete sv._flickAnim sv._flickAnim.cancel(); delete sv._flickAnim; sv._onTransEnd(); } // TODO: Review if neccesary (#2530129) e.stopPropagation(); // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later sv._gesture = { // Will hold the axis value axis: null, // The current attribute values startX: currentX, startY: currentY, // The X/Y coordinates where the event began startClientX: clientX, startClientY: clientY, // The X/Y coordinates where the event will end endClientX: null, endClientY: null, // The current delta of the event deltaX: null, deltaY: null, // Will be populated for flicks flick: null, // Create some listeners for the rest of the gesture cycle onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)), // @TODO: Don't bind gestureMoveEnd if it's a Flick? onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv)) }; }, /** * gesturemove event handler * * @method _onGestureMove * @param e {Event.Facade} The gesturemove event facade * @private */ _onGestureMove: function (e) { var sv = this, gesture = sv._gesture, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, startX = gesture.startX, startY = gesture.startY, startClientX = gesture.startClientX, startClientY = gesture.startClientY, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.move) { e.preventDefault(); } gesture.deltaX = startClientX - clientX; gesture.deltaY = startClientY - clientY; // Determine if this is a vertical or horizontal movement // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent if (gesture.axis === null) { gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. if (gesture.axis === DIM_X && svAxisX) { sv.set(SCROLL_X, startX + gesture.deltaX); } else if (gesture.axis === DIM_Y && svAxisY) { sv.set(SCROLL_Y, startY + gesture.deltaY); } }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.end) { e.preventDefault(); } // Store the end X/Y coordinates gesture.endClientX = clientX; gesture.endClientY = clientY; // Cleanup the event handlers gesture.onGestureMove.detach(); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle if (!flick) { // @TODO: Be more intelligent about this. Look at the Flick attribute to see // if it is safe to assume _flick did or didn't fire. // Then, the order _flick and _onGestureMoveEnd fire doesn't matter? // If there was movement (_onGestureMove fired) if (gesture.deltaX !== null && gesture.deltaY !== null) { // If we're out-out-bounds, then snapback if (sv._isOutOfBounds()) { sv._snapBack(); } // Inbounds else { // Don't fire scrollEnd on the gesture axis is the same as paginator's // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit if (sv.pages && !sv.pages.get(AXIS)[gesture.axis]) { sv._onTransEnd(); } } } } }, /** * Execute a flick at the end of a scroll action * * @method _flick * @param e {Event.Facade} The Flick event facade * @private */ _flick: function (e) { if (this._cDisabled) { return false; } var sv = this, svAxis = sv._cAxis, flick = e.flick, flickAxis = flick.axis, flickVelocity = flick.velocity, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, startPosition = sv.get(axisAttr); // Sometimes flick is enabled, but drag is disabled if (sv._gesture) { sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis if (svAxis[flickAxis]) { sv._flickFrame(flickVelocity, flickAxis, startPosition); } }, /** * Execute a single frame in the flick animation * * @method _flickFrame * @param velocity {Number} The velocity of this animated frame * @param flickAxis {String} The axis on which to animate * @param startPosition {Number} The starting X/Y point to flick from * @protected */ _flickFrame: function (velocity, flickAxis, startPosition) { var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, // Localize cached values bounce = sv._cBounce, bounceRange = sv._cBounceRange, deceleration = sv._cDeceleration, frameDuration = sv._cFrameDuration, // Calculate newVelocity = velocity * deceleration, newPosition = startPosition - (frameDuration * newVelocity), // Some convinience conditions min = flickAxis === DIM_X ? sv._minScrollX : sv._minScrollY, max = flickAxis === DIM_X ? sv._maxScrollX : sv._maxScrollY, belowMin = (newPosition < min), belowMax = (newPosition < max), aboveMin = (newPosition > min), aboveMax = (newPosition > max), belowMinRange = (newPosition < (min - bounceRange)), withinMinRange = (belowMin && (newPosition > (min - bounceRange))), withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))), aboveMaxRange = (newPosition > (max + bounceRange)), tooSlow; // If we're within the range but outside min/max, dampen the velocity if (withinMinRange || withinMaxRange) { newVelocity *= bounce; } // Is the velocity too slow to bother? tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim if (sv._flickAnim) { sv._flickAnim.cancel(); delete sv._flickAnim; } // If we're inside the scroll area, just end if (aboveMin && belowMax) { sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); sv.set(axisAttr, newPosition); } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { var sv = this, scrollY = sv.get(SCROLL_Y), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); scrollToY = _constrain(scrollToY, sv._minScrollY, sv._maxScrollY); // Because Mousewheel events fire off 'document', every ScrollView widget will react // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis, // becuase otherwise the 'prevent' will block page scrolling. if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Jump to the new offset sv.set(SCROLL_Y, scrollToY); // if we have scrollbars plugin, update & set the flash timer on the scrollbar // @TODO: This probably shouldn't be in this module if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves sv.scrollbars._update(); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event sv._onTransEnd(); // prevent browser default behavior on mouse scroll e.preventDefault(); } }, /** * Checks to see the current scrollX/scrollY position beyond the min/max boundary * * @method _isOutOfBounds * @param x {Number} [optional] The X position to check * @param y {Number} [optional] The Y position to check * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false) * @private */ _isOutOfBounds: function (x, y) { var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), minX = sv._minScrollX, minY = sv._minScrollY, maxX = sv._maxScrollX, maxY = sv._maxScrollY; return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY)); }, /** * Bounces back * @TODO: Should be more generalized and support both X and Y detection * * @method _snapBack * @private */ _snapBack: function () { var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), minX = sv._minScrollX, minY = sv._minScrollY, maxX = sv._maxScrollX, maxY = sv._maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); if (newX !== currentX) { sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else if (newY !== currentY) { sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { // It shouldn't ever get here, but in case it does, fire scrollEnd sv._onTransEnd(); } }, /** * After listener for changes to the scrollX or scrollY attribute * * @method _afterScrollChange * @param e {Event.Facade} The event facade * @protected */ _afterScrollChange: function (e) { if (e.src === ScrollView.UI_SRC) { return false; } var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() if (e.attrName === SCROLL_X) { scrollToArgs.push(val); scrollToArgs.push(sv.get(SCROLL_Y)); } else { scrollToArgs.push(sv.get(SCROLL_X)); scrollToArgs.push(val); } scrollToArgs.push(duration); scrollToArgs.push(easing); sv.scrollTo.apply(sv, scrollToArgs); }, /** * After listener for changes to the flick attribute * * @method _afterFlickChange * @param e {Event.Facade} The event facade * @protected */ _afterFlickChange: function (e) { this._bindFlick(e.newVal); }, /** * After listener for changes to the disabled attribute * * @method _afterDisabledChange * @param e {Event.Facade} The event facade * @protected */ _afterDisabledChange: function (e) { // Cache for performance - we check during move this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { this._cAxis = e.newVal; }, /** * After listener for changes to the drag attribute * * @method _afterDragChange * @param e {Event.Facade} The event facade * @protected */ _afterDragChange: function (e) { this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { var sv = this; // @TODO: Move to sv._cancelFlick() if (sv._flickAnim) { // Cancel the flick (if it exists) sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking delete sv._flickAnim; } // If for some reason we're OOB, snapback if (sv._isOutOfBounds()) { sv._snapBack(); } // Ideally this should be removed, but doing so causing some JS errors with fast swiping // because _gesture is being deleted after the previous one has been overwritten // delete sv._gesture; // TODO: Move to sv.prevGesture? }, /** * Setter for 'axis' attribute * * @method _axisSetter * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on * @param name {String} The attribute name * @return {Object} An object to specify scrollability on the x & y axes * * @protected */ _axisSetter: function (val) { // Turn a string into an axis object if (Y.Lang.isString(val)) { return { x: val.match(/x/i) ? true : false, y: val.match(/y/i) ? true : false }; } }, /** * The scrollX, scrollY setter implementation * * @method _setScroll * @private * @param {Number} val * @param {String} dim * * @return {Number} The value */ _setScroll : function(val) { // Just ensure the widget is not disabled if (this._cDisabled) { val = Y.Attribute.INVALID_VALUE; } return val; }, /** * Setter for the scrollX attribute * * @method _setScrollX * @param val {Number} The new scrollX value * @return {Number} The normalized value * @protected */ _setScrollX: function(val) { return this._setScroll(val, DIM_X); }, /** * Setter for the scrollY ATTR * * @method _setScrollY * @param val {Number} The new scrollY value * @return {Number} The normalized value * @protected */ _setScrollY: function(val) { return this._setScroll(val, DIM_Y); } // End prototype properties }, { // Static properties /** * The identity of the widget. * * @property NAME * @type String * @default 'scrollview' * @readOnly * @protected * @static */ NAME: 'scrollview', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Specifies ability to scroll on x, y, or x and y axis/axes. * * @attribute axis * @type String */ axis: { setter: '_axisSetter', writeOnce: 'initOnly' }, /** * The current scroll position in the x-axis * * @attribute scrollX * @type Number * @default 0 */ scrollX: { value: 0, setter: '_setScrollX' }, /** * The current scroll position in the y-axis * * @attribute scrollY * @type Number * @default 0 */ scrollY: { value: 0, setter: '_setScrollY' }, /** * Drag coefficent for inertial scrolling. The closer to 1 this * value is, the less friction during scrolling. * * @attribute deceleration * @default 0.93 */ deceleration: { value: 0.93 }, /** * Drag coefficient for intertial scrolling at the upper * and lower boundaries of the scrollview. Set to 0 to * disable "rubber-banding". * * @attribute bounce * @type Number * @default 0.1 */ bounce: { value: 0.1 }, /** * The minimum distance and/or velocity which define a flick. Can be set to false, * to disable flick support (note: drag support is enabled/disabled separately) * * @attribute flick * @type Object * @default Object with properties minDistance = 10, minVelocity = 0.3. */ flick: { value: { minDistance: 10, minVelocity: 0.3 } }, /** * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately) * @attribute drag * @type boolean * @default true */ drag: { value: true }, /** * The default duration to use when animating the bounce snap back. * * @attribute snapDuration * @type Number * @default 400 */ snapDuration: { value: 400 }, /** * The default easing to use when animating the bounce snap back. * * @attribute snapEasing * @type String * @default 'ease-out' */ snapEasing: { value: 'ease-out' }, /** * The default easing used when animating the flick * * @attribute easing * @type String * @default 'cubic-bezier(0, 0.1, 0, 1.0)' */ easing: { value: 'cubic-bezier(0, 0.1, 0, 1.0)' }, /** * The interval (ms) used when animating the flick for JS-timer animations * * @attribute frameDuration * @type Number * @default 15 */ frameDuration: { value: 15 }, /** * The default bounce distance in pixels * * @attribute bounceRange * @type Number * @default 150 */ bounceRange: { value: 150 } }, /** * List of class names used in the scrollview's DOM * * @property CLASS_NAMES * @type Object * @static */ CLASS_NAMES: CLASS_NAMES, /** * Flag used to source property changes initiated from the DOM * * @property UI_SRC * @type String * @static * @default 'ui' */ UI_SRC: UI, /** * Object map of style property names used to set transition properties. * Defaults to the vendor prefix established by the Transition module. * The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and * `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty"). * * @property _TRANSITION * @private */ _TRANSITION: { DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'), PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty') }, /** * The default bounce distance in pixels * * @property BOUNCE_RANGE * @type Number * @static * @default false * @deprecated (in 3.7.0) */ BOUNCE_RANGE: false, /** * The interval (ms) used when animating the flick * * @property FRAME_STEP * @type Number * @static * @default false * @deprecated (in 3.7.0) */ FRAME_STEP: false, /** * The default easing used when animating the flick * * @property EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ EASING: false, /** * The default easing to use when animating the bounce snap back. * * @property SNAP_EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ SNAP_EASING: false, /** * The default duration to use when animating the bounce snap back. * * @property SNAP_DURATION * @type Number * @static * @default false * @deprecated (in 3.7.0) */ SNAP_DURATION: false // End static properties }); }, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
lib/Types/WrapList.js
lemonCMS/redux-form-generator
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "prop-types", "react", "lodash/has", "lodash/map", "lodash/get", "lodash/chunk", "lodash/filter", "lodash/includes", "react-bootstrap/lib/Col", "react-bootstrap/lib/Row", "react-bootstrap/lib/FormControl", "react-bootstrap/lib/Alert", "react-bootstrap/lib/FormGroup", "react-bootstrap/lib/ControlLabel", "react-bootstrap/lib/HelpBlock", "react-bootstrap/lib/Radio", "lodash/isFunction"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("prop-types"), require("react"), require("lodash/has"), require("lodash/map"), require("lodash/get"), require("lodash/chunk"), require("lodash/filter"), require("lodash/includes"), require("react-bootstrap/lib/Col"), require("react-bootstrap/lib/Row"), require("react-bootstrap/lib/FormControl"), require("react-bootstrap/lib/Alert"), require("react-bootstrap/lib/FormGroup"), require("react-bootstrap/lib/ControlLabel"), require("react-bootstrap/lib/HelpBlock"), require("react-bootstrap/lib/Radio"), require("lodash/isFunction")); } else { var mod = { exports: {} }; factory(mod.exports, global.propTypes, global.react, global.has, global.map, global.get, global.chunk, global.filter, global.includes, global.Col, global.Row, global.FormControl, global.Alert, global.FormGroup, global.ControlLabel, global.HelpBlock, global.Radio, global.isFunction); global.WrapList = mod.exports; } })(this, function (_exports, _propTypes, _react, _has2, _map2, _get2, _chunk2, _filter2, _includes2, _Col, _Row, _FormControl, _Alert, _FormGroup, _ControlLabel, _HelpBlock, _Radio, _isFunction2) { "use strict"; _exports.__esModule = true; _exports["default"] = void 0; _propTypes = _interopRequireDefault(_propTypes); _react = _interopRequireDefault(_react); _has2 = _interopRequireDefault(_has2); _map2 = _interopRequireDefault(_map2); _get2 = _interopRequireDefault(_get2); _chunk2 = _interopRequireDefault(_chunk2); _filter2 = _interopRequireDefault(_filter2); _includes2 = _interopRequireDefault(_includes2); _Col = _interopRequireDefault(_Col); _Row = _interopRequireDefault(_Row); _FormControl = _interopRequireDefault(_FormControl); _Alert = _interopRequireDefault(_Alert); _FormGroup = _interopRequireDefault(_FormGroup); _ControlLabel = _interopRequireDefault(_ControlLabel); _HelpBlock = _interopRequireDefault(_HelpBlock); _Radio = _interopRequireDefault(_Radio); _isFunction2 = _interopRequireDefault(_isFunction2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var WrapList = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(WrapList, _React$Component); function WrapList() { var _this; _this = _React$Component.call(this) || this; _this.renderField = _this.renderField.bind(_assertThisInitialized(_this)); _this.handlePrevent = _this.handlePrevent.bind(_assertThisInitialized(_this)); _this.handleChange = _this.handleChange.bind(_assertThisInitialized(_this)); _this.filtered = _this.filtered.bind(_assertThisInitialized(_this)); _this.radioButtons = _this.radioButtons.bind(_assertThisInitialized(_this)); _this.radioButtonList = _this.radioButtonList.bind(_assertThisInitialized(_this)); _this.searchBox = _this.searchBox.bind(_assertThisInitialized(_this)); _this.state = { value: '', selected: [] }; _this.input = {}; return _this; } var _proto = WrapList.prototype; _proto.filtered = function filtered(options) { if (this.props["static"] === true || (0, _get2["default"])(this.props.field, 'static', false) === true) { return (0, _filter2["default"])(this.props.field.options, { value: this.input.value }); } var value = this.state.value; var strValue = String(value).toLowerCase(); if (value !== '') { return (0, _filter2["default"])(options, function (option) { return (0, _includes2["default"])(String(option.desc).toLowerCase(), strValue); }); } return options; }; _proto.radioButtonList = function radioButtonList(list) { var _this2 = this; var staticField = this.props["static"] || (0, _get2["default"])(this.props.field, 'static', false); return (0, _map2["default"])(list, function (option, key) { if (staticField === true) { return _react["default"].createElement(_FormControl["default"].Static, { key: key }, option.desc); } var disabled = false; if (_this2.props.field && _this2.props.field.disabled && (0, _isFunction2["default"])(_this2.props.field.disabled)) { disabled = _this2.props.checkDisabled(_this2.props.field.disabled(), (0, _get2["default"])(_this2.props.field, 'parent')); } return _react["default"].createElement(_Radio["default"], { key: key, disabled: disabled, name: _this2.input.name + "[" + key + "]", value: option.value, checked: String(_this2.input.value) === String(option.value), onChange: function onChange(event) { if (event.target.checked) { return _this2.input.onChange(option.value); } } }, option.desc); }); }; _proto.radioButtons = function radioButtons() { var _this3 = this; var filtered = this.filtered((0, _get2["default"])(this.props.field, 'options', [])); var field = (0, _get2["default"])(this.props, 'field'); if (filtered.length === 0) { return _react["default"].createElement(_Alert["default"], null, (0, _get2["default"])(this.props.field, 'filter_norecords', (0, _get2["default"])(this.props.locale, 'filter.norecords', 'No results'))); } if (field.chunks) { var split = Math.ceil(filtered.length / field.chunks); var chunks = function chunks() { var chunkData = (0, _chunk2["default"])(filtered, split); return (0, _map2["default"])(chunkData, function (chunk, key) { return _react["default"].createElement(_Col["default"], { key: key, md: Math.round(12 / field.chunks) }, _this3.radioButtonList(chunk)); }); }; return _react["default"].createElement(_Row["default"], null, chunks()); } return this.radioButtonList(filtered); }; _proto.searchBox = function searchBox() { var disabled = false; if (this.props.field && this.props.field.disabled && (0, _isFunction2["default"])(this.props.field.disabled)) { disabled = this.props.checkDisabled(this.props.field.disabled()); } if ((!!this.props.field.searchable || this.props.field.filter) && !this.props["static"]) { return _react["default"].createElement("input", { type: "text", disabled: disabled, placeholder: (0, _get2["default"])(this.props.field, 'filter_placeholder', (0, _get2["default"])(this.props.locale, 'filter.placeholder', 'Filter')), defaultValue: this.state.value, onKeyDown: this.handlePrevent, onKeyUp: this.handleChange, className: "form-control" }); } }; _proto.handlePrevent = function handlePrevent(e) { if (e.keyCode === 13) { e.preventDefault(); e.stopPropagation(); } }; _proto.handleChange = function handleChange(e) { if (e.keyCode === 13) { e.preventDefault(); e.stopPropagation(); } this.setState({ value: e.target.value }); }; _proto.renderField = function renderField(props) { var _this4 = this; if (this.props.field && this.props.field.hidden && (0, _isFunction2["default"])(this.props.field.hidden)) { if (this.props.checkHidden(this.props.field.hidden, (0, _get2["default"])(props, 'parent')) === true) { return null; } } else if (this.props.field && this.props.field.show && (0, _isFunction2["default"])(this.props.field.show)) { if (this.props.checkShow(this.props.field.show, (0, _get2["default"])(props, 'parent')) !== true) { return null; } } var input = props.input, label = props.label, help = props.help, _props$meta = props.meta, touched = _props$meta.touched, error = _props$meta.error, valid = _props$meta.valid; this.input = input; var size = (0, _get2["default"])(this.props.field, 'bsSize', this.props.size); var thisSize = function thisSize() { if (size !== 'medium') { return { bsSize: size }; } }; var labelSize = function labelSize() { if ((0, _has2["default"])(_this4.props.field, 'labelSize')) { return _this4.props.field.labelSize; } if (_this4.props.horizontal) { return { sm: 2 }; } }; var fieldSize = function fieldSize() { if ((0, _has2["default"])(_this4.props.field, 'fieldSize')) { return _this4.props.field.fieldSize; } if (_this4.props.horizontal) { return { sm: 10 }; } }; var validationState = function validationState() { if (touched && error) { return 'error'; } if (touched && valid) { return 'success'; } }; var getLabel = function getLabel() { if (label) { return _react["default"].createElement(_Col["default"], _extends({ componentClass: _ControlLabel["default"] }, labelSize()), label); } }; return _react["default"].createElement(_FormGroup["default"], _extends({}, thisSize(), { validationState: validationState() }), getLabel(), _react["default"].createElement(_Col["default"], _extends({}, fieldSize(), { className: (0, _get2["default"])(this.props.field, 'fieldClassName', '') }), this.searchBox(), _react["default"].createElement("div", { className: 'rdf-radiolist' }, this.radioButtons()), touched && error && _react["default"].createElement(_FormControl["default"].Feedback, null), help && (!touched || !error) && _react["default"].createElement(_HelpBlock["default"], null, help), touched && error && _react["default"].createElement(_HelpBlock["default"], null, error))); }; _proto.render = function render() { return null; }; return WrapList; }(_react["default"].Component); WrapList.propTypes = { 'checkDisabled': _propTypes["default"].func, 'checkHidden': _propTypes["default"].func, 'checkShow': _propTypes["default"].func, 'field': _propTypes["default"].object, 'size': _propTypes["default"].string, 'static': _propTypes["default"].bool, 'locale': _propTypes["default"].object, 'horizontal': _propTypes["default"].bool.isRequired }; WrapList.defaultProps = {}; var _default = WrapList; _exports["default"] = _default; });
docs/src/app/app.js
pradel/material-ui
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, useRouterHistory} from 'react-router'; import AppRoutes from './AppRoutes'; import injectTapEventPlugin from 'react-tap-event-plugin'; import {createHashHistory} from 'history'; // Helpers for debugging window.React = React; window.Perf = require('react-addons-perf'); // Needed for onTouchTap // Can go away when react 1.0 release // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); /** * Render the main app component. You can read more about the react-router here: * https://github.com/rackt/react-router/blob/master/docs/guides/overview.md */ ReactDOM.render( <Router history={useRouterHistory(createHashHistory)({queryKey: false})} onUpdate={() => window.scrollTo(0, 0)} > {AppRoutes} </Router> , document.getElementById('app'));
WebRoot/js/jquery.js
liaochente/tm
/*! jQuery v1.7.1 jquery.com | jquery.org/license */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return ( new Date() ).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!memory; } }; return self; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, marginDiv, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = marginDiv = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, conMarginTop, ptlm, vb, style, html, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; vb = "visibility:hidden;border:0;"; style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; html = "<div " + style + "><div></div></div>" + "<table " + style + " cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Figure out if the W3C box model works as expected div.innerHTML = ""; div.style.width = div.style.paddingLeft = "1px"; jQuery.boxModel = support.boxModel = div.offsetWidth === 2; if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.style.cssText = ptlm + vb; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); body.removeChild( container ); div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, attr, name, data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { attr = this[0].attributes; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } jQuery._data( this[0], "parsedAttrs", true ); } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var self = jQuery( this ), args = [ parts[0], value ]; self.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { for ( var name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; // See #9699 for explanation of this approach (setting first, then removal) jQuery.attr( elem, name, "" ); elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /\bhover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Determine handlers that should run if there are delegated events // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { // If form was submitted by the user, bubble the event up the tree if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; jQuery.event.simulate( "change", this, event, true ); } }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on.call( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( var type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; var cur = a.nextSibling; } while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery.clean( arguments ); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^([\-+])=([\-+.\de]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret === null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ( ret || 0 ); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight, i = 0, len = which.length; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i++ ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i++ ) { val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } } } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css(elem, "display") === "none" ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any flash of content if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); } // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom( this.cur(), 0 ); }, // Each step of an animation step: function( gotoEnd ) { var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Adds width/height step functions // Do not set anything below 0 jQuery.each([ "width", "height" ], function( i, prop ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
clients/packages/admin-client/src/ux/components/div-float/index.spec.js
nossas/bonde-client
/** * @jest-environment jsdom */ import React from 'react'; import { expect } from 'chai'; import { mount } from 'enzyme'; import DivFloat from '../../../ux/components/div-float'; describe('client/ux/components/div-float', () => { let floatLayout; beforeEach(() => { floatLayout = mount(<DivFloat />); }); it('should render children', () => { const floatLayout = mount( <DivFloat> <a href="http://localhost" /> </DivFloat> ); expect(floatLayout.find('a').length).to.equal(1); }); it('should render by default top and right position', () => { expect(floatLayout.props().horizontal).to.equal('right'); expect(floatLayout.props().vertical).to.equal('top'); }); it('should change className when change horizontal props', () => { floatLayout.setProps({ horizontal: 'left' }); expect(floatLayout.find('div').props().className).to.contains('left'); }); it('should change className when change vertical props', () => { floatLayout.setProps({ vertical: 'bottom' }); expect(floatLayout.find('div').props().className).to.contains('bottom'); }); });
examples/websdk-samples/LayerReactNativeSample/src/ui/messages/QuoteMessagePart.js
layerhq/layer-js-sampleapps
import React, { Component } from 'react'; import { StyleSheet, View, Text } from 'react-native'; export default class QuoteMessagePart extends Component { render() { return ( <View style={styles.container}> <Text style={styles.messageText}>{'"' + this.props.messagePart.body + '"'}</Text> </View> ) } } const styles = StyleSheet.create({ container: { paddingVertical: 12, paddingHorizontal: 12, borderRadius: 15, backgroundColor: 'rgba(240, 240, 240, 1.0)', borderColor: 'rgba(25, 165, 228, 1.0)', borderWidth: 2 }, messageText: { color: 'black', fontStyle: 'italic' } });
src/utils/stylePropable.js
rscnt/material-ui
import React from 'react'; import warning from 'warning'; let hasWarned; const warn = () => { warning(hasWarned, 'The \'material-ui/lib/mixins/style-propable.js\' mixin has been deprecated.' + ' Please do not use this mixin as it will be removed in an upcoming release.'); hasWarned = true; }; export const mergeStyles = (...args) => { warn(); return Object.assign({}, ...args); }; export default { propTypes: { style: React.PropTypes.object, }, mergeStyles, prepareStyles(...args) { warn(); const { prepareStyles = (style) => (style), } = (this.state && this.state.muiTheme) || (this.context && this.context.muiTheme) || (this.props && this.props.muiTheme) || {}; return prepareStyles(mergeStyles(...args)); }, componentWillMount() { warn(); }, };
examples/with-clerk/pages/index.js
azukaru/next.js
import React from 'react' import Head from 'next/head' import Link from 'next/link' import styles from '../styles/Home.module.css' import { SignedIn, SignedOut } from '@clerk/nextjs' const ClerkFeatures = () => ( <Link href="/user"> <a className={styles.cardContent}> <img src="/icons/layout.svg" /> <div> <h3>Explore features provided by Clerk</h3> <p> Interact with the user button, user profile, and more to preview what your users will see </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> ) const SignupLink = () => ( <Link href="/sign-up"> <a className={styles.cardContent}> <img src="/icons/user-plus.svg" /> <div> <h3>Sign up for an account</h3> <p> Sign up and sign in to explore all the features provided by Clerk out-of-the-box </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> ) const apiSample = `import { withSession } from '@clerk/nextjs/api' export default withSession((req, res) => { res.statusCode = 200 if (req.session) { res.json({ id: req.session.userId }) } else { res.json({ id: null }) } })` // Main component using <SignedIn> & <SignedOut>. // // The SignedIn and SignedOut components are used to control rendering depending // on whether or not a visitor is signed in. // // https://docs.clerk.dev/frontend/react/signedin-and-signedout const Main = () => ( <main className={styles.main}> <h1 className={styles.title}>Welcome to your new app</h1> <p className={styles.description}>Sign up for an account to get started</p> <div className={styles.cards}> <div className={styles.card}> <SignedIn> <ClerkFeatures /> </SignedIn> <SignedOut> <SignupLink /> </SignedOut> </div> <div className={styles.card}> <Link href="https://dashboard.clerk.dev"> <a target="_blank" rel="noreferrer" className={styles.cardContent}> <img src="/icons/settings.svg" /> <div> <h3>Configure settings for your app</h3> <p> Visit Clerk to manage instances and configure settings for user management, theme, and more </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> </div> </div> <APIRequest /> <div className={styles.links}> <Link href="https://docs.clerk.dev"> <a target="_blank" rel="noreferrer" className={styles.link}> <span className={styles.linkText}>Read Clerk documentation</span> </a> </Link> <Link href="https://nextjs.org/docs"> <a target="_blank" rel="noreferrer" className={styles.link}> <span className={styles.linkText}>Read NextJS documentation</span> </a> </Link> </div> </main> ) const APIRequest = () => { React.useEffect(() => { if (window.Prism) { window.Prism.highlightAll() } }) const [response, setResponse] = React.useState( '// Click above to run the request' ) const makeRequest = async () => { setResponse('// Loading...') try { const res = await fetch('/api/getAuthenticatedUserId') const body = await res.json() setResponse(JSON.stringify(body, null, ' ')) } catch (e) { setResponse( '// There was an error with the request. Please contact [email protected]' ) } } return ( <div className={styles.backend}> <h2>API request example</h2> <div className={styles.card}> <button target="_blank" rel="noreferrer" className={styles.cardContent} onClick={() => makeRequest()} > <img src="/icons/server.svg" /> <div> <h3>fetch('/api/getAuthenticatedUserId')</h3> <p> Retrieve the user ID of the signed in user, or null if there is no user </p> </div> <div className={styles.arrow}> <img src="/icons/download.svg" /> </div> </button> </div> <h4> Response <em> <SignedIn> You are signed in, so the request will return your user ID </SignedIn> <SignedOut> You are signed out, so the request will return null </SignedOut> </em> </h4> <pre> <code className="language-js">{response}</code> </pre> <h4>pages/api/getAuthenticatedUserId.js</h4> <pre> <code className="language-js">{apiSample}</code> </pre> </div> ) } // Footer component const Footer = () => ( <footer className={styles.footer}> Powered by{' '} <a href="https://clerk.dev" target="_blank" rel="noopener noreferrer"> <img src="/clerk.svg" alt="Clerk.dev" className={styles.logo} /> </a> + <a href="https://nextjs.org/" target="_blank" rel="noopener noreferrer"> <img src="/nextjs.svg" alt="Next.js" className={styles.logo} /> </a> </footer> ) const Home = () => ( <div className={styles.container}> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" ></meta> </Head> <Main /> <Footer /> </div> ) export default Home
src/platform/startup/tests/react.unit.spec.js
department-of-veterans-affairs/vets-website
import React from 'react'; import ReactDOM from 'react-dom'; import sinon from 'sinon'; import { expect } from 'chai'; import startReactApp from '../react'; const FakeWidget = () => <div id="fake-widget">Widget</div>; describe('startReactApp', () => { let renderStub; let sandbox; let reactRoot; let widgetRoot; beforeEach(() => { sandbox = sinon.createSandbox(); renderStub = sandbox.stub(ReactDOM, 'render').resolves(() => {}); reactRoot = document.createElement('div'); reactRoot.setAttribute('id', 'react-root'); document.body.appendChild(reactRoot); widgetRoot = document.createElement('div'); widgetRoot.setAttribute('id', 'widget-root'); document.body.appendChild(widgetRoot); }); afterEach(() => { sandbox.restore(); renderStub.restore(); document.body.removeChild(reactRoot); document.body.removeChild(widgetRoot); }); it('should render the component to #react-root when root argument is not provided', () => { startReactApp(FakeWidget); expect(renderStub.calledWith(FakeWidget, reactRoot)).to.be.true; }); it('should render the component to the provided root argument when it exists', () => { startReactApp(FakeWidget, document.getElementById('widget-root')); expect(renderStub.calledWith(FakeWidget, widgetRoot)).to.be.true; }); it('should not render the component if the provided root argument does not exist', () => { startReactApp(FakeWidget, document.getElementById('another-widget-root')); expect(renderStub.called).to.be.false; }); });
ajax/libs/js-data/1.5.8/js-data-debug.js
davidbau/cdnjs
/*! * js-data * @version 1.5.8 - Homepage <http://www.js-data.io/> * @author Jason Dobry <[email protected]> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else if(typeof define === 'function' && define.amd) define(["bluebird", "js-data-schema"], factory); else if(typeof exports === 'object') exports["JSData"] = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else root["JSData"] = factory(root["bluebird"], root["Schemator"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var DS = _interopRequire(__webpack_require__(3)); module.exports = { DS: DS, createStore: function createStore(options) { return new DS(options); }, DSUtils: DSUtils, DSErrors: DSErrors, version: { full: "1.5.8", major: parseInt("1", 10), minor: parseInt("5", 10), patch: parseInt("8", 10), alpha: true ? "false" : false, beta: true ? "false" : false } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; /* jshint eqeqeq:false */ var DSErrors = _interopRequire(__webpack_require__(2)); var forEach = _interopRequire(__webpack_require__(9)); var slice = _interopRequire(__webpack_require__(10)); var forOwn = _interopRequire(__webpack_require__(14)); var contains = _interopRequire(__webpack_require__(11)); var deepMixIn = _interopRequire(__webpack_require__(15)); var pascalCase = _interopRequire(__webpack_require__(19)); var remove = _interopRequire(__webpack_require__(12)); var pick = _interopRequire(__webpack_require__(16)); var sort = _interopRequire(__webpack_require__(13)); var upperCase = _interopRequire(__webpack_require__(20)); var observe = _interopRequire(__webpack_require__(6)); var es6Promise = _interopRequire(__webpack_require__(21)); var BinaryHeap = _interopRequire(__webpack_require__(22)); var w = undefined, _Promise = undefined; var DSUtils = undefined; var objectProto = Object.prototype; var toString = objectProto.toString; es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == "[object Array]" || false; }; var isRegExp = function (value) { return toString.call(value) == "[object RegExp]" || false; }; // adapted from lodash.isBoolean var isBoolean = function (value) { return value === true || value === false || value && typeof value == "object" && toString.call(value) == "[object Boolean]" || false; }; // adapted from lodash.isString var isString = function (value) { return typeof value == "string" || value && typeof value == "object" && toString.call(value) == "[object String]" || false; }; var isObject = function (value) { return toString.call(value) == "[object Object]" || false; }; // adapted from lodash.isDate var isDate = function (value) { return value && typeof value == "object" && toString.call(value) == "[object Date]" || false; }; // adapted from lodash.isNumber var isNumber = function (value) { var type = typeof value; return type == "number" || value && type == "object" && toString.call(value) == "[object Number]" || false; }; // adapted from lodash.isFunction var isFunction = function (value) { return typeof value == "function" || value && toString.call(value) === "[object Function]" || false; }; // shorthand argument checking functions, using these shaves 1.18 kb off of the minified build var isStringOrNumber = function (value) { return isString(value) || isNumber(value); }; var isStringOrNumberErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be a string or a number!"); }; var isObjectErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an object!"); }; var isArrayErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an array!"); }; // adapted from mout.isEmpty var isEmpty = function (val) { if (val == null) { // jshint ignore:line // typeof null == 'object' so we check it first return true; } else if (typeof val === "string" || isArray(val)) { return !val.length; } else if (typeof val === "object") { var _ret = (function () { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return { v: result }; })(); if (typeof _ret === "object") return _ret.v; } else { return true; } }; var intersection = function (array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item = undefined; for (var i = 0, _length = array1.length; i < _length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; }; var filter = function (array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; }; function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype["finally"]) { w.Promise.prototype["finally"] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = __webpack_require__(4); } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } var toPromisify = ["beforeValidate", "validate", "afterValidate", "beforeCreate", "afterCreate", "beforeUpdate", "afterUpdate", "beforeDestroy", "afterDestroy"]; // adapted from angular.copy var copy = function (source, destination, stackSource, stackDest) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest); } } } else { if (source === destination) { throw new Error("Cannot copy! Source and destination are identical."); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) { return stackDest[index]; } stackSource.push(source); stackDest.push(destination); } var result = undefined; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; }; // adapted from angular.equals var equals = function (o1, o2) { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == "object") { if (isArray(o1)) { if (!isArray(o2)) { return false; } if ((length = o1.length) == o2.length) { // jshint ignore:line for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) { return false; } } return true; } } else if (isDate(o1)) { if (!isDate(o2)) { return false; } return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) { return false; } keySet = {}; for (key in o1) { if (key.charAt(0) === "$" || isFunction(o1[key])) { continue; } if (!equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== "$" && o2[key] !== undefined && !isFunction(o2[key])) { return false; } } return true; } } } return false; }; var resolveId = function (definition, idOrInstance) { if (isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }; var resolveItem = function (resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }; var isValidString = function (val) { return val != null && val !== ""; // jshint ignore:line }; var join = function (items, separator) { separator = separator || ""; return filter(items, isValidString).join(separator); }; var makePath = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var result = join(args, "/"); return result.replace(/([^:\/]|^)\/{2,}/g, "$1/"); }; observe.setEqualityFn(equals); DSUtils = { // Options that inherit from defaults _: function _(parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA("\"options\" must be an object!"); } forEach(toPromisify, function (name) { if (typeof options[name] === "function" && options[name].toString().indexOf("for (var _len = arg") === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; O.prototype.orig = function () { var orig = {}; forOwn(this, function (value, key) { orig[key] = value; }); return orig; }; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function compute(fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: contains, copy: copy, deepMixIn: deepMixIn, diffObjectFromOldObject: observe.diffObjectFromOldObject, BinaryHeap: BinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function fromJson(json) { return isString(json) ? JSON.parse(json) : json; }, get: __webpack_require__(17), intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: pascalCase, pick: pick, Promise: _Promise, promisify: function promisify(fn, target) { var _this = this; if (!fn) { return; } else if (typeof fn !== "function") { throw new Error("Can only promisify functions!"); } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new _this.Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: remove, set: __webpack_require__(18), slice: slice, sort: sort, toJson: JSON.stringify, updateTimestamp: function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === "function" ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, upperCase: upperCase, removeCircular: function removeCircular(object) { var objects = []; return (function rmCirc(value) { var i = undefined; var nu = undefined; if (typeof value === "object" && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return undefined; } } objects.push(value); if (DSUtils.isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i]); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k]); }); } return nu; } return value; })(object); }, resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (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) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var IllegalArgumentError = (function (_Error) { function IllegalArgumentError(message) { _classCallCheck(this, IllegalArgumentError); _get(Object.getPrototypeOf(IllegalArgumentError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "Illegal Argument!"; } _inherits(IllegalArgumentError, _Error); return IllegalArgumentError; })(Error); var RuntimeError = (function (_Error2) { function RuntimeError(message) { _classCallCheck(this, RuntimeError); _get(Object.getPrototypeOf(RuntimeError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "RuntimeError Error!"; } _inherits(RuntimeError, _Error2); return RuntimeError; })(Error); var NonexistentResourceError = (function (_Error3) { function NonexistentResourceError(resourceName) { _classCallCheck(this, NonexistentResourceError); _get(Object.getPrototypeOf(NonexistentResourceError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = "" + resourceName + " is not a registered resource!"; } _inherits(NonexistentResourceError, _Error3); return NonexistentResourceError; })(Error); module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /* jshint eqeqeq:false */ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var syncMethods = _interopRequire(__webpack_require__(7)); var asyncMethods = _interopRequire(__webpack_require__(8)); var Schemator = undefined; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(_x, _x2, _x3, _x4) { var _again = true; _function: while (_again) { _again = false; var orderBy = _x, index = _x2, a = _x3, b = _x4; def = cA = cB = undefined; var def = orderBy[index]; var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]); if (DSUtils._s(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils._s(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === "DESC") { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } } } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, { errorFn: { value: function errorFn(a, b) { if (this.error && typeof this.error === "function") { try { if (typeof a === "string") { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } } } }); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ""; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.defaultAdapter = "http"; defaultsPrototype.debug = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ""; defaultsPrototype.error = console ? function (a, b, c) { return console[typeof console.error === "function" ? "error" : "log"](a, b, c); } : false; defaultsPrototype.fallbackAdapters = ["http"]; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.findInverseLinks = true; defaultsPrototype.idAttribute = "id"; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.loadFromServer = false; defaultsPrototype.log = console ? function (a, b, c, d, e) { return console[typeof console.info === "function" ? "info" : "log"](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { var _this = this; if (_this.debug && _this.log && typeof _this.log === "function") { _this.log(_this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.reapAction = !!DSUtils.w ? "inject" : "none"; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = "single"; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var filtered = collection; var where = null; var reserved = { skip: "", offset: "", where: "", limit: "", orderBy: "", sort: "" }; params = params || {}; options = options || {}; if (DSUtils._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { "==": value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils._s(clause)) { clause = { "===": clause }; } else if (DSUtils._n(clause) || DSUtils.isBoolean(clause)) { clause = { "==": clause }; } if (DSUtils._o(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr = undefined; var isOr = op[0] === "|"; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === "==") { expr = val == term; } else if (op === "===") { expr = val === term; } else if (op === "!=") { expr = val != term; } else if (op === "!==") { expr = val !== term; } else if (op === ">") { expr = val > term; } else if (op === ">=") { expr = val >= term; } else if (op === "<") { expr = val < term; } else if (op === "<=") { expr = val <= term; } else if (op === "isectEmpty") { expr = !DSUtils.intersection(val || [], term || []).length; } else if (op === "isectNotEmpty") { expr = DSUtils.intersection(val || [], term || []).length; } else if (op === "in") { if (DSUtils._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === "notIn") { if (DSUtils._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === "contains") { if (DSUtils._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === "notContains") { if (DSUtils._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : isOr ? keep || expr : keep && expr; } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils._s(params.orderBy)) { orderBy = [[params.orderBy, "ASC"]]; } else if (DSUtils._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils._s(params.sort)) { orderBy = [[params.sort, "ASC"]]; } else if (!orderBy && DSUtils._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { (function () { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils._s(def)) { orderBy[i] = [def, "ASC"]; } else if (!DSUtils._a(def)) { throw new DSErrors.IA("DS.filter(\"" + resourceName + "\"[, params][, options]): " + DSUtils.toJson(def) + ": Must be a string or an array!", { params: { "orderBy[i]": { actual: typeof def, expected: "string|array" } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); })(); } var limit = DSUtils._n(params.limit) ? params.limit : null; var skip = null; if (DSUtils._n(params.skip)) { skip = params.skip; } else if (DSUtils._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils._n(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils._n(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; var DS = (function () { function DS(options) { _classCallCheck(this, DS); var _this = this; options = options || {}; try { Schemator = __webpack_require__(5); } catch (e) {} if (!Schemator || DSUtils.isEmpty(Schemator)) { try { Schemator = window.Schemator; } catch (e) {} } Schemator = Schemator || options.schemator; if (typeof Schemator === "function") { _this.schemator = new Schemator(); } _this.store = {}; // alias store, shaves 0.1 kb off the minified build _this.s = _this.store; _this.definitions = {}; // alias definitions, shaves 0.3 kb off the minified build _this.defs = _this.definitions; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = DSUtils.observe; DSUtils.forOwn(options, function (v, k) { _this.defaults[k] = v; }); _this.defaults.logFn("new data store created", _this.defaults); } _createClass(DS, { getAdapter: { value: function getAdapter(options) { var errorIfNotExist = false; options = options || {}; this.defaults.logFn("getAdapter", options); if (DSUtils._s(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error("" + options.adapter + " is not a registered adapter!"); } else { return this.adapters[options.defaultAdapter]; } } }, registerAdapter: { value: function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; _this.defaults.logFn("registerAdapter", name, Adapter, options); if (DSUtils.isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options["default"]) { _this.defaults.defaultAdapter = name; } _this.defaults.logFn("default adapter is " + _this.defaults.defaultAdapter); } }, is: { value: function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } return instance instanceof definition[definition["class"]]; } } }); return DS; })(); var dsPrototype = DS.prototype; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter.shorthand = false; dsPrototype.errors = DSErrors; dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { if(typeof __WEBPACK_EXTERNAL_MODULE_5__ === 'undefined') {var e = new Error("Cannot find module \"undefined\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { // Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way to to define a default equality operator for diffObjectFromOldObject // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; var equalityFn = function (a, b) { return a === b; }; var blacklist = []; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, delete: true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.diffObjectFromOldObject = diffObjectFromOldObject; global.setEqualityFn = function (fn) { equalityFn = fn; }; global.setBlacklist = function (bl) { blacklist = bl; }; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })(exports); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var defineResource = _interopRequire(__webpack_require__(31)); var eject = _interopRequire(__webpack_require__(32)); var ejectAll = _interopRequire(__webpack_require__(33)); var filter = _interopRequire(__webpack_require__(34)); var inject = _interopRequire(__webpack_require__(35)); var link = _interopRequire(__webpack_require__(36)); var linkAll = _interopRequire(__webpack_require__(37)); var linkInverse = _interopRequire(__webpack_require__(38)); var unlinkInverse = _interopRequire(__webpack_require__(39)); var NER = DSErrors.NER; var IA = DSErrors.IA; var R = DSErrors.R; function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } module.exports = { changes: function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("changes", id, options); var item = _this.get(resourceName, id); if (item) { var _ret = (function () { if (DSUtils.w) { _this.s[resourceName].observers[id].deliver(); } var diff = DSUtils.diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], DSUtils.equals, options.ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return { v: diff }; })(); if (typeof _ret === "object") { return _ret.v; } } }, changeHistory: function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("changeHistory", id); if (!definition.keepChangeHistory) { definition.errorFn("changeHistory is disabled for this resource!"); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } }, compute: function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = DSUtils.resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R("Item not in the store!"); } else if (!DSUtils._o(instance) && !DSUtils._sn(instance)) { throw new IA("\"instance\" must be an object, string or number!"); } definition.logFn("compute", instance); DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; }, createInstance: function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item = undefined; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA("\"attrs\" must be an object!"); } options = DSUtils._(definition, options); options.logFn("createInstance", attrs, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition["class"]]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; }, defineResource: defineResource, digest: function digest() { this.observe.Platform.performMicrotaskCheckpoint(); }, eject: eject, ejectAll: ejectAll, filter: filter, get: function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("get", id, options); // cache miss, request resource from server var item = _this.s[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; }, getAll: function getAll(resourceName, ids) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !DSUtils._a(ids)) { throw DSUtils._aErr("ids"); } definition.logFn("getAll", ids); if (DSUtils._a(ids)) { var _length = ids.length; for (var i = 0; i < _length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; }, hasChanges: function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("hasChanges", id); // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } }, inject: inject, lastModified: function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn("lastModified", id); if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; }, lastSaved: function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn("lastSaved", id); if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; }, link: link, linkAll: linkAll, linkInverse: linkInverse, previous: function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("previous", id); // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; }, unlinkInverse: unlinkInverse }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var create = _interopRequire(__webpack_require__(40)); var destroy = _interopRequire(__webpack_require__(41)); var destroyAll = _interopRequire(__webpack_require__(42)); var find = _interopRequire(__webpack_require__(43)); var findAll = _interopRequire(__webpack_require__(44)); var loadRelations = _interopRequire(__webpack_require__(45)); var reap = _interopRequire(__webpack_require__(46)); var save = _interopRequire(__webpack_require__(47)); var update = _interopRequire(__webpack_require__(48)); var updateAll = _interopRequire(__webpack_require__(49)); module.exports = { create: create, destroy: destroy, destroyAll: destroyAll, find: find, findAll: findAll, loadRelations: loadRelations, reap: reap, refresh: function refresh(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.defs[resourceName]; id = DSUtils.resolveId(_this.defs[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.bypassCache = true; options.logFn("refresh", id, options); resolve(_this.get(resourceName, id)); } }).then(function (item) { return item ? _this.find(resourceName, id, options) : item; }); }, save: save, update: update, updateAll: updateAll }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(23); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(23); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(24); var forIn = __webpack_require__(25); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var forOwn = __webpack_require__(14); var isPlainObject = __webpack_require__(26); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var slice = __webpack_require__(10); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isPrimitive = __webpack_require__(27); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var namespace = __webpack_require__(28); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); var camelCase = __webpack_require__(30); var upperCase = __webpack_require__(20); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(51)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(50), (function() { return this; }()), __webpack_require__(52)(module))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /*! * yabh * @version 1.0.0 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <[email protected]> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["BinaryHeap"] = factory(); else root["BinaryHeap"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var _parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(_parent)) { break; } else { heap[parentN] = element; heap[n] = _parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ var bubbleDown = function (heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } }; var BinaryHeap = (function () { function BinaryHeap(weightFunc, compareFunc) { _classCallCheck(this, BinaryHeap); if (!weightFunc) { weightFunc = function (x) { return x; }; } if (!compareFunc) { compareFunc = function (x, y) { return x === y; }; } if (typeof weightFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"weightFunc\" must be a function!"); } if (typeof compareFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"compareFunc\" must be a function!"); } this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } _createClass(BinaryHeap, { push: { value: function push(node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); } }, peek: { value: function peek() { return this.heap[0]; } }, pop: { value: function pop() { var front = this.heap[0]; var end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; } }, remove: { value: function remove(node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; } }, removeAll: { value: function removeAll() { this.heap = []; } }, size: { value: function size() { return this.heap.length; } } }); return BinaryHeap; })(); module.exports = BinaryHeap; /***/ } /******/ ]) }); ; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(24); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var forEach = __webpack_require__(9); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); var replaceAccents = __webpack_require__(53); var removeNonWord = __webpack_require__(54); var upperCase = __webpack_require__(20); var lowerCase = __webpack_require__(55); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; module.exports = defineResource; /*jshint evil:true, loopfunc:true*/ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var Resource = function Resource(options) { _classCallCheck(this, Resource); DSUtils.deepMixIn(this, options); if ("endpoint" in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } }; var instanceMethods = ["compute", "refresh", "save", "update", "destroy", "loadRelations", "changeHistory", "changes", "hasChanges", "lastModified", "lastSaved", "link", "linkInverse", "previous", "unlinkInverse"]; function defineResource(definition) { var _this = this; var definitions = _this.defs; if (DSUtils._s(definition)) { definition = { name: definition.replace(/\s/gi, "") }; } if (!DSUtils._o(definition)) { throw DSUtils._oErr("definition"); } else if (!DSUtils._s(definition.name)) { throw new DSErrors.IA("\"name\" must be a string!"); } else if (_this.s[definition.name]) { throw new DSErrors.R("" + definition.name + " is already registered!"); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; // alias name, shaves 0.08 kb off the minified build def.n = def.name; def.logFn("Preparing resource."); if (!DSUtils._s(def.idAttribute)) { throw new DSErrors.IA("\"idAttribute\" must be a string!"); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils._a(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.n; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === "function") { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.defs[resourceName]; }; def.getEndpoint = function (id, options) { options.params = options.params || {}; var item = undefined; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty("endpoint") ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils._sn(id)) { item = def.get(id); } else if (DSUtils._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { var _ret = (function () { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return { v: DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint) }; })(); if (typeof _ret === "object") return _ret.v; } else { return endpoint; } } }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource var _class = def["class"] = DSUtils.pascalCase(def.name); try { if (typeof def.useClass === "function") { eval("function " + _class + "() { def.useClass.call(this); }"); def[_class] = eval(_class); def[_class].prototype = (function (proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval("function " + _class + "() {}"); def[_class] = eval(_class); } } catch (e) { def[_class] = function () {}; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[_class].prototype, def.methods); } def[_class].prototype.set = function (key, value) { DSUtils.set(this, key, value); var observer = _this.s[def.n].observers[this[def.idAttribute]]; if (observer && !DSUtils.observe.hasObjectObserve) { observer.deliver(); } else { _this.compute(def.n, this); } return this; }; def[_class].prototype.get = function (key) { return DSUtils.get(this, key); }; // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn("Computed property \"" + field + "\" conflicts with previously defined prototype method!"); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(","); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn("Use the computed property array syntax for compatibility with minified code!"); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.n, definition.schema); if (!definition.hasOwnProperty("validate")) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[_class].prototype["DS" + DSUtils.pascalCase(name)] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this[def.idAttribute] || this); args.unshift(def.n); return _this[name].apply(_this, args); }; }); def[_class].prototype.DSCreate = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this); args.unshift(def.n); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.n] = { collection: [], expiresHeap: new DSUtils.BinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { return _this.reap(def.n, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones var fns = ["registerAdapter", "getAdapter", "is"]; for (var key in _this) { if (typeof _this[key] === "function") { fns.push(key); } } DSUtils.forEach(fns, function (key) { var k = key; if (_this[k].shorthand !== false) { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(def.n); return _this[k].apply(_this, args); }; } else { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _this[k].apply(_this, args); }; } }); def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); DSUtils.forOwn(def.actions, function (action, name) { if (def[name] && !def.actions[name]) { throw new Error("Cannot override existing method \"" + name + "\"!"); } def[name] = function (options) { options = options || {}; var adapter = _this.getAdapter(action.adapter || "http"); var config = DSUtils.deepMixIn({}, action); if (!options.hasOwnProperty("endpoint") && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === "function") { config.url = options.getEndpoint(def, options); } else { config.url = DSUtils.makePath(options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(null, options), name); } config.method = config.method || "GET"; DSUtils.deepMixIn(config, options); return adapter.HTTP(config); }; }); // Mix-in events DSUtils.Events(def); def.logFn("Done preparing resource."); return def; } catch (err) { delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { module.exports = eject; function eject(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("eject", id, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { // jshint ignore:line item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { var _ret = (function () { if (options.notify) { definition.beforeEject(options, item); definition.emit("DS.beforeEject", definition, item); } _this.unlinkInverse(definition.n, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } if (!items.length) { toRemove.push(queryHash); } }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); definition.emit("DS.afterEject", definition, item); } return { v: item }; })(); if (typeof _ret === "object") { return _ret.v; } } } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { module.exports = ejectAll; function ejectAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr("params"); } definition.logFn("ejectAll", params, options); var resource = _this.s[resourceName]; var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.n, params); var ids = []; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } else { delete resource.completedQueries[queryHash]; } DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.n, id, options); }); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { module.exports = filter; function filter(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; if (!definition) { throw new _this.errors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr("params"); } // Protect against null params = params || {}; options = DSUtils._(definition, options); options.logFn("filter", params, options); var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; module.exports = inject; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); function _getReactFunction(DS, definition, resource) { var name = definition.n; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item = undefined; var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { definition.errorFn("Doh! You just changed the primary key of an object! Your data for the \"" + name + "\" resource is now in an undefined (probably broken) state."); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected = undefined; if (DSUtils._a(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { (function () { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); })(); } if (!(idA in attrs)) { var error = new DSErrors.R("" + definition.n + ".inject: \"attrs\" must contain the property specified by \"idAttribute\"!"); options.errorFn(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.defs[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R("" + definition.n + " relation is defined but the resource is not!"); } if (DSUtils._a(toInject)) { (function () { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName][toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options.orig()); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } }); attrs[def.localField] = items; })(); } else { if (toInject !== _this.s[relationName][toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options.orig()); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } } } }); var id = attrs[idA]; var item = _this.get(definition.n, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition["class"]]) { item = attrs; } else { item = new definition[definition["class"]](); } } else { item = {}; } DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); resource.previousAttributes[id] = DSUtils.copy(item); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(item); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); var timestamp = new Date().getTime(); resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === "belongsTo" && injected[definition.idAttribute]) { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } else if (options.findHasMany && def.type === "hasMany" || options.findHasOne && def.type === "hasOne") { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected = undefined; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._o(attrs) && !DSUtils._a(attrs)) { throw new DSErrors.IA("" + resourceName + ".inject: \"attrs\" must be an object or an array!"); } var name = definition.n; options = DSUtils._(definition, options); options.logFn("inject", attrs, options); if (options.notify) { options.beforeInject(options, attrs); definition.emit("DS.beforeInject", definition, attrs); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils._a(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); definition.emit("DS.afterInject", definition, injected); } return injected; } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { module.exports = link; function link(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("link", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === "belongsTo") { var _parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (_parent) { linked[def.localField] = _parent; } } else if (def.type === "hasMany") { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === "hasOne") { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkAll; function linkAll(resourceName, params, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("linkAll", params, relations); var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === "belongsTo") { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === "hasMany") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === "hasOne") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkInverse; function linkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("linkInverse", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.n)) { return; } if (definition.n === relationName) { _this.linkAll(d.n, {}, [definition.n]); } }); }); }); } return linked; } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { module.exports = unlinkInverse; function unlinkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("unlinkInverse", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.n === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.s[def.name].collection, function (item) { if (def.type === "hasMany" && item[def.localField]) { (function () { var index = undefined; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); if (index !== undefined) { item[def.localField].splice(index, 1); } })(); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { module.exports = create; function create(resourceName, attrs, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError = undefined; if (!definition) { rejectionError = new _this.errors.NER(resourceName); } else if (!DSUtils._o(attrs)) { rejectionError = DSUtils._oErr("attrs"); } else { options = DSUtils._(definition, options); if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } options.logFn("create", attrs, options); } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeCreate", definition, attrs); } return _this.getAdapter(options).create(definition, attrs, options); }).then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterCreate", definition, attrs); } if (options.cacheResponse) { var created = _this.inject(definition.n, attrs, options.orig()); var id = created[definition.idAttribute]; var resource = _this.s[resourceName]; resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroy; function destroy(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var item = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); options.logFn("destroy", id, options); resolve(item); } }).then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeDestroy", definition, attrs); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }).then(function () { return options.afterDestroy.call(item, options, item); }).then(function (item) { if (options.notify) { definition.emit("DS.afterDestroy", definition, item); } _this.eject(resourceName, id); return id; })["catch"](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroyAll; function destroyAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var ejected = undefined, toEject = undefined; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("attrs")); } else { options = DSUtils._(definition, options); options.logFn("destroyAll", params, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.beforeDestroy", definition, toEject); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.afterDestroy", definition, toEject); } return ejected || _this.ejectAll(resourceName, params); })["catch"](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /* jshint -W082 */ module.exports = find; function find(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.logFn("find", id, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries && _this.get(resourceName, id)) { resolve(_this.get(resourceName, id)); } else { delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise = undefined; var strategy = options.findStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { var injected = _this.inject(resourceName, data, options.orig()); resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return injected; } else { return _this.createInstance(resourceName, data, options.orig()); } }); } return resource.pendingQueries[id]; } else { return item; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[id]; } throw err; }); } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { module.exports = findAll; /* jshint -W082 */ function processResults(data, resourceName, queryHash, options) { var _this = this; var DSUtils = _this.utils; var resource = _this.s[resourceName]; var idAttribute = _this.defs[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options.orig()); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item) { var id = item[idAttribute]; if (id) { resource.completedQueries[id] = date; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); } } }); } else { options.errorFn("response is expected to be an array!"); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash = undefined; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("params")); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); options.logFn("findAll", params, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { resolve(_this.filter(resourceName, params, options.orig())); } else { resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise = undefined; var strategy = options.findAllStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options.orig()); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } throw err; }); } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { module.exports = loadRelations; function loadRelations(resourceName, instance, relations, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils._s(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(instance)) { reject(new DSErrors.IA("\"instance(id)\" must be a string, number or object!")); } else if (!DSUtils._a(relations)) { reject(new DSErrors.IA("\"relations\" must be a string or an array!")); } else { (function () { var _options = DSUtils._(definition, options); if (!_options.hasOwnProperty("findBelongsTo")) { _options.findBelongsTo = true; } if (!_options.hasOwnProperty("findHasMany")) { _options.findHasMany = true; } _options.logFn("loadRelations", instance, relations, _options); var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); if (DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task = undefined; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { "==": instance[definition.idAttribute] }; } if (def.type === "hasMany" && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()); } else if (def.type === "hasOne") { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], __options.orig()); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); })(); } }).then(function (tasks) { return DSUtils.Promise.all(tasks); }).then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { module.exports = reap; function reap(resourceName, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty("notify")) { options.notify = false; } options.logFn("reap", options); var items = []; var now = new Date().getTime(); var expiredItem = undefined; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); definition.emit("DS.beforeReap", definition, items); } if (options.reapAction === "inject") { (function () { var timestamp = new Date().getTime(); DSUtils.forEach(items, function (item) { resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); }); })(); } else if (options.reapAction === "eject") { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === "refresh") { var _ret2 = (function () { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return { v: DSUtils.Promise.all(tasks) }; })(); if (typeof _ret2 === "object") return _ret2.v; } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); definition.emit("DS.afterReap", definition, items); } return items; }); } /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { module.exports = save; function save(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var item = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R("id \"" + id + "\" not found in cache!")); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); options.logFn("save", id, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } if (options.changesOnly) { var resource = _this.s[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { module.exports = update; function update(resourceName, id, attrs, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.logFn("update", id, attrs, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { module.exports = updateAll; function updateAll(resourceName, attrs, params, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); options.logFn("updateAll", attrs, params, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (data) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } var origOptions = options.orig(); if (options.cacheResponse) { var _ret = (function () { var injected = _this.inject(definition.n, data, origOptions); var resource = _this.s[resourceName]; DSUtils.forEach(injected, function (i) { var id = i[definition.idAttribute]; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(i); } }); return { v: injected }; })(); if (typeof _ret === "object") return _ret.v; } else { var _ret2 = (function () { var instances = []; DSUtils.forEach(data, function (item) { instances.push(_this.createInstance(resourceName, item, origOptions)); }); return { v: instances }; })(); if (typeof _ret2 === "object") return _ret2.v; } }); } /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(29); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; /***/ } /******/ ]) });
__tests__/index.js
akiran/react-slick
"use strict"; import React from "react"; import { shallow, mount } from "enzyme"; import Slider from "../src/index"; describe("Slider", function() { it("should render", function() { const wrapper = shallow( <Slider> <div>slide1</div> </Slider> ); expect( wrapper.contains( <div tabIndex={-1} style={{ width: "100%", display: "inline-block" }}> slide1 </div> ) ).toBe(true); }); });
ajax/libs/angular-google-maps/2.1.0-X.7/angular-google-maps_dev_mapped.js
wil93/cdnjs
/*! angular-google-maps 2.1.0-X.7 2015-03-27 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/angular-google-maps.git */ ; (function( window, angular, undefined ){ 'use strict'; /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/angular-ui/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps.providers', []); angular.module('uiGmapgoogle-maps.wrapped', []); angular.module('uiGmapgoogle-maps.extensions', ['uiGmapgoogle-maps.wrapped', 'uiGmapgoogle-maps.providers']); angular.module('uiGmapgoogle-maps.directives.api.utils', ['uiGmapgoogle-maps.extensions']); angular.module('uiGmapgoogle-maps.directives.api.managers', []); angular.module('uiGmapgoogle-maps.directives.api.options', ['uiGmapgoogle-maps.directives.api.utils']); angular.module('uiGmapgoogle-maps.directives.api.options.builders', []); angular.module('uiGmapgoogle-maps.directives.api.models.child', ['uiGmapgoogle-maps.directives.api.utils', 'uiGmapgoogle-maps.directives.api.options', 'uiGmapgoogle-maps.directives.api.options.builders']); angular.module('uiGmapgoogle-maps.directives.api.models.parent', ['uiGmapgoogle-maps.directives.api.managers', 'uiGmapgoogle-maps.directives.api.models.child', 'uiGmapgoogle-maps.providers']); angular.module('uiGmapgoogle-maps.directives.api', ['uiGmapgoogle-maps.directives.api.models.parent']); angular.module('uiGmapgoogle-maps', ['uiGmapgoogle-maps.directives.api', 'uiGmapgoogle-maps.providers']); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.providers').factory('uiGmapMapScriptLoader', [ '$q', 'uiGmapuuid', function($q, uuid) { var getScriptUrl, includeScript, isGoogleMapsLoaded, scriptId; scriptId = void 0; getScriptUrl = function(options) { if (options.china) { return 'http://maps.google.cn/maps/api/js?'; } else { return 'https://maps.googleapis.com/maps/api/js?'; } }; includeScript = function(options) { var query, script; query = _.map(options, function(v, k) { return k + '=' + v; }); if (scriptId) { document.getElementById(scriptId).remove(); } query = query.join('&'); script = document.createElement('script'); script.id = scriptId = "ui_gmap_map_load_" + (uuid.generate()); script.type = 'text/javascript'; script.src = getScriptUrl(options) + query; return document.body.appendChild(script); }; isGoogleMapsLoaded = function() { return angular.isDefined(window.google) && angular.isDefined(window.google.maps); }; return { load: function(options) { var deferred, randomizedFunctionName; deferred = $q.defer(); if (isGoogleMapsLoaded()) { deferred.resolve(window.google.maps); return deferred.promise; } randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000); window[randomizedFunctionName] = function() { window[randomizedFunctionName] = null; deferred.resolve(window.google.maps); }; if (window.navigator.connection && window.Connection && window.navigator.connection.type === window.Connection.NONE) { document.addEventListener('online', function() { if (!isGoogleMapsLoaded()) { return includeScript(options); } }); } else { includeScript(options); } return deferred.promise; } }; } ]).provider('uiGmapGoogleMapApi', function() { this.options = { china: false, v: '3.17', libraries: '', language: 'en', sensor: 'false' }; this.configure = function(options) { angular.extend(this.options, options); }; this.$get = [ 'uiGmapMapScriptLoader', (function(_this) { return function(loader) { return loader.load(_this.options); }; })(this) ]; return this; }); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.extensions').service('uiGmapExtendGWin', function() { return { init: _.once(function() { var uiGmapInfoBox; if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) { if (recurse != null) { return; } this._isOpen = true; this._open(map, anchor, true); }; google.maps.InfoWindow.prototype.close = function(recurse) { if (recurse != null) { return; } this._isOpen = false; this._close(true); }; google.maps.InfoWindow.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; /* Do the same for InfoBox TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier */ if (window.InfoBox) { window.InfoBox.prototype._open = window.InfoBox.prototype.open; window.InfoBox.prototype._close = window.InfoBox.prototype.close; window.InfoBox.prototype._isOpen = false; window.InfoBox.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; window.InfoBox.prototype.close = function() { this._isOpen = false; this._close(); }; window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; uiGmapInfoBox = (function(superClass) { extend(uiGmapInfoBox, superClass); function uiGmapInfoBox(opts) { this.getOrigCloseBoxImg_ = bind(this.getOrigCloseBoxImg_, this); this.getCloseBoxDiv_ = bind(this.getCloseBoxDiv_, this); var box; box = new window.InfoBox(opts); _.extend(this, box); if (opts.closeBoxDiv != null) { this.closeBoxDiv_ = opts.closeBoxDiv; } } uiGmapInfoBox.prototype.getCloseBoxDiv_ = function() { return this.closeBoxDiv_; }; uiGmapInfoBox.prototype.getCloseBoxImg_ = function() { var div, img; div = this.getCloseBoxDiv_(); img = this.getOrigCloseBoxImg_(); return div || img; }; uiGmapInfoBox.prototype.getOrigCloseBoxImg_ = function() { var img; img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; img += " style='"; img += " position: relative;"; img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; return uiGmapInfoBox; })(window.InfoBox); window.uiGmapInfoBox = uiGmapInfoBox; } if (window.MarkerLabel_) { return window.MarkerLabel_.prototype.setContent = function() { var content; content = this.marker_.get('labelContent'); if (!content || _.isEqual(this.oldContent, content)) { return; } if (typeof (content != null ? content.nodeType : void 0) === 'undefined') { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; this.oldContent = content; } else { this.labelDiv_.innerHTML = ''; this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.labelDiv_.innerHTML = ''; this.eventDiv_.appendChild(content); this.oldContent = content; } }; } }) }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.extensions').service('uiGmapLodash', function() { /* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ this.intersectionObjects = function(array1, array2, comparison) { var res; if (comparison == null) { comparison = void 0; } res = _.map(array1, (function(_this) { return function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }; })(this)); return _.filter(res, function(o) { return o != null; }); }; this.containsObject = _.includeObject = function(obj, target, comparison) { if (comparison == null) { comparison = void 0; } if (obj === null) { return false; } return _.any(obj, (function(_this) { return function(value) { if (comparison != null) { return comparison(value, target); } else { return _.isEqual(value, target); } }; })(this)); }; this.differenceObjects = function(array1, array2, comparison) { if (comparison == null) { comparison = void 0; } return _.filter(array1, (function(_this) { return function(value) { return !_this.containsObject(array2, value, comparison); }; })(this)); }; this.withoutObjects = this.differenceObjects; this.indexOfObject = function(array, item, comparison, isSorted) { var i, length; if (array == null) { return -1; } i = 0; length = array.length; if (isSorted) { if (typeof isSorted === "number") { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return (array[i] === item ? i : -1); } } while (i < length) { if (comparison != null) { if (comparison(array[i], item)) { return i; } } else { if (_.isEqual(array[i], item)) { return i; } } i++; } return -1; }; this["extends"] = function(arrayOfObjectsToCombine) { return _.reduce(arrayOfObjectsToCombine, function(combined, toAdd) { return _.extend(combined, toAdd); }, {}); }; this.isNullOrUndefined = function(thing) { return _.isNull(thing || _.isUndefined(thing)); }; return this; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.extensions').factory('uiGmapString', function() { return function(str) { this.contains = function(value, fromIndex) { return str.indexOf(value, fromIndex) !== -1; }; return this; }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmap_sync', [ function() { return { fakePromise: function() { var _cb; _cb = void 0; return { then: function(cb) { return _cb = cb; }, resolve: function() { return _cb.apply(void 0, arguments); } }; } }; } ]).service('uiGmap_async', [ '$timeout', 'uiGmapPromise', 'uiGmapLogger', '$q', 'uiGmapDataStructures', 'uiGmapGmapUtil', function($timeout, uiGmapPromise, $log, $q, uiGmapDataStructures, uiGmapGmapUtil) { var ExposedPromise, PromiseQueueManager, SniffedPromise, _getArrayAndKeys, _getIterateeValue, defaultChunkSize, doChunk, doSkippPromise, each, errorObject, isInProgress, kickPromise, logTryCatch, managePromiseQueue, map, maybeCancelPromises, promiseStatus, promiseTypes, tryCatch; promiseTypes = uiGmapPromise.promiseTypes; isInProgress = uiGmapPromise.isInProgress; promiseStatus = uiGmapPromise.promiseStatus; ExposedPromise = uiGmapPromise.ExposedPromise; SniffedPromise = uiGmapPromise.SniffedPromise; kickPromise = function(sniffedPromise, cancelCb) { var promise; promise = sniffedPromise.promise(); promise.promiseType = sniffedPromise.promiseType; if (promise.$$state) { $log.debug("promiseType: " + promise.promiseType + ", state: " + (promiseStatus(promise.$$state.status))); } promise.cancelCb = cancelCb; return promise; }; doSkippPromise = function(sniffedPromise, lastPromise) { if (sniffedPromise.promiseType === promiseTypes.create && lastPromise.promiseType !== promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes.init) { $log.debug("lastPromise.promiseType " + lastPromise.promiseType + ", newPromiseType: " + sniffedPromise.promiseType + ", SKIPPED MUST COME AFTER DELETE ONLY"); return true; } return false; }; maybeCancelPromises = function(queue, sniffedPromise, lastPromise) { var first; if (sniffedPromise.promiseType === promiseTypes["delete"] && lastPromise.promiseType !== promiseTypes["delete"]) { if ((lastPromise.cancelCb != null) && _.isFunction(lastPromise.cancelCb) && isInProgress(lastPromise)) { $log.debug("promiseType: " + sniffedPromise.promiseType + ", CANCELING LAST PROMISE type: " + lastPromise.promiseType); lastPromise.cancelCb('cancel safe'); first = queue.peek(); if ((first != null) && isInProgress(first)) { if (first.hasOwnProperty("cancelCb") && _.isFunction(first.cancelCb)) { $log.debug("promiseType: " + first.promiseType + ", CANCELING FIRST PROMISE type: " + first.promiseType); return first.cancelCb('cancel safe'); } else { return $log.warn('first promise was not cancelable'); } } } } }; /* From a High Level: This is a SniffedPromiseQueueManager (looking to rename) where the queue is existingPiecesObj.existingPieces. This is a function and should not be considered a class. So it is run to manage the state (cancel, skip, link) as needed. Purpose: The whole point is to check if there is existing async work going on. If so we wait on it. arguments: - existingPiecesObj = Queue<Promises> - sniffedPromise = object wrapper holding a function to a pending (function) promise (promise: fnPromise) with its intended type. - cancelCb = callback which accepts a string, this string is intended to be returned at the end of _async.each iterator Where the cancelCb passed msg is 'cancel safe' _async.each will drop out and fall through. Thus canceling the promise gracefully without messing up state. Synopsis: - Promises have been broken down to 4 states create, update,delete (3 main) and init. (Helps boil down problems in ordering) where (init) is special to indicate that it is one of the first or to allow a create promise to work beyond being after a delete - Every Promise that comes is is enqueue and linked to the last promise in the queue. - A promise can be skipped or canceled to save cycles. Saved Cycles: - Skipped - This will only happen if async work comes in out of order. Where a pending create promise (un-executed) comes in after a delete promise. - Canceled - Where an incoming promise (un-executed promise) is of type delete and the any lastPromise is not a delete type. NOTE: - You should not muck with existingPieces as its state is dependent on this functional loop. - PromiseQueueManager should not be thought of as a class that has a life expectancy (it has none). It's sole purpose is to link, skip, and kill promises. It also manages the promise queue existingPieces. */ PromiseQueueManager = function(existingPiecesObj, sniffedPromise, cancelCb) { var lastPromise, newPromise; if (!existingPiecesObj.existingPieces) { existingPiecesObj.existingPieces = new uiGmapDataStructures.Queue(); return existingPiecesObj.existingPieces.enqueue(kickPromise(sniffedPromise, cancelCb)); } else { lastPromise = _.last(existingPiecesObj.existingPieces._content); if (doSkippPromise(sniffedPromise, lastPromise)) { return; } maybeCancelPromises(existingPiecesObj.existingPieces, sniffedPromise, lastPromise); newPromise = ExposedPromise(lastPromise["finally"](function() { return kickPromise(sniffedPromise, cancelCb); })); newPromise.cancelCb = cancelCb; newPromise.promiseType = sniffedPromise.promiseType; existingPiecesObj.existingPieces.enqueue(newPromise); return lastPromise["finally"](function() { return existingPiecesObj.existingPieces.dequeue(); }); } }; managePromiseQueue = function(objectToLock, promiseType, msg, cancelCb, fnPromise) { var cancelLogger; if (msg == null) { msg = ''; } cancelLogger = function(msg) { $log.debug(msg + ": " + msg); if ((cancelCb != null) && _.isFunction(cancelCb)) { return cancelCb(msg); } }; return PromiseQueueManager(objectToLock, SniffedPromise(fnPromise, promiseType), cancelLogger); }; defaultChunkSize = 80; errorObject = { value: null }; tryCatch = function(fn, ctx, args) { var e; try { return fn.apply(ctx, args); } catch (_error) { e = _error; errorObject.value = e; return errorObject; } }; logTryCatch = function(fn, ctx, deferred, args) { var msg, result; result = tryCatch(fn, ctx, args); if (result === errorObject) { msg = "error within chunking iterator: " + errorObject.value; $log.error(msg); deferred.reject(msg); } if (result === 'cancel safe') { return false; } return true; }; _getIterateeValue = function(collection, array, index) { var _isArray, valOrKey; _isArray = collection === array; valOrKey = array[index]; if (_isArray) { return valOrKey; } return collection[valOrKey]; }; _getArrayAndKeys = function(collection, keys, bailOutCb, cb) { var array; if (angular.isArray(collection)) { array = collection; } else { array = keys ? keys : Object.keys(_.omit(collection, ['length', 'forEach', 'map'])); keys = array; } if (cb == null) { cb = bailOutCb; } if (angular.isArray(array) && (array === void 0 || (array != null ? array.length : void 0) <= 0)) { if (cb !== bailOutCb) { return bailOutCb(); } } return cb(array, keys); }; /* Author: Nicholas McCready & jfriend00 _async handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui The design of any functionality of _async is to be like lodash/underscore and replicate it but call things asynchronously underneath. Each should be sufficient for most things to be derived from. Optional Asynchronous Chunking via promises. */ doChunk = function(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, _keys) { return _getArrayAndKeys(collection, _keys, function(array, keys) { var cnt, i, keepGoing, val; if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) { cnt = chunkSizeOrDontChunk; } else { cnt = array.length; } i = index; keepGoing = true; while (keepGoing && cnt-- && i < (array ? array.length : i + 1)) { val = _getIterateeValue(collection, array, i); keepGoing = angular.isFunction(val) ? true : logTryCatch(chunkCb, void 0, overallD, [val, i]); ++i; } if (array) { if (keepGoing && i < array.length) { index = i; if (chunkSizeOrDontChunk) { if ((pauseCb != null) && _.isFunction(pauseCb)) { logTryCatch(pauseCb, void 0, overallD, []); } return $timeout(function() { return doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index, keys); }, pauseMilli, false); } } else { return overallD.resolve(); } } }); }; each = function(collection, chunk, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var error, overallD, ret; if (chunkSizeOrDontChunk == null) { chunkSizeOrDontChunk = defaultChunkSize; } if (index == null) { index = 0; } if (pauseMilli == null) { pauseMilli = 1; } ret = void 0; overallD = uiGmapPromise.defer(); ret = overallD.promise; if (!pauseMilli) { error = 'pause (delay) must be set from _async!'; $log.error(error); overallD.reject(error); return ret; } return _getArrayAndKeys(collection, _keys, function() { overallD.resolve(); return ret; }, function(array, keys) { doChunk(collection, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index, keys); return ret; }); }; map = function(collection, iterator, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, _keys) { var results; results = []; return _getArrayAndKeys(collection, _keys, function() { return uiGmapPromise.resolve(results); }, function(array, keys) { return each(collection, function(o) { return results.push(iterator(o)); }, chunkSizeOrDontChunk, pauseCb, index, pauseMilli, keys).then(function() { return results; }); }); }; return { each: each, map: map, managePromiseQueue: managePromiseQueue, promiseLock: managePromiseQueue, defaultChunkSize: defaultChunkSize, chunkSizeFrom: function(fromSize, ret) { if (ret == null) { ret = void 0; } if (_.isNumber(fromSize)) { ret = fromSize; } if (uiGmapGmapUtil.isFalse(fromSize) || fromSize === false) { ret = false; } return ret; } }; } ]); }).call(this); ;(function() { var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapBaseObject', function() { var BaseObject, baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, ref, value; for (key in obj) { value = obj[key]; if (indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((ref = obj.extended) != null) { ref.apply(this); } return this; }; BaseObject.include = function(obj) { var key, ref, value; for (key in obj) { value = obj[key]; if (indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((ref = obj.included) != null) { ref.apply(this); } return this; }; return BaseObject; })(); return BaseObject; }); }).call(this); ; /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapChildEvents', function() { return { onChildCreation: function(child) {} }; }); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapCtrlHandle', [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.$on('$destroy', function() { return CtrlHandle.handle($scope); }); $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapEventsHelper", [ "uiGmapLogger", function($log) { var _getEventsObj, _hasEvents; _hasEvents = function(obj) { return angular.isDefined(obj.events) && (obj.events != null) && angular.isObject(obj.events); }; _getEventsObj = function(scope, model) { if (_hasEvents(scope)) { return scope; } if (_hasEvents(model)) { return model; } }; return { setEvents: function(gObject, scope, model, ignores) { var eventObj; eventObj = _getEventsObj(scope, model); if (eventObj != null) { return _.compact(_.map(eventObj.events, function(eventHandler, eventName) { var doIgnore; if (ignores) { doIgnore = _(ignores).contains(eventName); } if (eventObj.events.hasOwnProperty(eventName) && angular.isFunction(eventObj.events[eventName]) && !doIgnore) { return google.maps.event.addListener(gObject, eventName, function() { if (!scope.$evalAsync) { scope.$evalAsync = function() {}; } return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments])); }); } })); } }, removeEvents: function(listeners) { if (!listeners) { return; } return listeners.forEach(function(l) { if (l) { return google.maps.event.removeListener(l); } }); } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapFitHelper', [ 'uiGmapLogger', 'uiGmap_async', function($log, _async) { return { fit: function(gMarkers, gMap) { var bounds, everSet; if (gMap && gMarkers && gMarkers.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; gMarkers.forEach((function(_this) { return function(gMarker) { if (gMarker) { if (!everSet) { everSet = true; } return bounds.extend(gMarker.getPosition()); } }; })(this)); if (everSet) { return gMap.fitBounds(bounds); } } } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapGmapUtil', [ 'uiGmapLogger', '$compile', function(Logger, $compile) { var _isFalse, _isTruthy, getCoords, getLatitude, getLongitude, validateCoords; _isTruthy = function(value, bool, optionsArray) { return value === bool || optionsArray.indexOf(value) !== -1; }; _isFalse = function(value) { return _isTruthy(value, false, ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO']); }; getLatitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[1]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[1]; } else { return value.latitude; } }; getLongitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[0]; } else if (angular.isDefined(value.type) && value.type === 'Point') { return value.coordinates[0]; } else { return value.longitude; } }; getCoords = function(value) { if (!value) { return; } if (Array.isArray(value) && value.length === 2) { return new google.maps.LatLng(value[1], value[0]); } else if (angular.isDefined(value.type) && value.type === 'Point') { return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]); } else { return new google.maps.LatLng(value.latitude, value.longitude); } }; validateCoords = function(coords) { if (angular.isUndefined(coords)) { return false; } if (_.isArray(coords)) { if (coords.length === 2) { return true; } } else if ((coords != null) && (coords != null ? coords.type : void 0)) { if (coords.type === 'Point' && _.isArray(coords.coordinates) && coords.coordinates.length === 2) { return true; } } if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) { return true; } return false; }; return { setCoordsFromEvent: function(prevValue, newLatLon) { if (!prevValue) { return; } if (Array.isArray(prevValue) && prevValue.length === 2) { prevValue[1] = newLatLon.lat(); prevValue[0] = newLatLon.lng(); } else if (angular.isDefined(prevValue.type) && prevValue.type === 'Point') { prevValue.coordinates[1] = newLatLon.lat(); prevValue.coordinates[0] = newLatLon.lng(); } else { prevValue.latitude = newLatLon.lat(); prevValue.longitude = newLatLon.lng(); } return prevValue; }, getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor); xPos = parseFloat(anchor[1]); yPos = parseFloat(anchor[2]); if ((xPos != null) && (yPos != null)) { return new google.maps.Point(xPos, yPos); } }, createWindowOptions: function(gMarker, scope, content, defaults) { var options; if ((content != null) && (defaults != null) && ($compile != null)) { options = angular.extend({}, defaults, { content: this.buildContent(scope, defaults, content), position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords) }); if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) { if (options.boxClass == null) { } else { options.pixelOffset = { height: 0, width: -2 }; } } return options; } else { if (!defaults) { Logger.error('infoWindow defaults not defined'); if (!content) { return Logger.error('infoWindow content not defined'); } } else { return defaults; } } }, buildContent: function(scope, defaults, content) { var parsed, ret; if (defaults.content != null) { ret = defaults.content; } else { if ($compile != null) { content = content.replace(/^\s+|\s+$/g, ''); parsed = content === '' ? '' : $compile(content)(scope); if (parsed.length > 0) { ret = parsed[0]; } } else { ret = content; } } return ret; }, defaultDelay: 50, isTrue: function(value) { return _isTruthy(value, true, ['true', 'TRUE', 1, 'y', 'Y', 'yes', 'YES']); }, isFalse: _isFalse, isFalsy: function(value) { return _isTruthy(value, false, [void 0, null]) || _isFalse(value); }, getCoords: getCoords, validateCoords: validateCoords, equalCoords: function(coord1, coord2) { return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2); }, validatePath: function(path) { var array, i, polygon, trackMaxVertices; i = 0; if (angular.isUndefined(path.type)) { if (!Array.isArray(path) || path.length < 2) { return false; } while (i < path.length) { if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === 'function' && typeof path[i].lng === 'function'))) { return false; } i++; } return true; } else { if (angular.isUndefined(path.coordinates)) { return false; } if (path.type === 'Polygon') { if (path.coordinates[0].length < 4) { return false; } array = path.coordinates[0]; } else if (path.type === 'MultiPolygon') { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); polygon = path.coordinates[trackMaxVertices.index]; array = polygon[0]; if (array.length < 4) { return false; } } else if (path.type === 'LineString') { if (path.coordinates.length < 2) { return false; } array = path.coordinates; } else { return false; } while (i < array.length) { if (array[i].length !== 2) { return false; } i++; } return true; } }, convertPathPoints: function(path) { var array, i, latlng, result, trackMaxVertices; i = 0; result = new google.maps.MVCArray(); if (angular.isUndefined(path.type)) { while (i < path.length) { latlng; if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) { latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude); } else if (typeof path[i].lat === 'function' && typeof path[i].lng === 'function') { latlng = path[i]; } result.push(latlng); i++; } } else { array; if (path.type === 'Polygon') { array = path.coordinates[0]; } else if (path.type === 'MultiPolygon') { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); array = path.coordinates[trackMaxVertices.index][0]; } else if (path.type === 'LineString') { array = path.coordinates; } while (i < array.length) { result.push(new google.maps.LatLng(array[i][1], array[i][0])); i++; } } return result; }, extendMapBounds: function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }, getPath: function(object, key) { var obj; if ((key == null) || !_.isString(key)) { return key; } obj = object; _.each(key.split('.'), function(value) { if (obj) { return obj = obj[value]; } }); return obj; }, validateBoundPoints: function(bounds) { if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) { return false; } return true; }, convertBoundPoints: function(bounds) { var result; result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude)); return result; }, fitMapBounds: function(map, bounds) { return map.fitBounds(bounds); } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapIsReady', [ '$q', '$timeout', function($q, $timeout) { var ctr, promises, proms; ctr = 0; proms = []; promises = function() { return $q.all(proms); }; return { spawn: function() { var d; d = $q.defer(); proms.push(d.promise); ctr += 1; return { instance: ctr, deferred: d }; }, promises: promises, instances: function() { return ctr; }, promise: function(expect) { var d, ohCrap; if (expect == null) { expect = 1; } d = $q.defer(); ohCrap = function() { return $timeout(function() { if (ctr !== expect) { return ohCrap(); } else { return d.resolve(promises()); } }); }; ohCrap(); return d.promise; }, reset: function() { ctr = 0; return proms.length = 0; } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [ "uiGmapBaseObject", function(BaseObject) { var Linked; Linked = (function(superClass) { extend(Linked, superClass); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(BaseObject); return Linked; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapLogger', [ '$log', function($log) { var LEVELS, Logger, log, maybeExecLevel; LEVELS = { log: 1, info: 2, debug: 3, warn: 4, error: 5, none: 6 }; maybeExecLevel = function(level, current, fn) { if (level >= current) { return fn(); } }; log = function(logLevelFnName, msg) { if ($log != null) { return $log[logLevelFnName](msg); } else { return console[logLevelFnName](msg); } }; Logger = (function() { function Logger() { var logFns; this.doLog = true; logFns = {}; ['log', 'info', 'debug', 'warn', 'error'].forEach((function(_this) { return function(level) { return logFns[level] = function(msg) { if (_this.doLog) { return maybeExecLevel(LEVELS[level], _this.currentLevel, function() { return log(level, msg); }); } }; }; })(this)); this.LEVELS = LEVELS; this.currentLevel = LEVELS.error; this.log = logFns['log']; this.info = logFns['info']; this.debug = logFns['debug']; this.warn = logFns['warn']; this.error = logFns['error']; } Logger.prototype.spawn = function() { return new Logger(); }; Logger.prototype.setLog = function(someLogger) { return $log = someLogger; }; return Logger; })(); return new Logger(); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelKey', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapPromise', '$q', '$timeout', function(BaseObject, GmapUtil, uiGmapPromise, $q, $timeout) { var ModelKey; return ModelKey = (function(superClass) { extend(ModelKey, superClass); function ModelKey(scope1) { this.scope = scope1; this.modelsLength = bind(this.modelsLength, this); this.updateChild = bind(this.updateChild, this); this.destroy = bind(this.destroy, this); this.onDestroy = bind(this.onDestroy, this); this.setChildScope = bind(this.setChildScope, this); this.getChanges = bind(this.getChanges, this); this.getProp = bind(this.getProp, this); this.setIdKey = bind(this.setIdKey, this); this.modelKeyComparison = bind(this.modelKeyComparison, this); ModelKey.__super__.constructor.call(this); this["interface"] = {}; this["interface"].scopeKeys = []; this.defaultIdKey = 'id'; this.idKey = void 0; } ModelKey.prototype.evalModelHandle = function(model, modelKey) { if ((model == null) || (modelKey == null)) { return; } if (modelKey === 'self') { return model; } else { if (_.isFunction(modelKey)) { modelKey = modelKey(); } return GmapUtil.getPath(model, modelKey); } }; ModelKey.prototype.modelKeyComparison = function(model1, model2) { var hasCoords, isEqual, scope; hasCoords = _.contains(this["interface"].scopeKeys, 'coords'); if (hasCoords && (this.scope.coords != null) || !hasCoords) { scope = this.scope; } if (scope == null) { throw 'No scope set!'; } if (hasCoords) { isEqual = GmapUtil.equalCoords(this.scopeOrModelVal('coords', scope, model1), this.scopeOrModelVal('coords', scope, model2)); if (!isEqual) { return isEqual; } } isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) { return function(k) { return _this.scopeOrModelVal(scope[k], scope, model1) === _this.scopeOrModelVal(scope[k], scope, model2); }; })(this)); return isEqual; }; ModelKey.prototype.setIdKey = function(scope) { return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey; }; ModelKey.prototype.setVal = function(model, key, newValue) { var thingToSet; thingToSet = this.modelOrKey(model, key); thingToSet = newValue; return model; }; ModelKey.prototype.modelOrKey = function(model, key) { if (key == null) { return; } if (key !== 'self') { return GmapUtil.getPath(model, key); } return model; }; ModelKey.prototype.getProp = function(propName, scope, model) { return this.scopeOrModelVal(propName, scope, model); }; /* For the cases were watching a large object we only want to know the list of props that actually changed. Also we want to limit the amount of props we analyze to whitelisted props that are actually tracked by scope. (should make things faster with whitelisted) */ ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) { var c, changes, prop; if (whitelistedProps) { prev = _.pick(prev, whitelistedProps); now = _.pick(now, whitelistedProps); } changes = {}; prop = {}; c = {}; for (prop in now) { if (!prev || prev[prop] !== now[prop]) { if (_.isArray(now[prop])) { changes[prop] = now[prop]; } else if (_.isObject(now[prop])) { c = this.getChanges(now[prop], (prev ? prev[prop] : null)); if (!_.isEmpty(c)) { changes[prop] = c; } } else { changes[prop] = now[prop]; } } } return changes; }; ModelKey.prototype.scopeOrModelVal = function(key, scope, model, doWrap) { var maybeWrap, modelKey, modelProp, scopeProp; if (doWrap == null) { doWrap = false; } maybeWrap = function(isScope, ret, doWrap) { if (doWrap == null) { doWrap = false; } if (doWrap) { return { isScope: isScope, value: ret }; } return ret; }; scopeProp = scope[key]; if (_.isFunction(scopeProp)) { return maybeWrap(true, scopeProp(model), doWrap); } if (_.isObject(scopeProp)) { return maybeWrap(true, scopeProp, doWrap); } if (!_.isString(scopeProp)) { return maybeWrap(true, scopeProp, doWrap); } modelKey = scopeProp; if (!modelKey) { modelProp = model[key]; } else { modelProp = modelKey === 'self' ? model : model[modelKey]; } if (_.isFunction(modelProp)) { return maybeWrap(false, modelProp(), doWrap); } return maybeWrap(false, modelProp, doWrap); }; ModelKey.prototype.setChildScope = function(keys, childScope, model) { _.each(keys, (function(_this) { return function(name) { var isScopeObj, newValue; isScopeObj = _this.scopeOrModelVal(name, childScope, model, true); if ((isScopeObj != null ? isScopeObj.value : void 0) != null) { newValue = isScopeObj.value; if (newValue !== childScope[name]) { return childScope[name] = newValue; } } }; })(this)); return childScope.model = model; }; ModelKey.prototype.onDestroy = function(scope) {}; ModelKey.prototype.destroy = function(manualOverride) { var ref; if (manualOverride == null) { manualOverride = false; } if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { return this.scope.$destroy(); } else { return this.clean(); } }; ModelKey.prototype.updateChild = function(child, model) { if (model[this.idKey] == null) { this.$log.error("Model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } return child.updateModel(model); }; ModelKey.prototype.modelsLength = function(arrayOrObjModels) { var len, toCheck; if (arrayOrObjModels == null) { arrayOrObjModels = void 0; } len = 0; toCheck = arrayOrObjModels ? arrayOrObjModels : this.scope.models; if (toCheck == null) { return len; } if (angular.isArray(toCheck) || (toCheck.length != null)) { len = toCheck.length; } else { len = Object.keys(toCheck).length; } return len; }; return ModelKey; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').factory('uiGmapModelsWatcher', [ 'uiGmapLogger', 'uiGmap_async', '$q', 'uiGmapPromise', function(Logger, _async, $q, uiGmapPromise) { return { didQueueInitPromise: function(existingPiecesObj, scope) { if (scope.models.length === 0) { _async.promiseLock(existingPiecesObj, uiGmapPromise.promiseTypes.init, null, null, ((function(_this) { return function() { return uiGmapPromise.resolve(); }; })(this))); return true; } return false; }, figureOutState: function(idKey, scope, childObjects, comparison, callBack) { var adds, children, mappedScopeModelIds, removals, updates; adds = []; mappedScopeModelIds = {}; removals = []; updates = []; scope.models.forEach(function(m) { var child; if (m[idKey] != null) { mappedScopeModelIds[m[idKey]] = {}; if (childObjects.get(m[idKey]) == null) { return adds.push(m); } else { child = childObjects.get(m[idKey]); if (!comparison(m, child.clonedModel, scope)) { return updates.push({ model: m, child: child }); } } } else { return Logger.error(' id missing for model #{m.toString()},\ncan not use do comparison/insertion'); } }); children = childObjects.values(); children.forEach(function(c) { var id; if (c == null) { Logger.error('child undefined in ModelsWatcher.'); return; } if (c.model == null) { Logger.error('child.model undefined in ModelsWatcher.'); return; } id = c.model[idKey]; if (mappedScopeModelIds[id] == null) { return removals.push(c); } }); return { adds: adds, removals: removals, updates: updates }; } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [ '$q', '$timeout', 'uiGmapLogger', function($q, $timeout, $log) { var ExposedPromise, SniffedPromise, defer, isInProgress, isResolved, promise, promiseStatus, promiseStatuses, promiseTypes, resolve, strPromiseStatuses; promiseTypes = { create: 'create', update: 'update', "delete": 'delete', init: 'init' }; promiseStatuses = { IN_PROGRESS: 0, RESOLVED: 1, REJECTED: 2 }; strPromiseStatuses = (function() { var obj; obj = {}; obj["" + promiseStatuses.IN_PROGRESS] = 'in-progress'; obj["" + promiseStatuses.RESOLVED] = 'resolved'; obj["" + promiseStatuses.REJECTED] = 'rejected'; return obj; })(); isInProgress = function(promise) { if (promise.$$state) { return promise.$$state.status === promiseStatuses.IN_PROGRESS; } if (!promise.hasOwnProperty("$$v")) { return true; } }; isResolved = function(promise) { if (promise.$$state) { return promise.$$state.status === promiseStatuses.RESOLVED; } if (promise.hasOwnProperty("$$v")) { return true; } }; promiseStatus = function(status) { return strPromiseStatuses[status] || 'done w error'; }; ExposedPromise = function(promise) { var cancelDeferred, combined, wrapped; cancelDeferred = $q.defer(); combined = $q.all([promise, cancelDeferred.promise]); wrapped = $q.defer(); promise.then(cancelDeferred.resolve, (function() {}), function(notify) { cancelDeferred.notify(notify); return wrapped.notify(notify); }); combined.then(function(successes) { return wrapped.resolve(successes[0] || successes[1]); }, function(error) { return wrapped.reject(error); }); wrapped.promise.cancel = function(reason) { if (reason == null) { reason = 'canceled'; } return cancelDeferred.reject(reason); }; wrapped.promise.notify = function(msg) { if (msg == null) { msg = 'cancel safe'; } wrapped.notify(msg); if (promise.hasOwnProperty('notify')) { return promise.notify(msg); } }; if (promise.promiseType != null) { wrapped.promise.promiseType = promise.promiseType; } return wrapped.promise; }; SniffedPromise = function(fnPromise, promiseType) { return { promise: fnPromise, promiseType: promiseType }; }; defer = function() { return $q.defer(); }; resolve = function() { var d; d = $q.defer(); d.resolve.apply(void 0, arguments); return d.promise; }; promise = function(fnToWrap) { var d; if (!_.isFunction(fnToWrap)) { $log.error("uiGmapPromise.promise() only accepts functions"); return; } d = $q.defer(); $timeout(function() { var result; result = fnToWrap(); return d.resolve(result); }); return d.promise; }; return { defer: defer, promise: promise, resolve: resolve, promiseTypes: promiseTypes, isInProgress: isInProgress, isResolved: isResolved, promiseStatus: promiseStatus, ExposedPromise: ExposedPromise, SniffedPromise: SniffedPromise }; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() { /* Simple Object Map with a length property to make it easy to track length/size */ var PropMap; return PropMap = (function() { function PropMap() { this.removeAll = bind(this.removeAll, this); this.slice = bind(this.slice, this); this.push = bind(this.push, this); this.keys = bind(this.keys, this); this.values = bind(this.values, this); this.remove = bind(this.remove, this); this.put = bind(this.put, this); this.stateChanged = bind(this.stateChanged, this); this.get = bind(this.get, this); this.length = 0; this.dict = {}; this.didValsStateChange = false; this.didKeysStateChange = false; this.allVals = []; this.allKeys = []; } PropMap.prototype.get = function(key) { return this.dict[key]; }; PropMap.prototype.stateChanged = function() { this.didValsStateChange = true; return this.didKeysStateChange = true; }; PropMap.prototype.put = function(key, value) { if (this.get(key) == null) { this.length++; } this.stateChanged(); return this.dict[key] = value; }; PropMap.prototype.remove = function(key, isSafe) { var value; if (isSafe == null) { isSafe = false; } if (isSafe && !this.get(key)) { return void 0; } value = this.dict[key]; delete this.dict[key]; this.length--; this.stateChanged(); return value; }; PropMap.prototype.valuesOrKeys = function(str) { var keys, vals; if (str == null) { str = 'Keys'; } if (!this["did" + str + "StateChange"]) { return this['all' + str]; } vals = []; keys = []; _.each(this.dict, function(v, k) { vals.push(v); return keys.push(k); }); this.didKeysStateChange = false; this.didValsStateChange = false; this.allVals = vals; this.allKeys = keys; return this['all' + str]; }; PropMap.prototype.values = function() { return this.valuesOrKeys('Vals'); }; PropMap.prototype.keys = function() { return this.valuesOrKeys(); }; PropMap.prototype.push = function(obj, key) { if (key == null) { key = "key"; } return this.put(obj[key], obj); }; PropMap.prototype.slice = function() { return this.keys().map((function(_this) { return function(k) { return _this.remove(k); }; })(this)); }; PropMap.prototype.removeAll = function() { return this.slice(); }; PropMap.prototype.each = function(cb) { return _.each(this.dict, function(v, k) { return cb(v); }); }; PropMap.prototype.map = function(cb) { return _.map(this.dict, function(v, k) { return cb(v); }); }; return PropMap; })(); }); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropertyAction", [ "uiGmapLogger", function(Logger) { var PropertyAction; PropertyAction = function(setterFn) { this.setIfChange = function(newVal, oldVal) { var callingKey; callingKey = this.exp; if (!_.isEqual(oldVal, newVal)) { return setterFn(callingKey, newVal); } }; this.sic = this.setIfChange; return this; }; return PropertyAction; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps.directives.api.managers').factory('uiGmapClustererMarkerManager', [ 'uiGmapLogger', 'uiGmapFitHelper', 'uiGmapPropMap', function($log, FitHelper, PropMap) { var ClustererMarkerManager; ClustererMarkerManager = (function() { ClustererMarkerManager.type = 'ClustererMarkerManager'; function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) { if (opt_markers == null) { opt_markers = {}; } this.opt_options = opt_options != null ? opt_options : {}; this.opt_events = opt_events; this.checkSync = bind(this.checkSync, this); this.getGMarkers = bind(this.getGMarkers, this); this.fit = bind(this.fit, this); this.destroy = bind(this.destroy, this); this.clear = bind(this.clear, this); this.draw = bind(this.draw, this); this.removeMany = bind(this.removeMany, this); this.remove = bind(this.remove, this); this.addMany = bind(this.addMany, this); this.update = bind(this.update, this); this.add = bind(this.add, this); this.type = ClustererMarkerManager.type; this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, this.opt_options); this.propMapGMarkers = new PropMap(); this.attachEvents(this.opt_events, 'opt_events'); this.clusterer.setIgnoreHidden(true); this.noDrawOnSingleAddRemoves = true; $log.info(this); } ClustererMarkerManager.prototype.checkKey = function(gMarker) { var msg; if (gMarker.key == null) { msg = 'gMarker.key undefined and it is REQUIRED!!'; return $log.error(msg); } }; ClustererMarkerManager.prototype.add = function(gMarker) { this.checkKey(gMarker); this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.put(gMarker.key, gMarker); return this.checkSync(); }; ClustererMarkerManager.prototype.update = function(gMarker) { this.remove(gMarker); return this.add(gMarker); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.remove(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.removeMany(this.getGMarkers()); return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) { var eventHandler, eventName, results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info(optionsName + ": Attaching event: " + eventName + " to clusterer"); results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName])); } else { results.push(void 0); } } return results; } }; ClustererMarkerManager.prototype.clearEvents = function(options, optionsName) { var eventHandler, eventName, results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info(optionsName + ": Clearing event: " + eventName + " to clusterer"); results.push(google.maps.event.clearListeners(this.clusterer, eventName)); } else { results.push(void 0); } } return results; } }; ClustererMarkerManager.prototype.destroy = function() { this.clearEvents(this.opt_events, 'opt_events'); return this.clear(); }; ClustererMarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.clusterer.getMap()); }; ClustererMarkerManager.prototype.getGMarkers = function() { return this.clusterer.getMarkers().values(); }; ClustererMarkerManager.prototype.checkSync = function() {}; return ClustererMarkerManager; })(); return ClustererMarkerManager; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps.directives.api.managers").factory("uiGmapMarkerManager", [ "uiGmapLogger", "uiGmapFitHelper", "uiGmapPropMap", function(Logger, FitHelper, PropMap) { var MarkerManager; MarkerManager = (function() { MarkerManager.type = 'MarkerManager'; function MarkerManager(gMap, opt_markers, opt_options) { this.getGMarkers = bind(this.getGMarkers, this); this.fit = bind(this.fit, this); this.handleOptDraw = bind(this.handleOptDraw, this); this.clear = bind(this.clear, this); this.draw = bind(this.draw, this); this.removeMany = bind(this.removeMany, this); this.remove = bind(this.remove, this); this.addMany = bind(this.addMany, this); this.update = bind(this.update, this); this.add = bind(this.add, this); this.type = MarkerManager.type; this.gMap = gMap; this.gMarkers = new PropMap(); this.$log = Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { var exists, msg; if (optDraw == null) { optDraw = true; } if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; Logger.error(msg); throw msg; } exists = this.gMarkers.get(gMarker.key); if (!exists) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.put(gMarker.key, gMarker); } }; MarkerManager.prototype.update = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.remove(gMarker, optDraw); return this.add(gMarker, optDraw); }; MarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; MarkerManager.prototype.remove = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.handleOptDraw(gMarker, optDraw, false); if (this.gMarkers.get(gMarker.key)) { return this.gMarkers.remove(gMarker.key); } }; MarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(marker) { return _this.remove(marker); }; })(this)); }; MarkerManager.prototype.draw = function() { var deletes; deletes = []; this.gMarkers.each((function(_this) { return function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { gMarker.setMap(_this.gMap); return gMarker.isDrawn = true; } else { return deletes.push(gMarker); } } }; })(this)); return deletes.forEach((function(_this) { return function(gMarker) { gMarker.isDrawn = false; return _this.remove(gMarker, true); }; })(this)); }; MarkerManager.prototype.clear = function() { this.gMarkers.each(function(gMarker) { return gMarker.setMap(null); }); delete this.gMarkers; return this.gMarkers = new PropMap(); }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; MarkerManager.prototype.fit = function() { return FitHelper.fit(this.getGMarkers(), this.gMap); }; MarkerManager.prototype.getGMarkers = function() { return this.gMarkers.values(); }; return MarkerManager; })(); return MarkerManager; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').factory('uiGmapadd-events', [ '$timeout', function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(listener) { return google.maps.event.removeListener(listener); }); return remove = null; }; }; return addEvents; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').factory('uiGmaparray-sync', [ 'uiGmapadd-events', function(mapEvents) { return function(mapArray, scope, pathEval, pathChangedFn) { var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener; isSetFromScope = false; scopePath = scope.$eval(pathEval); if (!scope["static"]) { legacyHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath[index] = value; } else { scopePath[index].latitude = value.lat(); return scopePath[index].longitude = value.lng(); } }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath.splice(index, 0, value); } else { return scopePath.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); } }, remove_at: function(index) { if (isSetFromScope) { return; } return scopePath.splice(index, 1); } }; geojsonArray; if (scopePath.type === 'Polygon') { geojsonArray = scopePath.coordinates[0]; } else if (scopePath.type === 'LineString') { geojsonArray = scopePath.coordinates; } geojsonHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } geojsonArray[index][1] = value.lat(); return geojsonArray[index][0] = value.lng(); }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return geojsonArray.splice(index, 0, [value.lng(), value.lat()]); }, remove_at: function(index) { if (isSetFromScope) { return; } return geojsonArray.splice(index, 1); } }; mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers); } legacyWatcher = function(newPath) { var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { i = 0; oldLength = oldArray.getLength(); newLength = newPath.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newPath[i]; if (typeof newValue.equals === 'function') { if (!newValue.equals(oldValue)) { oldArray.setAt(i, newValue); changed = true; } } else { if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); changed = true; } } i++; } while (i < newLength) { newValue = newPath[i]; if (typeof newValue.lat === 'function' && typeof newValue.lng === 'function') { oldArray.push(newValue); } else { oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; geojsonWatcher = function(newPath) { var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { array; if (scopePath.type === 'Polygon') { array = newPath.coordinates[0]; } else if (scopePath.type === 'LineString') { array = newPath.coordinates; } i = 0; oldLength = oldArray.getLength(); newLength = array.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = array[i]; if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) { oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0])); changed = true; } i++; } while (i < newLength) { newValue = array[i]; oldArray.push(new google.maps.LatLng(newValue[1], newValue[0])); changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; watchListener; if (!scope["static"]) { if (angular.isUndefined(scopePath.type)) { watchListener = scope.$watchCollection(pathEval, legacyWatcher); } else { watchListener = scope.$watch(pathEval, geojsonWatcher, true); } } return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapChromeFixes", [ '$timeout', function($timeout) { return { maybeRepaint: function(el) { if (el) { el.style.opacity = 0.9; return $timeout(function() { return el.style.opacity = 1; }); } } }; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').service('uiGmapObjectIterators', function() { var _ignores, _iterators, _slapForEach, _slapMap; _ignores = ['length', 'forEach', 'map']; _iterators = []; _slapForEach = function(object) { object.forEach = function(cb) { return _.each(_.omit(object, _ignores), function(val) { if (!_.isFunction(val)) { return cb(val); } }); }; return object; }; _iterators.push(_slapForEach); _slapMap = function(object) { object.map = function(cb) { return _.map(_.omit(object, _ignores), function(val) { if (!_.isFunction(val)) { return cb(val); } }); }; return object; }; _iterators.push(_slapMap); return { slapMap: _slapMap, slapForEach: _slapForEach, slapAll: function(object) { _iterators.forEach(function(it) { return it(object); }); return object; } }; }); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.options.builders').service('uiGmapCommonOptionsBuilder', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapModelKey', function(BaseObject, $log, ModelKey) { var CommonOptionsBuilder; return CommonOptionsBuilder = (function(superClass) { extend(CommonOptionsBuilder, superClass); function CommonOptionsBuilder() { this.watchProps = bind(this.watchProps, this); this.buildOpts = bind(this.buildOpts, this); return CommonOptionsBuilder.__super__.constructor.apply(this, arguments); } CommonOptionsBuilder.prototype.props = [ 'clickable', 'draggable', 'editable', 'visible', { prop: 'stroke', isColl: true } ]; CommonOptionsBuilder.prototype.getCorrectModel = function(scope) { if (angular.isDefined(scope != null ? scope.model : void 0)) { return scope.model; } else { return scope; } }; CommonOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var model, opts, stroke; if (customOpts == null) { customOpts = {}; } if (forEachOpts == null) { forEachOpts = {}; } if (!this.scope) { $log.error('this.scope not defined in CommonOptionsBuilder can not buildOpts'); return; } if (!this.map) { $log.error('this.map not defined in CommonOptionsBuilder can not buildOpts'); return; } model = this.getCorrectModel(this.scope); stroke = this.scopeOrModelVal('stroke', this.scope, model); opts = angular.extend(customOpts, this.DEFAULTS, { map: this.map, strokeColor: stroke != null ? stroke.color : void 0, strokeOpacity: stroke != null ? stroke.opacity : void 0, strokeWeight: stroke != null ? stroke.weight : void 0 }); angular.forEach(angular.extend(forEachOpts, { clickable: true, draggable: false, editable: false, "static": false, fit: false, visible: true, zIndex: 0, icons: [] }), (function(_this) { return function(defaultValue, key) { var val; val = cachedEval ? cachedEval[key] : _this.scopeOrModelVal(key, _this.scope, model); if (angular.isUndefined(val)) { return opts[key] = defaultValue; } else { return opts[key] = model[key]; } }; })(this)); if (opts["static"]) { opts.editable = false; } return opts; }; CommonOptionsBuilder.prototype.watchProps = function(props) { if (props == null) { props = this.props; } return props.forEach((function(_this) { return function(prop) { if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) { if (prop != null ? prop.isColl : void 0) { return _this.scope.$watchCollection(prop.prop, _this.setMyOptions); } else { return _this.scope.$watch(prop, _this.setMyOptions); } } }; })(this)); }; return CommonOptionsBuilder; })(ModelKey); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.options.builders').factory('uiGmapPolylineOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var PolylineOptionsBuilder; return PolylineOptionsBuilder = (function(superClass) { extend(PolylineOptionsBuilder, superClass); function PolylineOptionsBuilder() { return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments); } PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolylineOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolylineOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapShapeOptionsBuilder', [ 'uiGmapCommonOptionsBuilder', function(CommonOptionsBuilder) { var ShapeOptionsBuilder; return ShapeOptionsBuilder = (function(superClass) { extend(ShapeOptionsBuilder, superClass); function ShapeOptionsBuilder() { return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments); } ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, cachedEval, forEachOpts) { var fill, model; model = this.getCorrectModel(this.scope); fill = cachedEval ? cachedEval['fill'] : this.scopeOrModelVal('fill', this.scope, model); customOpts = angular.extend(customOpts, { fillColor: fill != null ? fill.color : void 0, fillOpacity: fill != null ? fill.opacity : void 0 }); return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, cachedEval, forEachOpts); }; return ShapeOptionsBuilder; })(CommonOptionsBuilder); } ]).factory('uiGmapPolygonOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var PolygonOptionsBuilder; return PolygonOptionsBuilder = (function(superClass) { extend(PolygonOptionsBuilder, superClass); function PolygonOptionsBuilder() { return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments); } PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints, cachedEval) { return PolygonOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, cachedEval, { geodesic: false }); }; return PolygonOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapRectangleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var RectangleOptionsBuilder; return RectangleOptionsBuilder = (function(superClass) { extend(RectangleOptionsBuilder, superClass); function RectangleOptionsBuilder() { return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments); } RectangleOptionsBuilder.prototype.buildOpts = function(bounds, cachedEval) { return RectangleOptionsBuilder.__super__.buildOpts.call(this, { bounds: bounds }, cachedEval); }; return RectangleOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory('uiGmapCircleOptionsBuilder', [ 'uiGmapShapeOptionsBuilder', function(ShapeOptionsBuilder) { var CircleOptionsBuilder; return CircleOptionsBuilder = (function(superClass) { extend(CircleOptionsBuilder, superClass); function CircleOptionsBuilder() { return CircleOptionsBuilder.__super__.constructor.apply(this, arguments); } CircleOptionsBuilder.prototype.buildOpts = function(center, radius, cachedEval) { return CircleOptionsBuilder.__super__.buildOpts.call(this, { center: center, radius: radius }, cachedEval); }; return CircleOptionsBuilder; })(ShapeOptionsBuilder); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api.options').service('uiGmapMarkerOptions', [ 'uiGmapLogger', 'uiGmapGmapUtil', function($log, GmapUtil) { return _.extend(GmapUtil, { createOptions: function(coords, icon, defaults, map) { var opts; if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords), visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, isLabel: function(options) { if (options == null) { return false; } return (options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null); } }); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapBasePolyChildModel', [ 'uiGmapLogger', '$timeout', 'uiGmaparray-sync', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function($log, $timeout, arraySync, GmapUtil, EventsHelper) { return function(Builder, gFactory) { var BasePolyChildModel; return BasePolyChildModel = (function(superClass) { extend(BasePolyChildModel, superClass); BasePolyChildModel.include(GmapUtil); function BasePolyChildModel(scope1, attrs, map1, defaults, model) { var create; this.scope = scope1; this.attrs = attrs; this.map = map1; this.defaults = defaults; this.model = model; this.clean = bind(this.clean, this); this.clonedModel = _.clone(this.model, true); this.isDragging = false; this.internalEvents = { dragend: (function(_this) { return function() { return _.defer(function() { return _this.isDragging = false; }); }; })(this), dragstart: (function(_this) { return function() { return _this.isDragging = true; }; })(this) }; create = (function(_this) { return function() { var maybeCachedEval, pathPoints; if (_this.isDragging) { return; } pathPoints = _this.convertPathPoints(_this.scope.path); if (_this.gObject != null) { _this.clean(); } if (_this.scope.model != null) { maybeCachedEval = _this.scope; } if (pathPoints.length > 0) { _this.gObject = gFactory(_this.buildOpts(pathPoints, maybeCachedEval)); } if (_this.gObject) { if (_this.scope.fit) { _this.extendMapBounds(map, pathPoints); } arraySync(_this.gObject.getPath(), _this.scope, 'path', function(pathPoints) { if (_this.scope.fit) { return _this.extendMapBounds(map, pathPoints); } }); if (angular.isDefined(_this.scope.events) && angular.isObject(_this.scope.events)) { _this.listeners = _this.model ? EventsHelper.setEvents(_this.gObject, _this.scope, _this.model) : EventsHelper.setEvents(_this.gObject, _this.scope, _this.scope); } return _this.internalListeners = _this.model ? EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.model) : EventsHelper.setEvents(_this.gObject, { events: _this.internalEvents }, _this.scope); } }; })(this); create(); this.scope.$watch('path', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.gObject) { return create(); } }; })(this), true); if (!this.scope["static"] && angular.isDefined(this.scope.editable)) { this.scope.$watch('editable', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref = _this.gObject) != null ? ref.setEditable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.draggable)) { this.scope.$watch('draggable', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref = _this.gObject) != null ? ref.setDraggable(newValue) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.visible)) { this.scope.$watch('visible', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); } return (ref = _this.gObject) != null ? ref.setVisible(newValue) : void 0; }; })(this), true); } if (angular.isDefined(this.scope.geodesic)) { this.scope.$watch('geodesic', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { newValue = !_this.isFalse(newValue); return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.weight)) { this.scope.$watch('stroke.weight', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.color)) { this.scope.$watch('stroke.color', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.stroke) && angular.isDefined(this.scope.stroke.opacity)) { scope.$watch('stroke.opacity', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } if (angular.isDefined(this.scope.icons)) { this.scope.$watch('icons', (function(_this) { return function(newValue, oldValue) { var ref; if (newValue !== oldValue) { return (ref = _this.gObject) != null ? ref.setOptions(_this.buildOpts(_this.gObject.getPath())) : void 0; } }; })(this), true); } this.scope.$on('$destroy', (function(_this) { return function() { _this.clean(); return _this.scope = null; }; })(this)); if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.color)) { this.scope.$watch('fill.color', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(this.scope.fill) && angular.isDefined(this.scope.fill.opacity)) { this.scope.$watch('fill.opacity', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } if (angular.isDefined(this.scope.zIndex)) { this.scope.$watch('zIndex', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.gObject.setOptions(_this.buildOpts(_this.gObject.getPath())); } }; })(this)); } } BasePolyChildModel.prototype.clean = function() { var ref; EventsHelper.removeEvents(this.listeners); EventsHelper.removeEvents(this.internalListeners); if ((ref = this.gObject) != null) { ref.setMap(null); } return this.gObject = null; }; return BasePolyChildModel; })(Builder); }; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , & http://jsfiddle.net/YsQdh/88/ */ (function() { angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapDrawFreeHandChildModel', [ 'uiGmapLogger', '$q', function($log, $q) { var drawFreeHand, freeHandMgr; drawFreeHand = function(map, polys, done) { var move, poly; poly = new google.maps.Polyline({ map: map, clickable: false }); move = google.maps.event.addListener(map, 'mousemove', function(e) { return poly.getPath().push(e.latLng); }); google.maps.event.addListenerOnce(map, 'mouseup', function(e) { var path; google.maps.event.removeListener(move); path = poly.getPath(); poly.setMap(null); polys.push(new google.maps.Polygon({ map: map, path: path })); poly = null; google.maps.event.clearListeners(map.getDiv(), 'mousedown'); return done(); }); return void 0; }; freeHandMgr = function(map1, scope) { var disableMap, enableMap; this.map = map1; disableMap = (function(_this) { return function() { var mapOptions; mapOptions = { draggable: false, disableDefaultUI: true, scrollwheel: false, disableDoubleClickZoom: false }; $log.info('disabling map move'); return _this.map.setOptions(mapOptions); }; })(this); enableMap = (function(_this) { return function() { var mapOptions, ref; mapOptions = { draggable: true, disableDefaultUI: false, scrollwheel: true, disableDoubleClickZoom: true }; if ((ref = _this.deferred) != null) { ref.resolve(); } return _.defer(function() { return _this.map.setOptions(_.extend(mapOptions, scope.options)); }); }; })(this); this.engage = (function(_this) { return function(polys1) { _this.polys = polys1; _this.deferred = $q.defer(); disableMap(); $log.info('DrawFreeHandChildModel is engaged (drawing).'); google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) { return drawFreeHand(_this.map, _this.polys, enableMap); }); return _this.deferred.promise; }; })(this); return this; }; return freeHandMgr; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapMarkerChildModel', [ 'uiGmapModelKey', 'uiGmapGmapUtil', 'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction', 'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise', function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) { var MarkerChildModel; MarkerChildModel = (function(superClass) { var destroy; extend(MarkerChildModel, superClass); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); MarkerChildModel.include(MarkerOptions); destroy = function(child) { if ((child != null ? child.gObject : void 0) != null) { child.removeEvents(child.externalListeners); child.removeEvents(child.internalListeners); if (child != null ? child.gObject : void 0) { if (child.removeFromManager) { child.gManager.remove(child.gObject); } child.gObject.setMap(null); return child.gObject = null; } } }; function MarkerChildModel(scope, model1, keys, gMap, defaults, doClick, gManager, doDrawSelf, trackModel, needRedraw) { var action; this.model = model1; this.keys = keys; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gManager = gManager; this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true; this.trackModel = trackModel != null ? trackModel : true; this.needRedraw = needRedraw != null ? needRedraw : false; this.internalEvents = bind(this.internalEvents, this); this.setLabelOptions = bind(this.setLabelOptions, this); this.setOptions = bind(this.setOptions, this); this.setIcon = bind(this.setIcon, this); this.setCoords = bind(this.setCoords, this); this.isNotValid = bind(this.isNotValid, this); this.maybeSetScopeValue = bind(this.maybeSetScopeValue, this); this.createMarker = bind(this.createMarker, this); this.setMyScope = bind(this.setMyScope, this); this.updateModel = bind(this.updateModel, this); this.handleModelChanges = bind(this.handleModelChanges, this); this.destroy = bind(this.destroy, this); this.clonedModel = _.extend({}, this.model); this.deferred = uiGmapPromise.defer(); _.each(this.keys, (function(_this) { return function(v, k) { var keyValue; keyValue = _this.keys[k]; if ((keyValue != null) && !_.isFunction(keyValue) && _.isString(keyValue)) { return _this[k + 'Key'] = keyValue; } }; })(this)); this.idKey = this.idKeyKey || 'id'; if (this.model[this.idKey] != null) { this.id = this.model[this.idKey]; } MarkerChildModel.__super__.constructor.call(this, scope); this.scope.getGMarker = (function(_this) { return function() { return _this.gObject; }; })(this); this.firstTime = true; if (this.trackModel) { this.scope.model = this.model; this.scope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.handleModelChanges(newValue, oldValue); } }; })(this), true); } else { action = new PropertyAction((function(_this) { return function(calledKey, newVal) { if (!_this.firstTime) { return _this.setMyScope(calledKey, scope); } }; })(this), false); _.each(this.keys, function(v, k) { return scope.$watch(k, action.sic, true); }); } this.scope.$on('$destroy', (function(_this) { return function() { return destroy(_this); }; })(this)); this.createMarker(this.model); $log.info(this); } MarkerChildModel.prototype.destroy = function(removeFromManager) { if (removeFromManager == null) { removeFromManager = true; } this.removeFromManager = removeFromManager; return this.scope.$destroy(); }; MarkerChildModel.prototype.handleModelChanges = function(newValue, oldValue) { var changes, ctr, len; changes = this.getChanges(newValue, oldValue, IMarker.keys); if (!this.firstTime) { ctr = 0; len = _.keys(changes).length; return _.each(changes, (function(_this) { return function(v, k) { var doDraw; ctr += 1; doDraw = len === ctr; _this.setMyScope(k, newValue, oldValue, false, true, doDraw); return _this.needRedraw = true; }; })(this)); } }; MarkerChildModel.prototype.updateModel = function(model) { this.clonedModel = _.extend({}, model); return this.setMyScope('all', model, this.model); }; MarkerChildModel.prototype.renderGMarker = function(doDraw, validCb) { var coords; if (doDraw == null) { doDraw = true; } coords = this.getProp('coords', this.scope, this.model); if (coords != null) { if (!this.validateCoords(coords)) { $log.debug('MarkerChild does not have coords yet. They may be defined later.'); return; } if (validCb != null) { validCb(); } if (doDraw && this.gObject) { return this.gManager.add(this.gObject); } } else { if (doDraw && this.gObject) { return this.gManager.remove(this.gObject); } } }; MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit, doDraw) { var justCreated; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (doDraw == null) { doDraw = true; } if (model == null) { model = this.model; } else { this.model = model; } if (!this.gObject) { this.setOptions(this.scope, doDraw); justCreated = true; } switch (thingThatChanged) { case 'all': return _.each(this.keys, (function(_this) { return function(v, k) { return _this.setMyScope(k, model, oldModel, isInit, doDraw); }; })(this)); case 'icon': return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon, doDraw); case 'coords': return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords, doDraw); case 'options': if (!justCreated) { return this.createMarker(model, oldModel, isInit, doDraw); } } }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit, doDraw) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (doDraw == null) { doDraw = true; } this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions, doDraw); return this.firstTime = false; }; MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter, doDraw) { if (gSetter == null) { gSetter = void 0; } if (doDraw == null) { doDraw = true; } if (gSetter != null) { return gSetter(this.scope, doDraw); } }; if (MarkerChildModel.doDrawSelf && doDraw) { MarkerChildModel.gManager.draw(); } MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) { var hasIdenticalScopes, hasNoGmarker; if (doCheckGmarker == null) { doCheckGmarker = true; } hasNoGmarker = !doCheckGmarker ? false : this.gObject === void 0; hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false; return hasIdenticalScopes || hasNoGmarker; }; MarkerChildModel.prototype.setCoords = function(scope, doDraw) { if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope) || (this.gObject == null)) { return; } return this.renderGMarker(doDraw, (function(_this) { return function() { var newGValue, newModelVal, oldGValue; newModelVal = _this.getProp('coords', scope, _this.model); newGValue = _this.getCoords(newModelVal); oldGValue = _this.gObject.getPosition(); if ((oldGValue != null) && (newGValue != null)) { if (newGValue.lng() === oldGValue.lng() && newGValue.lat() === oldGValue.lat()) { return; } } _this.gObject.setPosition(newGValue); return _this.gObject.setVisible(_this.validateCoords(newModelVal)); }; })(this)); }; MarkerChildModel.prototype.setIcon = function(scope, doDraw) { if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope) || (this.gObject == null)) { return; } return this.renderGMarker(doDraw, (function(_this) { return function() { var coords, newValue, oldValue; oldValue = _this.gObject.getIcon(); newValue = _this.getProp('icon', scope, _this.model); if (oldValue === newValue) { return; } _this.gObject.setIcon(newValue); coords = _this.getProp('coords', scope, _this.model); _this.gObject.setPosition(_this.getCoords(coords)); return _this.gObject.setVisible(_this.validateCoords(coords)); }; })(this)); }; MarkerChildModel.prototype.setOptions = function(scope, doDraw) { var ref; if (doDraw == null) { doDraw = true; } if (this.isNotValid(scope, false)) { return; } this.renderGMarker(doDraw, (function(_this) { return function() { var _options, coords, icon; coords = _this.getProp('coords', scope, _this.model); icon = _this.getProp('icon', scope, _this.model); _options = _this.getProp('options', scope, _this.model); _this.opts = _this.createOptions(coords, icon, _options); if (_this.isLabel(_this.gObject) !== _this.isLabel(_this.opts) && (_this.gObject != null)) { _this.gManager.remove(_this.gObject); _this.gObject = void 0; } if (_this.gObject != null) { _this.gObject.setOptions(_this.setLabelOptions(_this.opts)); } if (!_this.gObject) { if (_this.isLabel(_this.opts)) { _this.gObject = new MarkerWithLabel(_this.setLabelOptions(_this.opts)); } else { _this.gObject = new google.maps.Marker(_this.opts); } _.extend(_this.gObject, { model: _this.model }); } if (_this.externalListeners) { _this.removeEvents(_this.externalListeners); } if (_this.internalListeners) { _this.removeEvents(_this.internalListeners); } _this.externalListeners = _this.setEvents(_this.gObject, _this.scope, _this.model, ['dragend']); _this.internalListeners = _this.setEvents(_this.gObject, { events: _this.internalEvents(), $evalAsync: function() {} }, _this.model); if (_this.id != null) { return _this.gObject.key = _this.id; } }; })(this)); if (this.gObject && (this.gObject.getMap() || this.gManager.type !== MarkerManager.type)) { this.deferred.resolve(this.gObject); } else { if (!this.gObject) { return this.deferred.reject('gObject is null'); } if (!(((ref = this.gObject) != null ? ref.getMap() : void 0) && this.gManager.type === MarkerManager.type)) { $log.debug('gObject has no map yet'); this.deferred.resolve(this.gObject); } } if (this.model[this.fitKey]) { return this.gManager.fit(); } }; MarkerChildModel.prototype.setLabelOptions = function(opts) { opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor); return opts; }; MarkerChildModel.prototype.internalEvents = function() { return { dragend: (function(_this) { return function(marker, eventName, model, mousearg) { var events, modelToSet, newCoords; modelToSet = _this.trackModel ? _this.scope.model : _this.model; newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gObject.getPosition()); modelToSet = _this.setVal(model, _this.coordsKey, newCoords); events = _this.scope.events; if ((events != null ? events.dragend : void 0) != null) { events.dragend(marker, eventName, modelToSet, mousearg); } return _this.scope.$apply(); }; })(this), click: (function(_this) { return function(marker, eventName, model, mousearg) { var click; click = _this.getProp('click', _this.scope, _this.model); if (_this.doClick && (click != null)) { return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg)); } }; })(this) }; }; return MarkerChildModel; })(ModelKey); return MarkerChildModel; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygonChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolygonOptionsBuilder', function(BaseGen, Builder) { var PolygonChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polygon(opts); }; base = new BaseGen(Builder, gFactory); return PolygonChildModel = (function(superClass) { extend(PolygonChildModel, superClass); function PolygonChildModel() { return PolygonChildModel.__super__.constructor.apply(this, arguments); } return PolygonChildModel; })(base); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylineChildModel', [ 'uiGmapBasePolyChildModel', 'uiGmapPolylineOptionsBuilder', function(BaseGen, Builder) { var PolylineChildModel, base, gFactory; gFactory = function(opts) { return new google.maps.Polyline(opts); }; base = BaseGen(Builder, gFactory); return PolylineChildModel = (function(superClass) { extend(PolylineChildModel, superClass); function PolylineChildModel() { return PolylineChildModel.__super__.constructor.apply(this, arguments); } return PolylineChildModel; })(base); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.child').factory('uiGmapWindowChildModel', [ 'uiGmapBaseObject', 'uiGmapGmapUtil', 'uiGmapLogger', '$compile', '$http', '$templateCache', 'uiGmapChromeFixes', 'uiGmapEventsHelper', function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache, ChromeFixes, EventsHelper) { var WindowChildModel; WindowChildModel = (function(superClass) { extend(WindowChildModel, superClass); WindowChildModel.include(GmapUtil); WindowChildModel.include(EventsHelper); function WindowChildModel(model1, scope1, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) { var maybeMarker; this.model = model1; this.scope = scope1; this.opts = opts; this.isIconVisibleOnClick = isIconVisibleOnClick; this.mapCtrl = mapCtrl; this.markerScope = markerScope; this.element = element; this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false; this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true; this.updateModel = bind(this.updateModel, this); this.destroy = bind(this.destroy, this); this.remove = bind(this.remove, this); this.getLatestPosition = bind(this.getLatestPosition, this); this.hideWindow = bind(this.hideWindow, this); this.showWindow = bind(this.showWindow, this); this.handleClick = bind(this.handleClick, this); this.watchOptions = bind(this.watchOptions, this); this.watchCoords = bind(this.watchCoords, this); this.createGWin = bind(this.createGWin, this); this.watchElement = bind(this.watchElement, this); this.watchAndDoShow = bind(this.watchAndDoShow, this); this.doShow = bind(this.doShow, this); this.clonedModel = _.clone(this.model, true); this.getGmarker = function() { var ref, ref1; if (((ref = this.markerScope) != null ? ref['getGMarker'] : void 0) != null) { return (ref1 = this.markerScope) != null ? ref1.getGMarker() : void 0; } }; this.listeners = []; this.createGWin(); maybeMarker = this.getGmarker(); if (maybeMarker != null) { maybeMarker.setClickable(true); } this.watchElement(); this.watchOptions(); this.watchCoords(); this.watchAndDoShow(); this.scope.$on('$destroy', (function(_this) { return function() { return _this.destroy(); }; })(this)); $log.info(this); } WindowChildModel.prototype.doShow = function(wasOpen) { if (this.scope.show === true || wasOpen) { return this.showWindow(); } else { return this.hideWindow(); } }; WindowChildModel.prototype.watchAndDoShow = function() { if (this.model.show != null) { this.scope.show = this.model.show; } this.scope.$watch('show', this.doShow, true); return this.doShow(); }; WindowChildModel.prototype.watchElement = function() { return this.scope.$watch((function(_this) { return function() { var ref, wasOpen; if (!(_this.element || _this.html)) { return; } if (_this.html !== _this.element.html() && _this.gObject) { if ((ref = _this.opts) != null) { ref.content = void 0; } wasOpen = _this.gObject.isOpen(); _this.remove(); return _this.createGWin(wasOpen); } }; })(this)); }; WindowChildModel.prototype.createGWin = function(isOpen) { var _opts, defaults, maybeMarker, ref, ref1; if (isOpen == null) { isOpen = false; } maybeMarker = this.getGmarker(); defaults = {}; if (this.opts != null) { if (this.scope.coords) { this.opts.position = this.getCoords(this.scope.coords); } defaults = this.opts; } if (this.element) { this.html = _.isObject(this.element) ? this.element.html() : this.element; } _opts = this.scope.options ? this.scope.options : defaults; this.opts = this.createWindowOptions(maybeMarker, this.markerScope || this.scope, this.html, _opts); if (this.opts != null) { if (!this.gObject) { if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) { this.gObject = new window.InfoBox(this.opts); } else { this.gObject = new google.maps.InfoWindow(this.opts); } this.listeners.push(google.maps.event.addListener(this.gObject, 'domready', function() { return ChromeFixes.maybeRepaint(this.content); })); this.listeners.push(google.maps.event.addListener(this.gObject, 'closeclick', (function(_this) { return function() { if (maybeMarker) { maybeMarker.setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { maybeMarker.setVisible(false); return maybeMarker.setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _this.gObject.close(); _this.model.show = false; if (_this.scope.closeClick != null) { return _this.scope.$evalAsync(_this.scope.closeClick()); } else { return _this.scope.$evalAsync(); } }; })(this))); } this.gObject.setContent(this.opts.content); this.handleClick(((ref = this.scope) != null ? (ref1 = ref.options) != null ? ref1.forceClick : void 0 : void 0) || isOpen); return this.doShow(this.gObject.isOpen()); } }; WindowChildModel.prototype.watchCoords = function() { var scope; scope = this.markerScope != null ? this.markerScope : this.scope; return scope.$watch('coords', (function(_this) { return function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { _this.hideWindow(); } else if (!_this.validateCoords(newValue)) { $log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.doShow(); _this.gObject.setPosition(pos); if (_this.opts) { return _this.opts.position = pos; } } }; })(this), true); }; WindowChildModel.prototype.watchOptions = function() { return this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.opts = newValue; if (_this.gObject != null) { _this.gObject.setOptions(_this.opts); if ((_this.opts.visible != null) && _this.opts.visible) { return _this.showWindow(); } else if (_this.opts.visible != null) { return _this.hideWindow(); } } } }; })(this), true); }; WindowChildModel.prototype.handleClick = function(forceClick) { var click, maybeMarker; if (this.gObject == null) { return; } maybeMarker = this.getGmarker(); click = (function(_this) { return function() { if (_this.gObject == null) { _this.createGWin(); } _this.showWindow(); if (maybeMarker != null) { _this.initialMarkerVisibility = maybeMarker.getVisible(); _this.oldMarkerAnimation = maybeMarker.getAnimation(); return maybeMarker.setVisible(_this.isIconVisibleOnClick); } }; })(this); if (forceClick) { click(); } if (maybeMarker) { return this.listeners = this.listeners.concat(this.setEvents(maybeMarker, { events: { click: click } }, this.model)); } }; WindowChildModel.prototype.showWindow = function() { var compiled, show, templateScope; if (this.gObject != null) { show = (function(_this) { return function() { var isOpen, maybeMarker, pos; if (!_this.gObject.isOpen()) { maybeMarker = _this.getGmarker(); if ((_this.gObject != null) && (_this.gObject.getPosition != null)) { pos = _this.gObject.getPosition(); } if (maybeMarker) { pos = maybeMarker.getPosition(); } if (!pos) { return; } _this.gObject.open(_this.mapCtrl, maybeMarker); isOpen = _this.gObject.isOpen(); if (_this.model.show !== isOpen) { return _this.model.show = isOpen; } } }; })(this); if (this.scope.templateUrl) { return $http.get(this.scope.templateUrl, { cache: $templateCache }).then((function(_this) { return function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = $compile(content.data)(templateScope); _this.gObject.setContent(compiled[0]); return show(); }; })(this)); } else if (this.scope.template) { templateScope = this.scope.$new(); if (angular.isDefined(this.scope.templateParameter)) { templateScope.parameter = this.scope.templateParameter; } compiled = $compile(this.scope.template)(templateScope); this.gObject.setContent(compiled[0]); return show(); } else { return show(); } } }; WindowChildModel.prototype.hideWindow = function() { if ((this.gObject != null) && this.gObject.isOpen()) { return this.gObject.close(); } }; WindowChildModel.prototype.getLatestPosition = function(overridePos) { var maybeMarker; maybeMarker = this.getGmarker(); if ((this.gObject != null) && (maybeMarker != null) && !overridePos) { return this.gObject.setPosition(maybeMarker.getPosition()); } else { if (overridePos) { return this.gObject.setPosition(overridePos); } } }; WindowChildModel.prototype.remove = function() { this.hideWindow(); this.removeEvents(this.listeners); this.listeners.length = 0; delete this.gObject; return delete this.opts; }; WindowChildModel.prototype.destroy = function(manualOverride) { var ref; if (manualOverride == null) { manualOverride = false; } this.remove(); if ((this.scope != null) && !((ref = this.scope) != null ? ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { return this.scope.$destroy(); } }; WindowChildModel.prototype.updateModel = function(model) { this.clonedModel = _.extend({}, model); return _.extend(this.model, this.clonedModel); }; return WindowChildModel; })(BaseObject); return WindowChildModel; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapBasePolysParentModel', [ '$timeout', 'uiGmapLogger', 'uiGmapModelKey', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmap_async', 'uiGmapPromise', function($timeout, $log, ModelKey, ModelsWatcher, PropMap, _async, uiGmapPromise) { return function(IPoly, PolyChildModel, gObjectName) { var BasePolysParentModel; return BasePolysParentModel = (function(superClass) { extend(BasePolysParentModel, superClass); BasePolysParentModel.include(ModelsWatcher); function BasePolysParentModel(scope, element, attrs, gMap1, defaults) { this.element = element; this.attrs = attrs; this.gMap = gMap1; this.defaults = defaults; this.createChild = bind(this.createChild, this); this.pieceMeal = bind(this.pieceMeal, this); this.createAllNew = bind(this.createAllNew, this); this.watchIdKey = bind(this.watchIdKey, this); this.createChildScopes = bind(this.createChildScopes, this); this.watchDestroy = bind(this.watchDestroy, this); this.onDestroy = bind(this.onDestroy, this); this.rebuildAll = bind(this.rebuildAll, this); this.doINeedToWipe = bind(this.doINeedToWipe, this); this.watchModels = bind(this.watchModels, this); BasePolysParentModel.__super__.constructor.call(this, scope); this["interface"] = IPoly; this.$log = $log; this.plurals = new PropMap(); _.each(IPoly.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.createChildScopes(); } BasePolysParentModel.prototype.watchModels = function(scope) { return scope.$watchCollection('models', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { if (_this.doINeedToWipe(newValue) || scope.doRebuildAll) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }; })(this)); }; BasePolysParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; BasePolysParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; BasePolysParentModel.prototype.onDestroy = function(scope) { BasePolysParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(true); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var ref; return (ref = _this.plurals) != null ? ref.removeAll() : void 0; }); }; })(this)); }; BasePolysParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; BasePolysParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error("No models to create " + gObjectName + "s from! I Need direct models!"); return; } if ((this.gMap == null) || (this.scope.models == null)) { return; } this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; BasePolysParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; BasePolysParentModel.prototype.createAllNew = function(scope, isArray) { var maybeCanceled; if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { var child; child = _this.createChild(model, _this.gMap); if (maybeCanceled) { $log.debug('createNew should fall through safely'); child.isEnabled = false; } return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.firstTime = false; }); }; })(this)); }; BasePolysParentModel.prototype.pieceMeal = function(scope, isArray) { var maybeCanceled, payload; if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; this.models = scope.models; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise(function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); }).then(function(state) { payload = state; if (payload.updates.length) { $log.info("polygons updates: " + payload.updates.length + " will be missed"); } return _async.each(payload.removals, function(child) { if (child != null) { child.destroy(); _this.plurals.remove(child.model[_this.idKey]); return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { if (maybeCanceled) { $log.debug('pieceMeal should fall through safely'); } _this.createChild(modelToAdd, _this.gMap); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(this.scope, true, true); } }; BasePolysParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(IPoly.scopeKeys, childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); childScope["static"] = this.scope["static"]; child = new PolyChildModel(childScope, this.attrs, gMap, this.defaults, model); if (model[this.idKey] == null) { this.$log.error(gObjectName + " model has no id to assign a child to.\nThis is required for performance. Please assign id,\nor redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; return BasePolysParentModel; })(ModelKey); }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapCircleParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapCircleOptionsBuilder', function($log, $timeout, GmapUtil, EventsHelper, Builder) { var CircleParentModel; return CircleParentModel = (function(superClass) { extend(CircleParentModel, superClass); CircleParentModel.include(GmapUtil); CircleParentModel.include(EventsHelper); function CircleParentModel(scope, element, attrs, map, DEFAULTS) { var clean, gObject, lastRadius; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; this.scope = scope; lastRadius = null; clean = (function(_this) { return function() { lastRadius = null; if (_this.listeners != null) { _this.removeEvents(_this.listeners); return _this.listeners = void 0; } }; })(this); gObject = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { return gObject.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); } }; })(this); this.props = this.props.concat([ { prop: 'center', isColl: true }, { prop: 'fill', isColl: true }, 'radius', 'zIndex' ]); this.watchProps(); if (this.scope.control != null) { this.scope.control.getCircle = function() { return gObject; }; } clean(); this.listeners = this.setEvents(gObject, scope, scope, ['radius_changed']); if (this.listeners != null) { this.listeners.push(google.maps.event.addListener(gObject, 'radius_changed', function() { /* possible google bug, and or because a circle has two radii radius_changed appears to fire twice (original and new) which is not too helpful therefore we will check for radius changes manually and bail out if nothing has changed */ var newRadius, work; newRadius = gObject.getRadius(); if (newRadius === lastRadius) { return; } lastRadius = newRadius; work = function() { var ref, ref1; if (newRadius !== scope.radius) { scope.radius = newRadius; } if (((ref = scope.events) != null ? ref.radius_changed : void 0) && _.isFunction((ref1 = scope.events) != null ? ref1.radius_changed : void 0)) { return scope.events.radius_changed(gObject, 'radius_changed', scope, arguments); } }; if (!angular.mock) { return scope.$evalAsync(function() { return work(); }); } else { return work(); } })); } if (this.listeners != null) { this.listeners.push(google.maps.event.addListener(gObject, 'center_changed', function() { return scope.$evalAsync(function() { if (angular.isDefined(scope.center.type)) { scope.center.coordinates[1] = gObject.getCenter().lat(); return scope.center.coordinates[0] = gObject.getCenter().lng(); } else { scope.center.latitude = gObject.getCenter().lat(); return scope.center.longitude = gObject.getCenter().lng(); } }); })); } scope.$on('$destroy', (function(_this) { return function() { clean(); return gObject.setMap(null); }; })(this)); $log.info(this); } return CircleParentModel; })(Builder); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapDrawingManagerParentModel', [ 'uiGmapLogger', '$timeout', 'uiGmapBaseObject', 'uiGmapEventsHelper', function($log, $timeout, BaseObject, EventsHelper) { var DrawingManagerParentModel; return DrawingManagerParentModel = (function(superClass) { extend(DrawingManagerParentModel, superClass); DrawingManagerParentModel.include(EventsHelper); function DrawingManagerParentModel(scope1, element, attrs, map) { var gObject, listeners; this.scope = scope1; this.attrs = attrs; this.map = map; gObject = new google.maps.drawing.DrawingManager(this.scope.options); gObject.setMap(this.map); listeners = void 0; if (this.scope.control != null) { this.scope.control.getDrawingManager = function() { return gObject; }; } if (!this.scope["static"] && this.scope.options) { this.scope.$watch('options', function(newValue) { return gObject != null ? gObject.setOptions(newValue) : void 0; }, true); } if (this.scope.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } scope.$on('$destroy', (function(_this) { return function() { if (listeners != null) { _this.removeEvents(listeners); } gObject.setMap(null); return gObject = null; }; })(this)); } return DrawingManagerParentModel; })(BaseObject); } ]); }).call(this); ; /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [ "uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(superClass) { extend(IMarkerParentModel, superClass); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope1, element, attrs, map) { this.scope = scope1; this.element = element; this.attrs = attrs; this.map = map; this.onWatch = bind(this.onWatch, this); this.watch = bind(this.watch, this); this.validateScope = bind(this.validateScope, this); IMarkerParentModel.__super__.constructor.call(this, this.scope); this.$log = Logger; if (!this.validateScope(this.scope)) { throw new String("Unable to construct IMarkerParentModel due to invalid scope"); } this.doClick = angular.isDefined(this.attrs.click); if (this.scope.options != null) { this.DEFAULTS = this.scope.options; } this.watch('coords', this.scope); this.watch('icon', this.scope); this.watch('options', this.scope); this.scope.$on("$destroy", (function(_this) { return function() { return _this.onDestroy(_this.scope); }; })(this)); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) { if (equalityCheck == null) { equalityCheck = true; } return scope.$watch(propNameToWatch, (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }; })(this), equalityCheck); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {}; return IMarkerParentModel; })(ModelKey); return IMarkerParentModel; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIWindowParentModel", [ "uiGmapModelKey", "uiGmapGmapUtil", "uiGmapLogger", function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; return IWindowParentModel = (function(superClass) { extend(IWindowParentModel, superClass); IWindowParentModel.include(GmapUtil); function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { IWindowParentModel.__super__.constructor.call(this, scope); this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.DEFAULTS = {}; if (scope.options != null) { this.DEFAULTS = scope.options; } } IWindowParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return IWindowParentModel; })(ModelKey); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapLayerParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(superClass) { extend(LayerParentModel, superClass); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info('type attribute for the layer directive is mandatory. Layer creation aborted!!'); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.gObject.setMap(this.gMap); } this.scope.$watch('show', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.gObject.setMap(_this.gMap); } else { return _this.gObject.setMap(null); } } }; })(this), true); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.gObject.setMap(null); _this.gObject = null; return _this.createGoogleLayer(); } }; })(this), true); this.scope.$on('$destroy', (function(_this) { return function() { return _this.gObject.setMap(null); }; })(this)); } LayerParentModel.prototype.createGoogleLayer = function() { var base; if (this.attrs.options == null) { this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.gObject = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options); } if ((this.gObject != null) && (this.onLayerCreated != null)) { return typeof (base = this.onLayerCreated(this.scope, this.gObject)) === "function" ? base(this.gObject) : void 0; } }; return LayerParentModel; })(BaseObject); return LayerParentModel; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapMapTypeParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', function(BaseObject, Logger) { var MapTypeParentModel; MapTypeParentModel = (function(superClass) { extend(MapTypeParentModel, superClass); function MapTypeParentModel(scope, element, attrs, gMap, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.$log = $log != null ? $log : Logger; this.hideOverlay = bind(this.hideOverlay, this); this.showOverlay = bind(this.showOverlay, this); this.refreshMapType = bind(this.refreshMapType, this); this.createMapType = bind(this.createMapType, this); if (this.attrs.options == null) { this.$log.info('options attribute for the map-type directive is mandatory. Map type creation aborted!!'); return; } this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0; this.doShow = true; this.createMapType(); if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.showOverlay(); } this.scope.$watch('show', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.showOverlay(); } else { return _this.hideOverlay(); } } }; })(this), true); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); if (angular.isDefined(this.attrs.refresh)) { this.scope.$watch('refresh', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); } this.scope.$on('$destroy', (function(_this) { return function() { _this.hideOverlay(); return _this.mapType = null; }; })(this)); } MapTypeParentModel.prototype.createMapType = function() { if (this.scope.options.getTile != null) { this.mapType = this.scope.options; } else if (this.scope.options.getTileUrl != null) { this.mapType = new google.maps.ImageMapType(this.scope.options); } else { this.$log.info('options should provide either getTile or getTileUrl methods. Map type creation aborted!!'); return; } if (this.attrs.id && this.scope.id) { this.gMap.mapTypes.set(this.scope.id, this.mapType); if (!angular.isDefined(this.attrs.show)) { this.doShow = false; } } return this.mapType.layerId = this.id; }; MapTypeParentModel.prototype.refreshMapType = function() { this.hideOverlay(); this.mapType = null; this.createMapType(); if (this.doShow && (this.gMap != null)) { return this.showOverlay(); } }; MapTypeParentModel.prototype.showOverlay = function() { return this.gMap.overlayMapTypes.push(this.mapType); }; MapTypeParentModel.prototype.hideOverlay = function() { var found; found = false; return this.gMap.overlayMapTypes.forEach((function(_this) { return function(mapType, index) { if (!found && mapType.layerId === _this.id) { found = true; _this.gMap.overlayMapTypes.removeAt(index); } }; })(this)); }; return MapTypeParentModel; })(BaseObject); return MapTypeParentModel; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [ "uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", "uiGmapLogger", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil, $log) { var MarkersParentModel, _setPlurals; _setPlurals = function(val, objToSet) { objToSet.plurals = new PropMap(); objToSet.scope.plurals = objToSet.plurals; return objToSet; }; MarkersParentModel = (function(superClass) { extend(MarkersParentModel, superClass); MarkersParentModel.include(GmapUtil); MarkersParentModel.include(ModelsWatcher); function MarkersParentModel(scope, element, attrs, map) { this.onDestroy = bind(this.onDestroy, this); this.newChildMarker = bind(this.newChildMarker, this); this.pieceMeal = bind(this.pieceMeal, this); this.rebuildAll = bind(this.rebuildAll, this); this.createAllNew = bind(this.createAllNew, this); this.createChildScopes = bind(this.createChildScopes, this); this.validateScope = bind(this.validateScope, this); this.onWatch = bind(this.onWatch, this); var self; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map); this["interface"] = IMarker; self = this; _setPlurals(new PropMap(), this); this.scope.pluralsUpdate = { updateCtr: 0 }; this.$log.info(this); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; this.setIdKey(scope); this.scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); if (!this.modelsLength()) { this.modelsRendered = false; } this.scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.modelsRendered) { if (newValue.length === 0 && oldValue.length === 0) { return; } _this.modelsRendered = true; return _this.onWatch('models', scope, newValue, oldValue); } }; })(this), !this.isTrue(attrs.modelsbyref)); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('clusterEvents', scope); this.watch('fit', scope); this.watch('idKey', scope); this.gManager = void 0; this.createAllNew(scope); } MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === "idKey" && newValue !== oldValue) { this.idKey = newValue; } if (this.doRebuildAll || propNameToWatch === 'doCluster') { return this.rebuildAll(scope); } else { return this.pieceMeal(scope); } }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; /* Not used internally by this parent created for consistency for external control in the API */ MarkersParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if ((this.gMap == null) || (this.scope.models == null)) { return; } if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } }; MarkersParentModel.prototype.createAllNew = function(scope) { var maybeCanceled, ref, ref1, ref2, self; if (this.gManager != null) { this.gManager.clear(); delete this.gManager; } if (scope.doCluster) { if (scope.clusterEvents) { self = this; if (!this.origClusterEvents) { this.origClusterEvents = { click: (ref = scope.clusterEvents) != null ? ref.click : void 0, mouseout: (ref1 = scope.clusterEvents) != null ? ref1.mouseout : void 0, mouseover: (ref2 = scope.clusterEvents) != null ? ref2.mouseover : void 0 }; } else { angular.extend(scope.clusterEvents, this.origClusterEvents); } angular.extend(scope.clusterEvents, { click: function(cluster) { return self.maybeExecMappedEvent(cluster, 'click'); }, mouseout: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseout'); }, mouseover: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseover'); } }); } this.gManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, scope.clusterEvents); } else { this.gManager = new MarkerManager(this.map); } if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { _this.newChildMarker(model, scope); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { _this.modelsRendered = true; if (scope.fit) { _this.gManager.fit(); } _this.gManager.draw(); return _this.scope.pluralsUpdate.updateCtr += 1; }, _async.chunkSizeFrom(scope.chunk)); }; })(this)); }; MarkersParentModel.prototype.rebuildAll = function(scope) { var ref; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } if ((ref = this.scope.plurals) != null ? ref.length : void 0) { return this.onDestroy(scope).then((function(_this) { return function() { return _this.createAllNew(scope); }; })(this)); } else { return this.createAllNew(scope); } }; MarkersParentModel.prototype.pieceMeal = function(scope) { var maybeCanceled, payload; if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; if (this.modelsLength() && this.scope.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.scope.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } _this.scope.plurals.remove(child.id); return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { _this.newChildMarker(modelToAdd, scope); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) { scope.plurals = _this.scope.plurals; if (scope.fit) { _this.gManager.fit(); } _this.gManager.draw(); } return _this.scope.pluralsUpdate.updateCtr += 1; }); }; })(this)); } else { this.inProgress = false; return this.rebuildAll(scope); } }; MarkersParentModel.prototype.newChildMarker = function(model, scope) { var child, childScope, doDrawSelf, keys; if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.$log.info('child', child, 'markers', this.scope.markerModels); childScope = scope.$new(false); childScope.events = scope.events; keys = {}; IMarker.scopeKeys.forEach(function(k) { return keys[k] = scope[k]; }); child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gManager, doDrawSelf = false); this.scope.plurals.put(model[this.idKey], child); return child; }; MarkersParentModel.prototype.onDestroy = function(scope) { MarkersParentModel.__super__.onDestroy.call(this, scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.scope.plurals.values(), function(model) { if (model != null) { return model.destroy(false); } }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { if (_this.gManager != null) { _this.gManager.clear(); } _this.plurals.removeAll(); if (_this.plurals !== _this.scope.plurals) { console.error('plurals out of sync for MarkersParentModel'); } return _this.scope.pluralsUpdate.updateCtr += 1; }); }; })(this)); }; MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) { var pair, ref; if (_.isFunction((ref = this.scope.clusterEvents) != null ? ref[fnName] : void 0)) { pair = this.mapClusterToPlurals(cluster); if (this.origClusterEvents[fnName]) { return this.origClusterEvents[fnName](pair.cluster, pair.mapped); } } }; MarkersParentModel.prototype.mapClusterToPlurals = function(cluster) { var mapped; mapped = cluster.getMarkers().map((function(_this) { return function(g) { return _this.scope.plurals.get(g.key).model; }; })(this)); return { cluster: cluster, mapped: mapped }; }; MarkersParentModel.prototype.getItem = function(scope, modelsPropToIterate, index) { if (modelsPropToIterate === 'models') { return scope[modelsPropToIterate][index]; } return scope[modelsPropToIterate].get(index); }; return MarkersParentModel; })(IMarkerParentModel); return MarkersParentModel; } ]); }).call(this); ;(function() { ['Polygon', 'Polyline'].forEach(function(name) { return angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory("uiGmap" + name + "sParentModel", [ 'uiGmapBasePolysParentModel', "uiGmap" + name + "ChildModel", "uiGmapI" + name, function(BasePolysParentModel, ChildModel, IPoly) { return BasePolysParentModel(IPoly, ChildModel, name); } ]); }); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapRectangleParentModel', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', 'uiGmapRectangleOptionsBuilder', function($log, GmapUtil, EventsHelper, Builder) { var RectangleParentModel; return RectangleParentModel = (function(superClass) { extend(RectangleParentModel, superClass); RectangleParentModel.include(GmapUtil); RectangleParentModel.include(EventsHelper); function RectangleParentModel(scope, element, attrs, map, DEFAULTS) { var bounds, clear, createBounds, dragging, fit, gObject, init, listeners, myListeners, settingBoundsFromScope, updateBounds; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; bounds = void 0; dragging = false; myListeners = []; listeners = void 0; fit = (function(_this) { return function() { if (_this.isTrue(_this.attrs.fit)) { return _this.fitMapBounds(_this.map, bounds); } }; })(this); createBounds = (function(_this) { return function() { var ref, ref1, ref2; if ((_this.scope.bounds != null) && (((ref = _this.scope.bounds) != null ? ref.sw : void 0) != null) && (((ref1 = _this.scope.bounds) != null ? ref1.ne : void 0) != null) && _this.validateBoundPoints(_this.scope.bounds)) { bounds = _this.convertBoundPoints(_this.scope.bounds); return $log.info("new new bounds created: " + (JSON.stringify(bounds))); } else if ((_this.scope.bounds.getNorthEast != null) && (_this.scope.bounds.getSouthWest != null)) { return bounds = _this.scope.bounds; } else { if (_this.scope.bounds != null) { return $log.error("Invalid bounds for newValue: " + (JSON.stringify((ref2 = _this.scope) != null ? ref2.bounds : void 0))); } } }; })(this); createBounds(); gObject = new google.maps.Rectangle(this.buildOpts(bounds)); $log.info("gObject (rectangle) created: " + gObject); settingBoundsFromScope = false; updateBounds = (function(_this) { return function() { var b, ne, sw; b = gObject.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return _this.scope.$evalAsync(function(s) { if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) { return s.bounds = b; } }); }; })(this); init = (function(_this) { return function() { fit(); _this.removeEvents(myListeners); myListeners.push(google.maps.event.addListener(gObject, 'dragstart', function() { return dragging = true; })); myListeners.push(google.maps.event.addListener(gObject, 'dragend', function() { dragging = false; return updateBounds(); })); return myListeners.push(google.maps.event.addListener(gObject, 'bounds_changed', function() { if (dragging) { return; } return updateBounds(); })); }; })(this); clear = (function(_this) { return function() { _this.removeEvents(myListeners); if (listeners != null) { _this.removeEvents(listeners); } return gObject.setMap(null); }; })(this); if (bounds != null) { init(); } this.scope.$watch('bounds', (function(newValue, oldValue) { var isNew; if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) { return; } settingBoundsFromScope = true; if (newValue == null) { clear(); return; } if (bounds == null) { isNew = true; } else { fit(); } createBounds(); gObject.setBounds(bounds); settingBoundsFromScope = false; if (isNew && (bounds != null)) { return init(); } }), true); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { if ((bounds != null) && (newVals != null)) { return gObject.setOptions(_this.buildOpts(bounds)); } } }; })(this); this.props.push('bounds'); this.watchProps(this.props); if (this.attrs.events != null) { listeners = this.setEvents(gObject, this.scope, this.scope); this.scope.$watch('events', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(gObject, _this.scope, _this.scope); } }; })(this)); } this.scope.$on('$destroy', (function(_this) { return function() { return clear(); }; })(this)); $log.info(this); } return RectangleParentModel; })(Builder); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapSearchBoxParentModel', [ 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapEventsHelper', '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) { var SearchBoxParentModel; SearchBoxParentModel = (function(superClass) { extend(SearchBoxParentModel, superClass); SearchBoxParentModel.include(EventsHelper); function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) { var controlDiv; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.ctrlPosition = ctrlPosition; this.template = template; this.$log = $log != null ? $log : Logger; this.setVisibility = bind(this.setVisibility, this); this.getBounds = bind(this.getBounds, this); this.setBounds = bind(this.setBounds, this); this.createSearchBox = bind(this.createSearchBox, this); this.addToParentDiv = bind(this.addToParentDiv, this); this.addAsMapControl = bind(this.addAsMapControl, this); this.init = bind(this.init, this); if (this.attrs.template == null) { this.$log.error('template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!'); return; } if (angular.isUndefined(this.scope.options)) { this.scope.options = {}; this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.visible)) { this.scope.options.visible = true; } if (angular.isUndefined(this.scope.options.autocomplete)) { this.scope.options.autocomplete = false; } this.visible = this.scope.options.visible; this.autocomplete = this.scope.options.autocomplete; controlDiv = angular.element('<div></div>'); controlDiv.append(this.template); this.input = controlDiv.find('input')[0]; this.init(); } SearchBoxParentModel.prototype.init = function() { this.createSearchBox(); this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (angular.isObject(newValue)) { if (newValue.bounds != null) { _this.setBounds(newValue.bounds); } if (newValue.visible != null) { if (_this.visible !== newValue.visible) { return _this.setVisibility(newValue.visible); } } } }; })(this), true); if (this.attrs.parentdiv != null) { this.addToParentDiv(); } else { this.addAsMapControl(); } if (this.autocomplete) { this.listener = google.maps.event.addListener(this.gObject, 'place_changed', (function(_this) { return function() { return _this.places = _this.gObject.getPlace(); }; })(this)); } else { this.listener = google.maps.event.addListener(this.gObject, 'places_changed', (function(_this) { return function() { return _this.places = _this.gObject.getPlaces(); }; })(this)); } this.listeners = this.setEvents(this.gObject, this.scope, this.scope); this.$log.info(this); return this.scope.$on('$destroy', (function(_this) { return function() { return _this.gObject = null; }; })(this)); }; SearchBoxParentModel.prototype.addAsMapControl = function() { return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); }; SearchBoxParentModel.prototype.addToParentDiv = function() { this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv)); return this.parentDiv.append(this.input); }; SearchBoxParentModel.prototype.createSearchBox = function() { if (this.autocomplete) { return this.gObject = new google.maps.places.Autocomplete(this.input, this.scope.options); } else { return this.gObject = new google.maps.places.SearchBox(this.input, this.scope.options); } }; SearchBoxParentModel.prototype.setBounds = function(bounds) { if (angular.isUndefined(bounds.isEmpty)) { this.$log.error('Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds.'); } else { if (bounds.isEmpty() === false) { if (this.gObject != null) { return this.gObject.setBounds(bounds); } } } }; SearchBoxParentModel.prototype.getBounds = function() { return this.gObject.getBounds(); }; SearchBoxParentModel.prototype.setVisibility = function(val) { if (this.attrs.parentdiv != null) { if (val === false) { this.parentDiv.addClass("ng-hide"); } else { this.parentDiv.removeClass("ng-hide"); } } else { if (val === false) { this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].clear(); } else { this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); } } return this.visible = val; }; return SearchBoxParentModel; })(BaseObject); return SearchBoxParentModel; } ]); }).call(this); ; /* WindowsChildModel generator where there are many ChildModels to a parent. */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api.models.parent').factory('uiGmapWindowsParentModel', [ 'uiGmapIWindowParentModel', 'uiGmapModelsWatcher', 'uiGmapPropMap', 'uiGmapWindowChildModel', 'uiGmapLinked', 'uiGmap_async', 'uiGmapLogger', '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', 'uiGmapIWindow', 'uiGmapGmapUtil', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise, IWindow, GmapUtil) { var WindowsParentModel; WindowsParentModel = (function(superClass) { extend(WindowsParentModel, superClass); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, gMap1, markersScope) { this.gMap = gMap1; this.markersScope = markersScope; this.modelKeyComparison = bind(this.modelKeyComparison, this); this.interpolateContent = bind(this.interpolateContent, this); this.setChildScope = bind(this.setChildScope, this); this.createWindow = bind(this.createWindow, this); this.setContentKeys = bind(this.setContentKeys, this); this.pieceMeal = bind(this.pieceMeal, this); this.createAllNew = bind(this.createAllNew, this); this.watchIdKey = bind(this.watchIdKey, this); this.createChildScopes = bind(this.createChildScopes, this); this.watchOurScope = bind(this.watchOurScope, this); this.watchDestroy = bind(this.watchDestroy, this); this.onDestroy = bind(this.onDestroy, this); this.rebuildAll = bind(this.rebuildAll, this); this.doINeedToWipe = bind(this.doINeedToWipe, this); this.watchModels = bind(this.watchModels, this); this.go = bind(this.go, this); WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache); this["interface"] = IWindow; this.plurals = new PropMap(); _.each(IWindow.scopeKeys, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.linked = new Linked(scope, element, attrs, ctrls); this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.firstWatchModels = true; this.$log.info(self); this.parentScope = void 0; this.go(scope); } WindowsParentModel.prototype.go = function(scope) { this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); return this.createChildScopes(); }; WindowsParentModel.prototype.watchModels = function(scope) { var itemToWatch; itemToWatch = this.markersScope != null ? 'pluralsUpdate' : 'models'; return scope.$watch(itemToWatch, (function(_this) { return function(newValue, oldValue) { var doScratch; if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) { _this.firstWatchModels = false; if (_this.doRebuildAll || _this.doINeedToWipe(scope.models)) { return _this.rebuildAll(scope, true, true); } else { doScratch = _this.plurals.length === 0; if (_this.existingPieces != null) { return _.last(_this.existingPieces._content).then(function() { return _this.createChildScopes(doScratch); }); } else { return _this.createChildScopes(doScratch); } } } }; })(this), true); }; WindowsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return this.onDestroy(doDelete).then((function(_this) { return function() { if (doCreate) { return _this.createChildScopes(); } }; })(this)); }; WindowsParentModel.prototype.onDestroy = function(scope) { WindowsParentModel.__super__.onDestroy.call(this, this.scope); return _async.promiseLock(this, uiGmapPromise.promiseTypes["delete"], void 0, void 0, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(child) { return child.destroy(); }, _async.chunkSizeFrom(_this.scope.cleanchunk, false)).then(function() { var ref; return (ref = _this.plurals) != null ? ref.removeAll() : void 0; }); }; })(this)); }; WindowsParentModel.prototype.watchDestroy = function(scope) { return scope.$on('$destroy', (function(_this) { return function() { _this.firstWatchModels = true; _this.firstTime = true; return _this.rebuildAll(scope, false, true); }; })(this)); }; WindowsParentModel.prototype.watchOurScope = function(scope) { return _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; }; })(this)); }; WindowsParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { var modelsNotDefined, ref, ref1; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (this.markersScope === void 0 || (((ref = this.markersScope) != null ? ref.plurals : void 0) === void 0 || ((ref1 = this.markersScope) != null ? ref1.models : void 0) === void 0))) { this.$log.error('No models to create windows from! Need direct models or models derived from markers!'); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.watchIdKey(this.linked.scope); if (isCreatingFromScratch) { return this.createAllNew(this.linked.scope, false); } else { return this.pieceMeal(this.linked.scope, false); } } else { this.parentScope = this.markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNew(this.markersScope, true, 'plurals', false); } else { return this.pieceMeal(this.markersScope, true, 'plurals', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; WindowsParentModel.prototype.createAllNew = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = false; } if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } this.setContentKeys(scope.models); if (this.didQueueInitPromise(this, scope)) { return; } maybeCanceled = null; return _async.promiseLock(this, uiGmapPromise.promiseTypes.create, 'createAllNew', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return _async.each(scope.models, function(model) { var gMarker, ref; gMarker = hasGMarker ? (ref = _this.getItem(scope, modelsPropToIterate, model[_this.idKey])) != null ? ref.gObject : void 0 : void 0; if (!maybeCanceled) { if (!gMarker && _this.markersScope) { $log.error('Unable to get gMarker from markersScope!'); } _this.createWindow(model, gMarker, _this.gMap); } return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)).then(function() { return _this.firstTime = false; }); }; })(this)); }; WindowsParentModel.prototype.pieceMeal = function(scope, hasGMarker, modelsPropToIterate, isArray) { var maybeCanceled, payload; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } if (scope.$$destroyed) { return; } maybeCanceled = null; payload = null; if ((scope != null) && this.modelsLength() && this.plurals.length) { return _async.promiseLock(this, uiGmapPromise.promiseTypes.update, 'pieceMeal', (function(canceledMsg) { return maybeCanceled = canceledMsg; }), (function(_this) { return function() { return uiGmapPromise.promise((function() { return _this.figureOutState(_this.idKey, scope, _this.plurals, _this.modelKeyComparison); })).then(function(state) { payload = state; return _async.each(payload.removals, function(child) { if (child != null) { _this.plurals.remove(child.id); if (child.destroy != null) { child.destroy(true); } return maybeCanceled; } }, _async.chunkSizeFrom(scope.chunk)); }).then(function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker, ref; gMarker = (ref = _this.getItem(scope, modelsPropToIterate, modelToAdd[_this.idKey])) != null ? ref.gObject : void 0; if (!gMarker) { throw 'Gmarker undefined'; } _this.createWindow(modelToAdd, gMarker, _this.gMap); return maybeCanceled; }); }).then(function() { return _async.each(payload.updates, function(update) { _this.updateChild(update.child, update.model); return maybeCanceled; }, _async.chunkSizeFrom(scope.chunk)); }); }; })(this)); } else { $log.debug('pieceMeal: rebuildAll'); return this.rebuildAll(this.scope, true, true); } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (this.modelsLength(models)) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { var child, childScope, fakeElement, opts, ref, ref1; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); fakeElement = { html: (function(_this) { return function() { return _this.interpolateContent(_this.linked.element.html(), model); }; })(this) }; this.DEFAULTS = this.scopeOrModelVal(this.optionsKey, this.scope, model) || {}; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (ref = this.markersScope) != null ? (ref1 = ref.plurals.get(model[this.idKey])) != null ? ref1.scope : void 0 : void 0, fakeElement, false, true); if (model[this.idKey] == null) { this.$log.error('Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key.'); return; } this.plurals.put(model[this.idKey], child); return child; }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { _.each(IWindow.scopeKeys, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, i, interpModel, key, len, ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = $interpolate(content); interpModel = {}; ref = this.contentKeys; for (i = 0, len = ref.length; i < len; i++) { key = ref[i]; interpModel[key] = model[key]; } return exp(interpModel); }; WindowsParentModel.prototype.modelKeyComparison = function(model1, model2) { var isEqual, scope; scope = this.scope.coords != null ? this.scope : this.parentScope; if (scope == null) { throw 'No scope or parentScope set!'; } isEqual = GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords)); if (!isEqual) { return isEqual; } isEqual = _.every(_.without(this["interface"].scopeKeys, 'coords'), (function(_this) { return function(k) { return _this.evalModelHandle(model1, scope[k]) === _this.evalModelHandle(model2, scope[k]); }; })(this)); return isEqual; }; return WindowsParentModel; })(IWindowParentModel); return WindowsParentModel; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [ "uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) { return _.extend(ICircle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new CircleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [ "uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) { var Control; return Control = (function(superClass) { extend(Control, superClass); function Control() { this.link = bind(this.link, this); Control.__super__.constructor.call(this); } Control.prototype.link = function(scope, element, attrs, ctrl) { return GoogleMapApi.then((function(_this) { return function(maps) { var index, position; if (angular.isUndefined(scope.template)) { _this.$log.error('mapControl: could not find a valid template property'); return; } index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0; position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER'; if (!maps.ControlPosition[position]) { _this.$log.error('mapControl: invalid position property'); return; } return IControl.mapPromise(scope, ctrl).then(function(map) { var control, controlDiv; control = void 0; controlDiv = angular.element('<div></div>'); return $http.get(scope.template, { cache: $templateCache }).success(function(template) { var templateCtrl, templateScope; templateScope = scope.$new(); controlDiv.append(template); if (angular.isDefined(scope.controller)) { templateCtrl = $controller(scope.controller, { $scope: templateScope }); controlDiv.children().data('$ngControllerController', templateCtrl); } control = $compile(controlDiv.children())(templateScope); if (index) { return control[0].index = index; } }).error(function(error) { return _this.$log.error('mapControl: template could not be found'); }).then(function() { return map.controls[google.maps.ControlPosition[position]].push(control[0]); }); }); }; })(this)); }; return Control; })(IControl); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapDragZoom', [ 'uiGmapCtrlHandle', 'uiGmapPropertyAction', function(CtrlHandle, PropertyAction) { return { restrict: 'EMA', transclude: true, template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>', require: '^' + 'uiGmapGoogleMap', scope: { keyboardkey: '=', options: '=', spec: '=' }, controller: [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'uiGmapDragZoom'; return _.extend(this, CtrlHandle.handle($scope, $element)); } ], link: function(scope, element, attrs, ctrl) { return CtrlHandle.mapPromise(scope, ctrl).then(function(map) { var enableKeyDragZoom, setKeyAction, setOptionsAction; enableKeyDragZoom = function(opts) { map.enableKeyDragZoom(opts); if (scope.spec) { return scope.spec.enableKeyDragZoom(opts); } }; setKeyAction = new PropertyAction(function(key, newVal) { if (newVal) { return enableKeyDragZoom({ key: newVal }); } else { return enableKeyDragZoom(); } }); setOptionsAction = new PropertyAction(function(key, newVal) { if (newVal) { return enableKeyDragZoom(newVal); } }); scope.$watch('keyboardkey', setKeyAction.sic); setKeyAction.sic(scope.keyboardkey); scope.$watch('options', setOptionsAction.sic); return setOptionsAction.sic(scope.options); }); } }; } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapDrawingManager", [ "uiGmapIDrawingManager", "uiGmapDrawingManagerParentModel", function(IDrawingManager, DrawingManagerParentModel) { return _.extend(IDrawingManager, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then(function(map) { return new DrawingManagerParentModel(scope, element, attrs, map); }); } }); } ]); }).call(this); ; /* - Link up Polygons to be sent back to a controller - inject the draw function into a controllers scope so that controller can call the directive to draw on demand - draw function creates the DrawFreeHandChildModel which manages itself */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapApiFreeDrawPolygons', [ 'uiGmapLogger', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapDrawFreeHandChildModel', 'uiGmapLodash', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel, uiGmapLodash) { var FreeDrawPolygons; return FreeDrawPolygons = (function(superClass) { extend(FreeDrawPolygons, superClass); function FreeDrawPolygons() { this.link = bind(this.link, this); return FreeDrawPolygons.__super__.constructor.apply(this, arguments); } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EMA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^' + 'uiGmapGoogleMap'; FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=' }; FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) { return this.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var freeHand, listener; if (!scope.polygons) { return $log.error('No polygons to bind to!'); } if (!_.isArray(scope.polygons)) { return $log.error('Free Draw Polygons must be of type Array!'); } freeHand = new DrawFreeHandChildModel(map, ctrl.getScope()); listener = void 0; return scope.draw = function() { if (typeof listener === "function") { listener(); } return freeHand.engage(scope.polygons).then(function() { var firstTime; firstTime = true; return listener = scope.$watchCollection('polygons', function(newValue, oldValue) { var removals; if (firstTime || newValue === oldValue) { firstTime = false; return; } removals = uiGmapLodash.differenceObjects(oldValue, newValue); return removals.forEach(function(p) { return p.setMap(null); }); }); }); }; }; })(this)); }; return FreeDrawPolygons; })(BaseObject); } ]); }).call(this); ;(function() { angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [ function() { var DEFAULTS; DEFAULTS = {}; return { restrict: "EA", replace: true, require: '^' + 'uiGmapGoogleMap', scope: { center: "=center", radius: "=radius", stroke: "=stroke", fill: "=fill", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=", events: "=", control: "=", zIndex: "=zindex" } }; } ]); }).call(this); ; /* - interface for all controls to derive from - to enforce a minimum set of requirements - attributes - template - position - controller - index */ (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIControl", [ "uiGmapBaseObject", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, Logger, CtrlHandle) { var IControl; return IControl = (function(superClass) { extend(IControl, superClass); IControl.extend(CtrlHandle); function IControl() { this.restrict = 'EA'; this.replace = true; this.require = '^' + 'uiGmapGoogleMap'; this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IControl; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIDrawingManager', [ function() { return { restrict: 'EA', replace: true, require: '^' + 'uiGmapGoogleMap', scope: { "static": '@', control: '=', options: '=', events: '=' } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIMarker', [ 'uiGmapBaseObject', 'uiGmapCtrlHandle', function(BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(superClass) { extend(IMarker, superClass); IMarker.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; IMarker.scopeKeys = _.keys(IMarker.scope); IMarker.keys = IMarker.scopeKeys; IMarker.extend(CtrlHandle); function IMarker() { this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = _.extend(this.scope || {}, IMarker.scope); } return IMarker; })(BaseObject); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolygon', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolygon; return IPolygon = (function(superClass) { extend(IPolygon, superClass); IPolygon.scope = { path: '=path', stroke: '=stroke', clickable: '=', draggable: '=', editable: '=', geodesic: '=', fill: '=', icons: '=icons', visible: '=', "static": '=', events: '=', zIndex: '=zindex', fit: '=', control: '=control' }; IPolygon.scopeKeys = _.keys(IPolygon.scope); IPolygon.include(GmapUtil); IPolygon.extend(CtrlHandle); function IPolygon() {} IPolygon.prototype.restrict = 'EMA'; IPolygon.prototype.replace = true; IPolygon.prototype.require = '^' + 'uiGmapGoogleMap'; IPolygon.prototype.scope = IPolygon.scope; IPolygon.prototype.DEFAULTS = {}; IPolygon.prototype.$log = Logger; return IPolygon; })(BaseObject); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIPolyline', [ 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapLogger', 'uiGmapCtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolyline; return IPolyline = (function(superClass) { extend(IPolyline, superClass); IPolyline.scope = { path: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', geodesic: '=', icons: '=', visible: '=', "static": '=', fit: '=', events: '=', zIndex: '=zindex' }; IPolyline.scopeKeys = _.keys(IPolyline.scope); IPolyline.include(GmapUtil); IPolyline.extend(CtrlHandle); function IPolyline() {} IPolyline.prototype.restrict = 'EMA'; IPolyline.prototype.replace = true; IPolyline.prototype.require = '^' + 'uiGmapGoogleMap'; IPolyline.prototype.scope = IPolyline.scope; IPolyline.prototype.DEFAULTS = {}; IPolyline.prototype.$log = Logger; return IPolyline; })(BaseObject); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapIRectangle', [ function() { 'use strict'; var DEFAULTS; DEFAULTS = {}; return { restrict: 'EMA', require: '^' + 'uiGmapGoogleMap', replace: true, scope: { bounds: '=', stroke: '=', clickable: '=', draggable: '=', editable: '=', fill: '=', visible: '=', events: '=' } }; } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapIWindow', [ 'uiGmapBaseObject', 'uiGmapChildEvents', 'uiGmapCtrlHandle', function(BaseObject, ChildEvents, CtrlHandle) { var IWindow; return IWindow = (function(superClass) { extend(IWindow, superClass); IWindow.scope = { coords: '=coords', template: '=template', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options', control: '=control', show: '=show' }; IWindow.scopeKeys = _.keys(IWindow.scope); IWindow.include(ChildEvents); IWindow.extend(CtrlHandle); function IWindow() { this.restrict = 'EMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = '^' + 'uiGmapGoogleMap'; this.replace = true; this.scope = _.extend(this.scope || {}, IWindow.scope); } return IWindow; })(BaseObject); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapMap', [ '$timeout', '$q', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapBaseObject', 'uiGmapCtrlHandle', 'uiGmapIsReady', 'uiGmapuuid', 'uiGmapExtendGWin', 'uiGmapExtendMarkerClusterer', 'uiGmapGoogleMapsUtilV3', 'uiGmapGoogleMapApi', 'uiGmapEventsHelper', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi, EventsHelper) { 'use strict'; var DEFAULTS, Map, initializeItems; DEFAULTS = void 0; initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer]; return Map = (function(superClass) { extend(Map, superClass); Map.include(GmapUtil); function Map() { this.link = bind(this.link, this); var ctrlFn, self; ctrlFn = function($scope) { var ctrlObj, retCtrl; retCtrl = void 0; $scope.$on('$destroy', function() { return IsReady.reset(); }); ctrlObj = CtrlHandle.handle($scope); $scope.ctrlType = 'Map'; $scope.deferred.promise.then(function() { return initializeItems.forEach(function(i) { return i.init(); }); }); ctrlObj.getMap = function() { return $scope.map; }; retCtrl = _.extend(this, ctrlObj); return retCtrl; }; this.controller = ['$scope', ctrlFn]; self = this; } Map.prototype.restrict = 'EMA'; Map.prototype.transclude = true; Map.prototype.replace = false; Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>'; Map.prototype.scope = { center: '=', zoom: '=', dragging: '=', control: '=', options: '=', events: '=', eventOpts: '=', styles: '=', bounds: '=', update: '=' }; Map.prototype.link = function(scope, element, attrs) { var listeners, unbindCenterWatch; listeners = []; scope.$on('$destroy', function() { return EventsHelper.removeEvents(listeners); }); scope.idleAndZoomChanged = false; if (scope.center == null) { unbindCenterWatch = scope.$watch('center', (function(_this) { return function() { if (!scope.center) { return; } unbindCenterWatch(); return _this.link(scope, element, attrs); }; })(this)); return; } return GoogleMapApi.then((function(_this) { return function(maps) { var _gMap, customListeners, disabledEvents, dragging, el, eventName, getEventHandler, mapOptions, maybeHookToEvent, opts, ref, resolveSpawned, settingFromDirective, spawned, type, updateCenter, zoomPromise; DEFAULTS = { mapTypeId: maps.MapTypeId.ROADMAP }; spawned = IsReady.spawn(); resolveSpawned = function() { return spawned.deferred.resolve({ instance: spawned.instance, map: _gMap }); }; if (!_this.validateCoords(scope.center)) { $log.error('angular-google-maps: could not find a valid center property'); return; } if (!angular.isDefined(scope.zoom)) { $log.error('angular-google-maps: map zoom property not set'); return; } el = angular.element(element); el.addClass('angular-google-map'); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type '" + attrs.type + "'"); } } mapOptions = angular.extend({}, DEFAULTS, opts, { center: _this.getCoords(scope.center), zoom: scope.zoom, bounds: scope.bounds }); _gMap = new google.maps.Map(el.find('div')[1], mapOptions); _gMap['uiGmap_id'] = uuid.generate(); dragging = false; listeners.push(google.maps.event.addListenerOnce(_gMap, 'idle', function() { scope.deferred.resolve(_gMap); return resolveSpawned(); })); disabledEvents = attrs.events && (((ref = scope.events) != null ? ref.blacklist : void 0) != null) ? scope.events.blacklist : []; if (_.isString(disabledEvents)) { disabledEvents = [disabledEvents]; } maybeHookToEvent = function(eventName, fn, prefn) { if (!_.contains(disabledEvents, eventName)) { if (prefn) { prefn(); } return listeners.push(google.maps.event.addListener(_gMap, eventName, function() { var ref1; if (!((ref1 = scope.update) != null ? ref1.lazy : void 0)) { return fn(); } })); } }; if (!_.contains(disabledEvents, 'all')) { maybeHookToEvent('dragstart', function() { dragging = true; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); maybeHookToEvent('dragend', function() { dragging = false; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); updateCenter = function(c, s) { if (c == null) { c = _gMap.center; } if (s == null) { s = scope; } if (_.contains(disabledEvents, 'center')) { return; } if (angular.isDefined(s.center.type)) { if (s.center.coordinates[1] !== c.lat()) { s.center.coordinates[1] = c.lat(); } if (s.center.coordinates[0] !== c.lng()) { return s.center.coordinates[0] = c.lng(); } } else { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } }; settingFromDirective = false; maybeHookToEvent('idle', function() { var b, ne, sw; b = _gMap.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); settingFromDirective = true; return scope.$evalAsync(function(s) { updateCenter(); if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0 && !_.contains(disabledEvents, 'bounds')) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } if (!_.contains(disabledEvents, 'zoom')) { s.zoom = _gMap.zoom; scope.idleAndZoomChanged = !scope.idleAndZoomChanged; } return settingFromDirective = false; }); }); } if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_gMap, eventName, arguments]); }; }; customListeners = []; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { customListeners.push(google.maps.event.addListener(_gMap, eventName, getEventHandler(eventName))); } } listeners.concat(customListeners); } _gMap.getOptions = function() { return mapOptions; }; scope.map = _gMap; if ((attrs.control != null) && (scope.control != null)) { scope.control.refresh = function(maybeCoords) { var coords, ref1, ref2; if (_gMap == null) { return; } if (((typeof google !== "undefined" && google !== null ? (ref1 = google.maps) != null ? (ref2 = ref1.event) != null ? ref2.trigger : void 0 : void 0 : void 0) != null) && (_gMap != null)) { google.maps.event.trigger(_gMap, 'resize'); } if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.longitude : void 0) != null)) { coords = _this.getCoords(maybeCoords); if (_this.isTrue(attrs.pan)) { return _gMap.panTo(coords); } else { return _gMap.setCenter(coords); } } }; scope.control.getGMap = function() { return _gMap; }; scope.control.getMapOptions = function() { return mapOptions; }; scope.control.getCustomEventListeners = function() { return customListeners; }; scope.control.removeEvents = function(yourListeners) { return EventsHelper.removeEvents(yourListeners); }; } scope.$watch('center', function(newValue, oldValue) { var coords, settingCenterFromScope; if (newValue === oldValue || settingFromDirective) { return; } coords = _this.getCoords(scope.center); if (coords.lat() === _gMap.center.lat() && coords.lng() === _gMap.center.lng()) { return; } settingCenterFromScope = true; if (!dragging) { if (!_this.validateCoords(newValue)) { $log.error("Invalid center for newValue: " + (JSON.stringify(newValue))); } if (_this.isTrue(attrs.pan) && scope.zoom === _gMap.zoom) { _gMap.panTo(coords); } else { _gMap.setCenter(coords); } } return settingCenterFromScope = false; }, true); zoomPromise = null; scope.$watch('zoom', function(newValue, oldValue) { var ref1, ref2, settingZoomFromScope; if (newValue == null) { return; } if (_.isEqual(newValue, oldValue) || (_gMap != null ? _gMap.getZoom() : void 0) === (scope != null ? scope.zoom : void 0) || settingFromDirective) { return; } settingZoomFromScope = true; if (zoomPromise != null) { $timeout.cancel(zoomPromise); } return zoomPromise = $timeout(function() { _gMap.setZoom(newValue); return settingZoomFromScope = false; }, ((ref1 = scope.eventOpts) != null ? (ref2 = ref1.debounce) != null ? ref2.zoomMs : void 0 : void 0) + 20, false); }); scope.$watch('bounds', function(newValue, oldValue) { var bounds, ne, ref1, ref2, ref3, ref4, sw; if (newValue === oldValue) { return; } if (((newValue != null ? (ref1 = newValue.northeast) != null ? ref1.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref2 = newValue.northeast) != null ? ref2.longitude : void 0 : void 0) == null) || ((newValue != null ? (ref3 = newValue.southwest) != null ? ref3.latitude : void 0 : void 0) == null) || ((newValue != null ? (ref4 = newValue.southwest) != null ? ref4.longitude : void 0 : void 0) == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _gMap.fitBounds(bounds); }); return ['options', 'styles'].forEach(function(toWatch) { return scope.$watch(toWatch, function(newValue, oldValue) { var watchItem; watchItem = this.exp; if (_.isEqual(newValue, oldValue)) { return; } if (watchItem === 'options') { opts.options = newValue; } else { opts.options[watchItem] = newValue; } if (_gMap != null) { return _gMap.setOptions(opts); } }, true); }); }; })(this)); }; return Map; })(BaseObject); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [ "uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", "uiGmapLogger", function(IMarker, MarkerChildModel, MarkerManager, $log) { var Marker; return Marker = (function(superClass) { extend(Marker, superClass); function Marker() { this.link = bind(this.link, this); Marker.__super__.constructor.call(this); this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; $log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Marker'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { var mapPromise; mapPromise = IMarker.mapPromise(scope, ctrl); mapPromise.then((function(_this) { return function(map) { var doClick, doDrawSelf, gManager, keys, m, trackModel; gManager = new MarkerManager(map); keys = _.object(IMarker.keys, IMarker.keys); m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, gManager, doDrawSelf = false, trackModel = false); m.deferred.promise.then(function(gMarker) { return scope.deferred.resolve(gMarker); }); if (scope.control != null) { return scope.control.getGMarkers = gManager.getGMarkers; } }; })(this)); return scope.$on('$destroy', (function(_this) { return function() { var gManager; if (typeof gManager !== "undefined" && gManager !== null) { gManager.clear(); } return gManager = null; }; })(this)); }; return Marker; })(IMarker); } ]); }).call(this); ;(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [ "uiGmapIMarker", "uiGmapPlural", "uiGmapMarkersParentModel", "uiGmap_sync", "uiGmapLogger", function(IMarker, Plural, MarkersParentModel, _sync, $log) { var Markers; return Markers = (function(superClass) { extend(Markers, superClass); function Markers() { Markers.__super__.constructor.call(this); this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; Plural.extend(this, { doCluster: '=docluster', clusterOptions: '=clusteroptions', clusterEvents: '=clusterevents', modelsByRef: '=modelsbyref' }); $log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Markers'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { var parentModel, ready; parentModel = void 0; ready = function() { return scope.deferred.resolve(); }; return IMarker.mapPromise(scope, ctrl).then(function(map) { var mapScope; mapScope = ctrl.getScope(); mapScope.$watch('idleAndZoomChanged', function() { return _.defer(parentModel.gManager.draw); }); parentModel = new MarkersParentModel(scope, element, attrs, map); Plural.link(scope, parentModel); if (scope.control != null) { scope.control.getGMarkers = function() { var ref; return (ref = parentModel.gManager) != null ? ref.getGMarkers() : void 0; }; scope.control.getChildMarkers = function() { return parentModel.plurals; }; } return _.last(parentModel.existingPieces._content).then(function() { return ready(); }); }); }; return Markers; })(IMarker); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').service('uiGmapPlural', [ function() { var _initControl; _initControl = function(scope, parent) { if (scope.control == null) { return; } scope.control.updateModels = function(models) { scope.models = models; return parent.createChildScopes(false); }; scope.control.newModels = function(models) { scope.models = models; return parent.rebuildAll(scope, true, true); }; scope.control.clean = function() { return parent.rebuildAll(scope, false, true); }; scope.control.getPlurals = function() { return parent.plurals; }; scope.control.getManager = function() { return parent.gManager; }; scope.control.hasManager = function() { return (parent.gManager != null) === true; }; return scope.control.managerDraw = function() { var ref; if (scope.control.hasManager()) { return (ref = scope.control.getManager()) != null ? ref.draw() : void 0; } }; }; return { extend: function(obj, obj2) { return _.extend(obj.scope || {}, obj2 || {}, { idKey: '=idkey', doRebuildAll: '=dorebuildall', models: '=models', chunk: '=chunk', cleanchunk: '=cleanchunk', control: '=control' }); }, link: function(scope, parent) { return _initControl(scope, parent); } }; } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygon', [ 'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonChildModel', function(IPolygon, $timeout, arraySync, PolygonChild) { var Polygon; return Polygon = (function(superClass) { extend(Polygon, superClass); function Polygon() { this.link = bind(this.link, this); return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.link = function(scope, element, attrs, mapCtrl) { var children, promise; children = []; promise = IPolygon.mapPromise(scope, mapCtrl); if (scope.control != null) { scope.control.getInstance = this; scope.control.polygons = children; scope.control.promise = promise; } return promise.then((function(_this) { return function(map) { return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygon; })(IPolygon); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolygons', [ 'uiGmapIPolygon', '$timeout', 'uiGmaparray-sync', 'uiGmapPolygonsParentModel', 'uiGmapPlural', function(Interface, $timeout, arraySync, ParentModel, Plural) { var Polygons; return Polygons = (function(superClass) { extend(Polygons, superClass); function Polygons() { this.link = bind(this.link, this); Polygons.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polygons.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polygons: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polygons: no models found to create from'); } return Plural.link(scope, new ParentModel(scope, element, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygons; })(Interface); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolyline', [ 'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylineChildModel', function(IPolyline, $timeout, arraySync, PolylineChildModel) { var Polyline; return Polyline = (function(superClass) { extend(Polyline, superClass); function Polyline() { this.link = bind(this.link, this); return Polyline.__super__.constructor.apply(this, arguments); } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null || !_this.validatePath(scope.path)) { _this.$log.warn('polyline: no valid path attribute found'); } return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS); }; })(this)); }; return Polyline; })(IPolyline); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapPolylines', [ 'uiGmapIPolyline', '$timeout', 'uiGmaparray-sync', 'uiGmapPolylinesParentModel', 'uiGmapPlural', function(IPolyline, $timeout, arraySync, PolylinesParentModel, Plural) { var Polylines; return Polylines = (function(superClass) { extend(Polylines, superClass); function Polylines() { this.link = bind(this.link, this); Polylines.__super__.constructor.call(this); Plural.extend(this); this.$log.info(this); } Polylines.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (angular.isUndefined(scope.path) || scope.path === null) { _this.$log.warn('polylines: no valid path attribute found'); } if (!scope.models) { _this.$log.warn('polylines: no models found to create from'); } return Plural.link(scope, new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polylines; })(IPolyline); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapRectangle', [ 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapIRectangle', 'uiGmapRectangleParentModel', function($log, GmapUtil, IRectangle, RectangleParentModel) { return _.extend(IRectangle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new RectangleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindow', [ 'uiGmapIWindow', 'uiGmapGmapUtil', 'uiGmapWindowChildModel', 'uiGmapLodash', 'uiGmapLogger', function(IWindow, GmapUtil, WindowChildModel, uiGmapLodash, $log) { var Window; return Window = (function(superClass) { extend(Window, superClass); Window.include(GmapUtil); function Window() { this.link = bind(this.link, this); Window.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; $log.debug(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var markerCtrl, markerScope; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; this.mapPromise = IWindow.mapPromise(scope, ctrls[0]); return this.mapPromise.then((function(_this) { return function(mapCtrl) { var isIconVisibleOnClick; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } if (!markerCtrl) { _this.init(scope, element, isIconVisibleOnClick, mapCtrl); return; } return markerScope.deferred.promise.then(function(gMarker) { return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope); }); }; })(this)); }; Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) { var childWindow, defaults, gMarker, hasScopeCoords, opts; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && this.validateCoords(scope.coords); if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) { gMarker = markerScope.getGMarker(); } opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults; if (mapCtrl != null) { childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element); this.childWindows.push(childWindow); scope.$on('$destroy', (function(_this) { return function() { _this.childWindows = uiGmapLodash.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) { return child1.scope.$id === child2.scope.$id; }); return _this.childWindows.length = 0; }; })(this)); } if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.gObject; }); }; })(this); scope.control.getChildWindows = (function(_this) { return function() { return _this.childWindows; }; })(this); scope.control.getPlurals = scope.control.getChildWindows; scope.control.showWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.showWindow(); }); }; })(this); scope.control.hideWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.hideWindow(); }); }; })(this); } if ((this.onChildCreation != null) && (childWindow != null)) { return this.onChildCreation(childWindow); } }; return Window; })(IWindow); } ]); }).call(this); ;(function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; angular.module('uiGmapgoogle-maps.directives.api').factory('uiGmapWindows', [ 'uiGmapIWindow', 'uiGmapPlural', 'uiGmapWindowsParentModel', 'uiGmapPromise', 'uiGmapLogger', function(IWindow, Plural, WindowsParentModel, uiGmapPromise, $log) { /* Windows directive where many windows map to the models property */ var Windows; return Windows = (function(superClass) { extend(Windows, superClass); function Windows() { this.init = bind(this.init, this); this.link = bind(this.link, this); Windows.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; Plural.extend(this); $log.debug(this); } Windows.prototype.link = function(scope, element, attrs, ctrls) { var mapScope, markerCtrl, markerScope; mapScope = ctrls[0].getScope(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; return mapScope.deferred.promise.then((function(_this) { return function(map) { var promise, ref; promise = (markerScope != null ? (ref = markerScope.deferred) != null ? ref.promise : void 0 : void 0) || uiGmapPromise.resolve(); return promise.then(function() { var pieces, ref1; pieces = (ref1 = _this.parentModel) != null ? ref1.existingPieces : void 0; if (pieces) { return pieces.then(function() { return _this.init(scope, element, attrs, ctrls, map, markerScope); }); } else { return _this.init(scope, element, attrs, ctrls, map, markerScope); } }); }; })(this)); }; Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) { var parentModel; parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope); Plural.link(scope, parentModel); if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return parentModel.plurals.map(function(child) { return child.gObject; }); }; })(this); return scope.control.getChildWindows = (function(_this) { return function() { return parentModel.plurals; }; })(this); } }; return Windows; })(IWindow); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [ "uiGmapMap", function(Map) { return new Map(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapMarker', [ '$timeout', 'uiGmapMarker', function($timeout, Marker) { return new Marker($timeout); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapMarkers', [ '$timeout', 'uiGmapMarkers', function($timeout, Markers) { return new Markers($timeout); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolygon', [ 'uiGmapPolygon', function(Polygon) { return new Polygon(); } ]); }).call(this); ; /* @authors Julian Popescu - https://github.com/jpopesculian Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive("uiGmapCircle", [ "uiGmapCircle", function(Circle) { return Circle; } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [ "uiGmapPolyline", function(Polyline) { return new Polyline(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolylines', [ 'uiGmapPolylines', function(Polylines) { return new Polylines(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Chentsu Lin - https://github.com/ChenTsuLin */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [ "uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) { return Rectangle; } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [ "$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) { return new Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) { return new Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); ; /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive('uiGmapLayer', [ '$timeout', 'uiGmapLogger', 'uiGmapLayerParentModel', function($timeout, Logger, LayerParentModel) { var Layer; Layer = (function() { function Layer() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\'angular-google-map-layer\' ng-transclude></span>'; this.replace = true; this.scope = { show: '=show', type: '=type', namespace: '=namespace', options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (scope.onCreated != null) { return new LayerParentModel(scope, element, attrs, map, scope.onCreated); } else { return new LayerParentModel(scope, element, attrs, map); } }; })(this)); }; return Layer; })(); return new Layer(); } ]); }).call(this); ; /* @authors Adam Kreitals, [email protected] */ /* mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [ "uiGmapControl", function(Control) { return new Control(); } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapDragZoom', [ 'uiGmapDragZoom', function(DragZoom) { return DragZoom; } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').directive("uiGmapDrawingManager", [ "uiGmapDrawingManager", function(DrawingManager) { return DrawingManager; } ]); }).call(this); ; /* @authors Nicholas McCready - https://twitter.com/nmccready * Brunt of the work is in DrawFreeHandChildModel */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapFreeDrawPolygons', [ 'uiGmapApiFreeDrawPolygons', function(FreeDrawPolygons) { return new FreeDrawPolygons(); } ]); }).call(this); ; /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [ "$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) { var MapType; MapType = (function() { function MapType() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", options: '=options', refresh: '=refresh', id: '@' }; } MapType.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new MapTypeParentModel(scope, element, attrs, map); }; })(this)); }; return MapType; })(); return new MapType(); } ]); }).call(this); ; /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapPolygons', [ 'uiGmapPolygons', function(Polygons) { return new Polygons(); } ]); }).call(this); ; /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready - Carrie Kengle - http://about.me/carrie */ /* Places Search Box directive This directive is used to create a Places Search Box. This directive creates a new scope. {attribute input required} HTMLInputElement {attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification) */ (function() { var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('uiGmapgoogle-maps').directive('uiGmapSearchBox', [ 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) { var SearchBox; SearchBox = (function() { SearchBox.prototype.require = 'ngModel'; function SearchBox() { this.link = bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'uiGmapGoogleMap'; this.priority = -1; this.transclude = true; this.template = '<span class=\'angular-google-map-search\' ng-transclude></span>'; this.replace = true; this.scope = { template: '=template', events: '=events', position: '=?position', options: '=?options', parentdiv: '=?parentdiv', ngModel: "=?" }; } SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) { return GoogleMapApi.then((function(_this) { return function(maps) { return $http.get(scope.template, { cache: $templateCache }).success(function(template) { if (angular.isUndefined(scope.events)) { _this.$log.error('searchBox: the events property is required'); return; } return mapCtrl.getScope().deferred.promise.then(function(map) { var ctrlPosition; ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT'; if (!maps.ControlPosition[ctrlPosition]) { _this.$log.error('searchBox: invalid position property'); return; } return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope)); }); }); }; })(this)); }; return SearchBox; })(); return new SearchBox(); } ]); }).call(this); ;(function() { angular.module('uiGmapgoogle-maps').directive('uiGmapShow', [ '$animate', 'uiGmapLogger', function($animate, $log) { return { scope: { 'uiGmapShow': '=', 'uiGmapAfterShow': '&', 'uiGmapAfterHide': '&' }, link: function(scope, element) { var angular_post_1_3_handle, angular_pre_1_3_handle, handle; angular_post_1_3_handle = function(animateAction, cb) { return $animate[animateAction](element, 'ng-hide').then(function() { return cb(); }); }; angular_pre_1_3_handle = function(animateAction, cb) { return $animate[animateAction](element, 'ng-hide', cb); }; handle = function(animateAction, cb) { if (angular.version.major > 1) { return $log.error("uiGmapShow is not supported for Angular Major greater than 1.\nYour Major is " + angular.version.major + "\""); } if (angular.version.major === 1 && angular.version.minor < 3) { return angular_pre_1_3_handle(animateAction, cb); } return angular_post_1_3_handle(animateAction, cb); }; return scope.$watch('uiGmapShow', function(show) { if (show) { handle('removeClass', scope.uiGmapAfterShow); } if (!show) { return handle('addClass', scope.uiGmapAfterHide); } }); } }; } ]); }).call(this); ; /* @authors: - Nicholas McCready - https://twitter.com/nmccready */ /* StreetViewPanorama Directive to care of basic initialization of StreetViewPanorama */ (function() { angular.module('uiGmapgoogle-maps').directive('uiGmapStreetViewPanorama', [ 'uiGmapGoogleMapApi', 'uiGmapLogger', 'uiGmapGmapUtil', 'uiGmapEventsHelper', function(GoogleMapApi, $log, GmapUtil, EventsHelper) { var name; name = 'uiGmapStreetViewPanorama'; return { restrict: 'EMA', template: '<div class="angular-google-map-street-view-panorama"></div>', replace: true, scope: { focalcoord: '=', radius: '=?', events: '=?', options: '=?', control: '=?', povoptions: '=?', imagestatus: '=' }, link: function(scope, element, attrs) { return GoogleMapApi.then((function(_this) { return function(maps) { var clean, create, didCreateOptionsFromDirective, firstTime, handleSettings, listeners, opts, pano, povOpts, sv; pano = void 0; sv = void 0; didCreateOptionsFromDirective = false; listeners = void 0; opts = null; povOpts = null; clean = function() { EventsHelper.removeEvents(listeners); if (pano != null) { pano.unbind('position'); pano.setVisible(false); } if (sv != null) { if ((sv != null ? sv.setVisible : void 0) != null) { sv.setVisible(false); } return sv = void 0; } }; handleSettings = function(perspectivePoint, focalPoint) { var heading; heading = google.maps.geometry.spherical.computeHeading(perspectivePoint, focalPoint); didCreateOptionsFromDirective = true; scope.radius = scope.radius || 50; povOpts = angular.extend({ heading: heading, zoom: 1, pitch: 0 }, scope.povoptions || {}); opts = opts = angular.extend({ navigationControl: false, addressControl: false, linksControl: false, position: perspectivePoint, pov: povOpts, visible: true }, scope.options || {}); return didCreateOptionsFromDirective = false; }; create = function() { var focalPoint; if (!scope.focalcoord) { $log.error(name + ": focalCoord needs to be defined"); return; } if (!scope.radius) { $log.error(name + ": needs a radius to set the camera view from its focal target."); return; } clean(); if (sv == null) { sv = new google.maps.StreetViewService(); } if (scope.events) { listeners = EventsHelper.setEvents(sv, scope, scope); } focalPoint = GmapUtil.getCoords(scope.focalcoord); return sv.getPanoramaByLocation(focalPoint, scope.radius, function(streetViewPanoramaData, status) { var ele, perspectivePoint, ref; if (scope.imagestatus != null) { scope.imagestatus = status; } if (((ref = scope.events) != null ? ref.image_status_changed : void 0) != null) { scope.events.image_status_changed(sv, 'image_status_changed', scope, status); } if (status === "OK") { perspectivePoint = streetViewPanoramaData.location.latLng; handleSettings(perspectivePoint, focalPoint); ele = element[0]; return pano = new google.maps.StreetViewPanorama(ele, opts); } }); }; if (scope.control != null) { scope.control.getOptions = function() { return opts; }; scope.control.getPovOptions = function() { return povOpts; }; scope.control.getGObject = function() { return sv; }; } scope.$watch('options', function(newValue, oldValue) { if (newValue === oldValue || newValue === opts || didCreateOptionsFromDirective) { return; } return create(); }); firstTime = true; scope.$watch('focalcoord', function(newValue, oldValue) { if (newValue === oldValue && !firstTime) { return; } if (newValue == null) { return; } firstTime = false; return create(); }); return scope.$on('$destroy', function() { return clean(); }); }; })(this)); } }; } ]); }).call(this); ;angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapuuid', function() { //BEGIN REPLACE /* Version: core-1.0 The MIT License: Copyright (c) 2012 LiosK. */ function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c}; //END REPLACE return UUID; }); ;// wrap the utility libraries needed in ./lib // http://google-maps-utility-library-v3.googlecode.com/svn/ angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapGoogleMapsUtilV3', function () { return { init: _.once(function () { //BEGIN REPLACE /** * @name InfoBox * @version 1.1.13 [March 19, 2014] * @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google) * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] * @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class. * <p> * An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several * additional properties for advanced styling. An InfoBox can also be used as a map label. * <p> * An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>. */ /*! * * 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. */ /*jslint browser:true */ /*global google */ /** * @name InfoBoxOptions * @class This class represents the optional parameter passed to the {@link InfoBox} constructor. * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node). * @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>. * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum. * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox * (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>) * to the map pixel corresponding to <tt>position</tt>. * @property {LatLng} position The geographic location at which to display the InfoBox. * @property {number} zIndex The CSS z-index style value for the InfoBox. * Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property. * @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container. * @property {Object} [boxStyle] An object literal whose properties define specific CSS * style values to be applied to the InfoBox. Style values defined here override those that may * be defined in the <code>boxClass</code> style sheet. If this property is changed after the * InfoBox has been created, all previously set styles (except those defined in the style sheet) * are removed from the InfoBox before the new style values are applied. * @property {string} closeBoxMargin The CSS margin style value for the close box. * The default is "2px" (a 2-pixel margin on all sides). * @property {string} closeBoxURL The URL of the image representing the close box. * Note: The default is the URL for Google's standard close box. * Set this property to "" if no close box is required. * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the * map edge after an auto-pan. * @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>. * [Deprecated in favor of the <tt>visible</tt> property.] * @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>. * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code> * location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned). * @property {string} pane The pane where the InfoBox is to appear (default is "floatPane"). * Set the pane to "mapPane" if the InfoBox is being used as a map label. * Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object. * @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout, * mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox * (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set * this property to <tt>true</tt> if the InfoBox is being used as a map label. */ /** * Creates an InfoBox with the options specified in {@link InfoBoxOptions}. * Call <tt>InfoBox.open</tt> to add the box to the map. * @constructor * @param {InfoBoxOptions} [opt_opts] */ function InfoBox(opt_opts) { opt_opts = opt_opts || {}; google.maps.OverlayView.apply(this, arguments); // Standard options (in common with google.maps.InfoWindow): // this.content_ = opt_opts.content || ""; this.disableAutoPan_ = opt_opts.disableAutoPan || false; this.maxWidth_ = opt_opts.maxWidth || 0; this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0); this.position_ = opt_opts.position || new google.maps.LatLng(0, 0); this.zIndex_ = opt_opts.zIndex || null; // Additional options (unique to InfoBox): // this.boxClass_ = opt_opts.boxClass || "infoBox"; this.boxStyle_ = opt_opts.boxStyle || {}; this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px"; this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif"; if (opt_opts.closeBoxURL === "") { this.closeBoxURL_ = ""; } this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1); if (typeof opt_opts.visible === "undefined") { if (typeof opt_opts.isHidden === "undefined") { opt_opts.visible = true; } else { opt_opts.visible = !opt_opts.isHidden; } } this.isHidden_ = !opt_opts.visible; this.alignBottom_ = opt_opts.alignBottom || false; this.pane_ = opt_opts.pane || "floatPane"; this.enableEventPropagation_ = opt_opts.enableEventPropagation || false; this.div_ = null; this.closeListener_ = null; this.moveListener_ = null; this.contextListener_ = null; this.eventListeners_ = null; this.fixedWidthSet_ = null; } /* InfoBox extends OverlayView in the Google Maps API v3. */ InfoBox.prototype = new google.maps.OverlayView(); /** * Creates the DIV representing the InfoBox. * @private */ InfoBox.prototype.createInfoBoxDiv_ = function () { var i; var events; var bw; var me = this; // This handler prevents an event in the InfoBox from being passed on to the map. // var cancelHandler = function (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; // This handler ignores the current event in the InfoBox and conditionally prevents // the event from being passed on to the map. It is used for the contextmenu event. // var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }; if (!this.div_) { this.div_ = document.createElement("div"); this.setBoxStyle_(); if (typeof this.content_.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + this.content_; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(this.content_); } // Add the InfoBox DIV to the DOM this.getPanes()[this.pane_].appendChild(this.div_); this.addClickHandler_(); if (this.div_.style.width) { this.fixedWidthSet_ = true; } else { if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) { this.div_.style.width = this.maxWidth_; this.div_.style.overflow = "auto"; this.fixedWidthSet_ = true; } else { // The following code is needed to overcome problems with MSIE bw = this.getBoxWidths_(); this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px"; this.fixedWidthSet_ = false; } } this.panBox_(this.disableAutoPan_); if (!this.enableEventPropagation_) { this.eventListeners_ = []; // Cancel event propagation. // // Note: mousemove not included (to resolve Issue 152) events = ["mousedown", "mouseover", "mouseout", "mouseup", "click", "dblclick", "touchstart", "touchend", "touchmove"]; for (i = 0; i < events.length; i++) { this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler)); } // Workaround for Google bug that causes the cursor to change to a pointer // when the mouse moves over a marker underneath InfoBox. this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) { this.style.cursor = "default"; })); } this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler); /** * This event is fired when the DIV containing the InfoBox's content is attached to the DOM. * @name InfoBox#domready * @event */ google.maps.event.trigger(this, "domready"); } }; /** * Returns the HTML <IMG> tag for the close box. * @private */ InfoBox.prototype.getCloseBoxImg_ = function () { var img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; // Do this because Opera chokes on style='float: right;' img += " style='"; img += " position: relative;"; // Required by MSIE img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; /** * Adds the click handler to the InfoBox close box. * @private */ InfoBox.prototype.addClickHandler_ = function () { var closeBox; if (this.closeBoxURL_ !== "") { closeBox = this.div_.firstChild; this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_()); } else { this.closeListener_ = null; } }; /** * Returns the function to call when the user clicks the close box of an InfoBox. * @private */ InfoBox.prototype.getCloseClickHandler_ = function () { var me = this; return function (e) { // 1.0.3 fix: Always prevent propagation of a close box click to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } /** * This event is fired when the InfoBox's close box is clicked. * @name InfoBox#closeclick * @event */ google.maps.event.trigger(me, "closeclick"); me.close(); }; }; /** * Pans the map so that the InfoBox appears entirely within the map's visible area. * @private */ InfoBox.prototype.panBox_ = function (disablePan) { var map; var bounds; var xOffset = 0, yOffset = 0; if (!disablePan) { map = this.getMap(); if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama if (!map.getBounds().contains(this.position_)) { // Marker not in visible area of map, so set center // of map to the marker position first. map.setCenter(this.position_); } bounds = map.getBounds(); var mapDiv = map.getDiv(); var mapWidth = mapDiv.offsetWidth; var mapHeight = mapDiv.offsetHeight; var iwOffsetX = this.pixelOffset_.width; var iwOffsetY = this.pixelOffset_.height; var iwWidth = this.div_.offsetWidth; var iwHeight = this.div_.offsetHeight; var padX = this.infoBoxClearance_.width; var padY = this.infoBoxClearance_.height; var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_); if (pixPosition.x < (-iwOffsetX + padX)) { xOffset = pixPosition.x + iwOffsetX - padX; } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) { xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth; } if (this.alignBottom_) { if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) { yOffset = pixPosition.y + iwOffsetY - padY - iwHeight; } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwOffsetY + padY - mapHeight; } } else { if (pixPosition.y < (-iwOffsetY + padY)) { yOffset = pixPosition.y + iwOffsetY - padY; } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight; } } if (!(xOffset === 0 && yOffset === 0)) { // Move the map to the shifted center. // var c = map.getCenter(); map.panBy(xOffset, yOffset); } } } }; /** * Sets the style of the InfoBox by setting the style sheet and applying * other specific styles requested. * @private */ InfoBox.prototype.setBoxStyle_ = function () { var i, boxStyle; if (this.div_) { // Apply style values from the style sheet defined in the boxClass parameter: this.div_.className = this.boxClass_; // Clear existing inline style values: this.div_.style.cssText = ""; // Apply style values defined in the boxStyle parameter: boxStyle = this.boxStyle_; for (i in boxStyle) { if (boxStyle.hasOwnProperty(i)) { this.div_.style[i] = boxStyle[i]; } } // Fix for iOS disappearing InfoBox problem. // See http://stackoverflow.com/questions/9229535/google-maps-markers-disappear-at-certain-zoom-level-only-on-iphone-ipad this.div_.style.WebkitTransform = "translateZ(0)"; // Fix up opacity style for benefit of MSIE: // if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") { // See http://www.quirksmode.org/css/opacity.html this.div_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.div_.style.opacity * 100) + ")\""; this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")"; } // Apply required styles: // this.div_.style.position = "absolute"; this.div_.style.visibility = 'hidden'; if (this.zIndex_ !== null) { this.div_.style.zIndex = this.zIndex_; } } }; /** * Get the widths of the borders of the InfoBox. * @private * @return {Object} widths object (top, bottom left, right) */ InfoBox.prototype.getBoxWidths_ = function () { var computedStyle; var bw = {top: 0, bottom: 0, left: 0, right: 0}; var box = this.div_; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; } } else if (document.documentElement.currentStyle) { // MSIE if (box.currentStyle) { // The current styles may not be in pixel units, but assume they are (bad!) bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0; } } return bw; }; /** * Invoked when <tt>close</tt> is called. Do not call it directly. */ InfoBox.prototype.onRemove = function () { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the InfoBox based on the current map projection and zoom level. */ InfoBox.prototype.draw = function () { this.createInfoBoxDiv_(); var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_); this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px"; if (this.alignBottom_) { this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px"; } else { this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px"; } if (this.isHidden_) { this.div_.style.visibility = "hidden"; } else { this.div_.style.visibility = "visible"; } }; /** * Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>, * <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt> * properties have no affect until the current InfoBox is <tt>close</tt>d and a new one * is <tt>open</tt>ed. * @param {InfoBoxOptions} opt_opts */ InfoBox.prototype.setOptions = function (opt_opts) { if (typeof opt_opts.boxClass !== "undefined") { // Must be first this.boxClass_ = opt_opts.boxClass; this.setBoxStyle_(); } if (typeof opt_opts.boxStyle !== "undefined") { // Must be second this.boxStyle_ = opt_opts.boxStyle; this.setBoxStyle_(); } if (typeof opt_opts.content !== "undefined") { this.setContent(opt_opts.content); } if (typeof opt_opts.disableAutoPan !== "undefined") { this.disableAutoPan_ = opt_opts.disableAutoPan; } if (typeof opt_opts.maxWidth !== "undefined") { this.maxWidth_ = opt_opts.maxWidth; } if (typeof opt_opts.pixelOffset !== "undefined") { this.pixelOffset_ = opt_opts.pixelOffset; } if (typeof opt_opts.alignBottom !== "undefined") { this.alignBottom_ = opt_opts.alignBottom; } if (typeof opt_opts.position !== "undefined") { this.setPosition(opt_opts.position); } if (typeof opt_opts.zIndex !== "undefined") { this.setZIndex(opt_opts.zIndex); } if (typeof opt_opts.closeBoxMargin !== "undefined") { this.closeBoxMargin_ = opt_opts.closeBoxMargin; } if (typeof opt_opts.closeBoxURL !== "undefined") { this.closeBoxURL_ = opt_opts.closeBoxURL; } if (typeof opt_opts.infoBoxClearance !== "undefined") { this.infoBoxClearance_ = opt_opts.infoBoxClearance; } if (typeof opt_opts.isHidden !== "undefined") { this.isHidden_ = opt_opts.isHidden; } if (typeof opt_opts.visible !== "undefined") { this.isHidden_ = !opt_opts.visible; } if (typeof opt_opts.enableEventPropagation !== "undefined") { this.enableEventPropagation_ = opt_opts.enableEventPropagation; } if (this.div_) { this.draw(); } }; /** * Sets the content of the InfoBox. * The content can be plain text or an HTML DOM node. * @param {string|Node} content */ InfoBox.prototype.setContent = function (content) { this.content_ = content; if (this.div_) { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } // Odd code required to make things work with MSIE. // if (!this.fixedWidthSet_) { this.div_.style.width = ""; } if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } // Perverse code required to make things work with MSIE. // (Ensures the close box does, in fact, float to the right.) // if (!this.fixedWidthSet_) { this.div_.style.width = this.div_.offsetWidth + "px"; if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } } this.addClickHandler_(); } /** * This event is fired when the content of the InfoBox changes. * @name InfoBox#content_changed * @event */ google.maps.event.trigger(this, "content_changed"); }; /** * Sets the geographic location of the InfoBox. * @param {LatLng} latlng */ InfoBox.prototype.setPosition = function (latlng) { this.position_ = latlng; if (this.div_) { this.draw(); } /** * This event is fired when the position of the InfoBox changes. * @name InfoBox#position_changed * @event */ google.maps.event.trigger(this, "position_changed"); }; /** * Sets the zIndex style for the InfoBox. * @param {number} index */ InfoBox.prototype.setZIndex = function (index) { this.zIndex_ = index; if (this.div_) { this.div_.style.zIndex = index; } /** * This event is fired when the zIndex of the InfoBox changes. * @name InfoBox#zindex_changed * @event */ google.maps.event.trigger(this, "zindex_changed"); }; /** * Sets the visibility of the InfoBox. * @param {boolean} isVisible */ InfoBox.prototype.setVisible = function (isVisible) { this.isHidden_ = !isVisible; if (this.div_) { this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible"); } }; /** * Returns the content of the InfoBox. * @returns {string} */ InfoBox.prototype.getContent = function () { return this.content_; }; /** * Returns the geographic location of the InfoBox. * @returns {LatLng} */ InfoBox.prototype.getPosition = function () { return this.position_; }; /** * Returns the zIndex for the InfoBox. * @returns {number} */ InfoBox.prototype.getZIndex = function () { return this.zIndex_; }; /** * Returns a flag indicating whether the InfoBox is visible. * @returns {boolean} */ InfoBox.prototype.getVisible = function () { var isVisible; if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) { isVisible = false; } else { isVisible = !this.isHidden_; } return isVisible; }; /** * Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.show = function () { this.isHidden_ = false; if (this.div_) { this.div_.style.visibility = "visible"; } }; /** * Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.hide = function () { this.isHidden_ = true; if (this.div_) { this.div_.style.visibility = "hidden"; } }; /** * Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt> * (usually a <tt>google.maps.Marker</tt>) is specified, the position * of the InfoBox is set to the position of the <tt>anchor</tt>. If the * anchor is dragged to a new location, the InfoBox moves as well. * @param {Map|StreetViewPanorama} map * @param {MVCObject} [anchor] */ InfoBox.prototype.open = function (map, anchor) { var me = this; if (anchor) { this.position_ = anchor.getPosition(); this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () { me.setPosition(this.getPosition()); }); } this.setMap(map); if (this.div_) { this.panBox_(); } }; /** * Removes the InfoBox from the map. */ InfoBox.prototype.close = function () { var i; if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } if (this.eventListeners_) { for (i = 0; i < this.eventListeners_.length; i++) { google.maps.event.removeListener(this.eventListeners_[i]); } this.eventListeners_ = null; } if (this.moveListener_) { google.maps.event.removeListener(this.moveListener_); this.moveListener_ = null; } if (this.contextListener_) { google.maps.event.removeListener(this.contextListener_); this.contextListener_ = null; } this.setMap(null); }; /** * @name KeyDragZoom for V3 * @version 2.0.9 [December 17, 2012] NOT YET RELEASED * @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com] * @fileoverview This library adds a drag zoom capability to a V3 Google map. * When drag zoom is enabled, holding down a designated hot key <code>(shift | ctrl | alt)</code> * while dragging a box around an area of interest will zoom the map in to that area when * the mouse button is released. Optionally, a visual control can also be supplied for turning * a drag zoom operation on and off. * Only one line of code is needed: <code>google.maps.Map.enableKeyDragZoom();</code> * <p> * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2, * it causes a context menu to appear when running on the Macintosh. * <p> * Note that if the map's container has a border around it, the border widths must be specified * in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation. * <p>NL: 2009-05-28: initial port to core API V3. * <br>NL: 2009-11-02: added a temp fix for -moz-transform for FF3.5.x using code from Paul Kulchenko (http://notebook.kulchenko.com/maps/gridmove). * <br>NL: 2010-02-02: added a fix for IE flickering on divs onmousemove, caused by scroll value when get mouse position. * <br>GL: 2010-06-15: added a visual control option. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function () { /*jslint browser:true */ /*global window,google */ /* Utility functions use "var funName=function()" syntax to allow use of the */ /* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */ /** * Converts "thin", "medium", and "thick" to pixel widths * in an MSIE environment. Not called for other browsers * because getComputedStyle() returns pixel widths automatically. * @param {string} widthValue The value of the border width parameter. */ var toPixels = function (widthValue) { var px; switch (widthValue) { case "thin": px = "2px"; break; case "medium": px = "4px"; break; case "thick": px = "6px"; break; default: px = widthValue; } return px; }; /** * Get the widths of the borders of an HTML element. * * @param {Node} h The HTML element. * @return {Object} The width object {top, bottom left, right}. */ var getBorderWidths = function (h) { var computedStyle; var bw = {}; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; return bw; } } else if (document.documentElement.currentStyle) { // MSIE if (h.currentStyle) { // The current styles may not be in pixel units so try to convert (bad!) bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0; bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0; bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0; bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0; return bw; } } // Shouldn't get this far for any modern browser bw.top = parseInt(h.style["border-top-width"], 10) || 0; bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0; bw.left = parseInt(h.style["border-left-width"], 10) || 0; bw.right = parseInt(h.style["border-right-width"], 10) || 0; return bw; }; // Page scroll values for use by getMousePosition. To prevent flickering on MSIE // they are calculated only when the document actually scrolls, not every time the // mouse moves (as they would be if they were calculated inside getMousePosition). var scroll = { x: 0, y: 0 }; var getScrollValue = function (e) { scroll.x = (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft); scroll.y = (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop); }; getScrollValue(); /** * Get the position of the mouse relative to the document. * @param {Event} e The mouse event. * @return {Object} The position object {left, top}. */ var getMousePosition = function (e) { var posX = 0, posY = 0; e = e || window.event; if (typeof e.pageX !== "undefined") { posX = e.pageX; posY = e.pageY; } else if (typeof e.clientX !== "undefined") { // MSIE posX = e.clientX + scroll.x; posY = e.clientY + scroll.y; } return { left: posX, top: posY }; }; /** * Get the position of an HTML element relative to the document. * @param {Node} h The HTML element. * @return {Object} The position object {left, top}. */ var getElementPosition = function (h) { var posX = h.offsetLeft; var posY = h.offsetTop; var parent = h.offsetParent; // Add offsets for all ancestors in the hierarchy while (parent !== null) { // Adjust for scrolling elements which may affect the map position. // // See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific // // "...make sure that every element [on a Web page] with an overflow // of anything other than visible also has a position style set to // something other than the default static..." if (parent !== document.body && parent !== document.documentElement) { posX -= parent.scrollLeft; posY -= parent.scrollTop; } // See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5 // Example: http://notebook.kulchenko.com/maps/gridmove var m = parent; // This is the "normal" way to get offset information: var moffx = m.offsetLeft; var moffy = m.offsetTop; // This covers those cases where a transform is used: if (!moffx && !moffy && window.getComputedStyle) { var matrix = document.defaultView.getComputedStyle(m, null).MozTransform || document.defaultView.getComputedStyle(m, null).WebkitTransform; if (matrix) { if (typeof matrix === "string") { var parms = matrix.split(","); moffx += parseInt(parms[4], 10) || 0; moffy += parseInt(parms[5], 10) || 0; } } } posX += moffx; posY += moffy; parent = parent.offsetParent; } return { left: posX, top: posY }; }; /** * Set the properties of an object to those from another object. * @param {Object} obj The target object. * @param {Object} vals The source object. */ var setVals = function (obj, vals) { if (obj && vals) { for (var x in vals) { if (vals.hasOwnProperty(x)) { obj[x] = vals[x]; } } } return obj; }; /** * Set the opacity. If op is not passed in, this function just performs an MSIE fix. * @param {Node} h The HTML element. * @param {number} op The opacity value (0-1). */ var setOpacity = function (h, op) { if (typeof op !== "undefined") { h.style.opacity = op; } if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") { h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")"; } }; /** * @name KeyDragZoomOptions * @class This class represents the optional parameter passed into <code>google.maps.Map.enableKeyDragZoom</code>. * @property {string} [key="shift"] The hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>. * NOTE: Do not use Ctrl as the hot key with Google Maps JavaScript API V3 since, unlike with V2, * it causes a context menu to appear when running on the Macintosh. Also note that the * <code>alt</code> hot key refers to the Option key on a Macintosh. * @property {Object} [boxStyle={border: "4px solid #736AFF"}] * An object literal defining the CSS styles of the zoom box. * Border widths must be specified in pixel units (or as thin, medium, or thick). * @property {Object} [veilStyle={backgroundColor: "gray", opacity: 0.25, cursor: "crosshair"}] * An object literal defining the CSS styles of the veil pane which covers the map when a drag * zoom is activated. The previous name for this property was <code>paneStyle</code> but the use * of this name is now deprecated. * @property {boolean} [noZoom=false] A flag indicating whether to disable zooming after an area is * selected. Set this to <code>true</code> to allow KeyDragZoom to be used as a simple area * selection tool. * @property {boolean} [visualEnabled=false] A flag indicating whether a visual control is to be used. * @property {string} [visualClass=""] The name of the CSS class defining the styles for the visual * control. To prevent the visual control from being printed, set this property to the name of * a class, defined inside a <code>@media print</code> rule, which sets the CSS * <code>display</code> style to <code>none</code>. * @property {ControlPosition} [visualPosition=google.maps.ControlPosition.LEFT_TOP] * The position of the visual control. * @property {Size} [visualPositionOffset=google.maps.Size(35, 0)] The width and height values * provided by this property are the offsets (in pixels) from the location at which the control * would normally be drawn to the desired drawing location. * @property {number} [visualPositionIndex=null] The index of the visual control. * The index is for controlling the placement of the control relative to other controls at the * position given by <code>visualPosition</code>; controls with a lower index are placed first. * Use a negative value to place the control <i>before</i> any default controls. No index is * generally required. * @property {String} [visualSprite="http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"] * The URL of the sprite image used for showing the visual control in the on, off, and hot * (i.e., when the mouse is over the control) states. The three images within the sprite must * be the same size and arranged in on-hot-off order in a single row with no spaces between images. * @property {Size} [visualSize=google.maps.Size(20, 20)] The width and height values provided by * this property are the size (in pixels) of each of the images within <code>visualSprite</code>. * @property {Object} [visualTips={off: "Turn on drag zoom mode", on: "Turn off drag zoom mode"}] * An object literal defining the help tips that appear when * the mouse moves over the visual control. The <code>off</code> property is the tip to be shown * when the control is off and the <code>on</code> property is the tip to be shown when the * control is on. */ /** * @name DragZoom * @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key * or by turning on the visual control. * This object is created when <code>google.maps.Map.enableKeyDragZoom</code> is called; it cannot be created directly. * Use <code>google.maps.Map.getDragZoomObject</code> to gain access to this object in order to attach event listeners. * @param {Map} map The map to which the DragZoom object is to be attached. * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters. */ function DragZoom(map, opt_zoomOpts) { var me = this; var ov = new google.maps.OverlayView(); ov.onAdd = function () { me.init_(map, opt_zoomOpts); }; ov.draw = function () { }; ov.onRemove = function () { }; ov.setMap(map); this.prjov_ = ov; } /** * Initialize the tool. * @param {Map} map The map to which the DragZoom object is to be attached. * @param {KeyDragZoomOptions} [opt_zoomOpts] The optional parameters. */ DragZoom.prototype.init_ = function (map, opt_zoomOpts) { var i; var me = this; this.map_ = map; opt_zoomOpts = opt_zoomOpts || {}; this.key_ = opt_zoomOpts.key || "shift"; this.key_ = this.key_.toLowerCase(); this.borderWidths_ = getBorderWidths(this.map_.getDiv()); this.veilDiv_ = []; for (i = 0; i < 4; i++) { this.veilDiv_[i] = document.createElement("div"); // Prevents selection of other elements on the webpage // when a drag zoom operation is in progress: this.veilDiv_[i].onselectstart = function () { return false; }; // Apply default style values for the veil: setVals(this.veilDiv_[i].style, { backgroundColor: "gray", opacity: 0.25, cursor: "crosshair" }); // Apply style values specified in veilStyle parameter: setVals(this.veilDiv_[i].style, opt_zoomOpts.paneStyle); // Old option name was "paneStyle" setVals(this.veilDiv_[i].style, opt_zoomOpts.veilStyle); // New name is "veilStyle" // Apply mandatory style values: setVals(this.veilDiv_[i].style, { position: "absolute", overflow: "hidden", display: "none" }); // Workaround for Firefox Shift-Click problem: if (this.key_ === "shift") { this.veilDiv_[i].style.MozUserSelect = "none"; } setOpacity(this.veilDiv_[i]); // An IE fix: If the background is transparent it cannot capture mousedown // events, so if it is, change the background to white with 0 opacity. if (this.veilDiv_[i].style.backgroundColor === "transparent") { this.veilDiv_[i].style.backgroundColor = "white"; setOpacity(this.veilDiv_[i], 0); } this.map_.getDiv().appendChild(this.veilDiv_[i]); } this.noZoom_ = opt_zoomOpts.noZoom || false; this.visualEnabled_ = opt_zoomOpts.visualEnabled || false; this.visualClass_ = opt_zoomOpts.visualClass || ""; this.visualPosition_ = opt_zoomOpts.visualPosition || google.maps.ControlPosition.LEFT_TOP; this.visualPositionOffset_ = opt_zoomOpts.visualPositionOffset || new google.maps.Size(35, 0); this.visualPositionIndex_ = opt_zoomOpts.visualPositionIndex || null; this.visualSprite_ = opt_zoomOpts.visualSprite || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png"; this.visualSize_ = opt_zoomOpts.visualSize || new google.maps.Size(20, 20); this.visualTips_ = opt_zoomOpts.visualTips || {}; this.visualTips_.off = this.visualTips_.off || "Turn on drag zoom mode"; this.visualTips_.on = this.visualTips_.on || "Turn off drag zoom mode"; this.boxDiv_ = document.createElement("div"); // Apply default style values for the zoom box: setVals(this.boxDiv_.style, { border: "4px solid #736AFF" }); // Apply style values specified in boxStyle parameter: setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle); // Apply mandatory style values: setVals(this.boxDiv_.style, { position: "absolute", display: "none" }); setOpacity(this.boxDiv_); this.map_.getDiv().appendChild(this.boxDiv_); this.boxBorderWidths_ = getBorderWidths(this.boxDiv_); this.listeners_ = [ google.maps.event.addDomListener(document, "keydown", function (e) { me.onKeyDown_(e); }), google.maps.event.addDomListener(document, "keyup", function (e) { me.onKeyUp_(e); }), google.maps.event.addDomListener(this.veilDiv_[0], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[1], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[2], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(this.veilDiv_[3], "mousedown", function (e) { me.onMouseDown_(e); }), google.maps.event.addDomListener(document, "mousedown", function (e) { me.onMouseDownDocument_(e); }), google.maps.event.addDomListener(document, "mousemove", function (e) { me.onMouseMove_(e); }), google.maps.event.addDomListener(document, "mouseup", function (e) { me.onMouseUp_(e); }), google.maps.event.addDomListener(window, "scroll", getScrollValue) ]; this.hotKeyDown_ = false; this.mouseDown_ = false; this.dragging_ = false; this.startPt_ = null; this.endPt_ = null; this.mapWidth_ = null; this.mapHeight_ = null; this.mousePosn_ = null; this.mapPosn_ = null; if (this.visualEnabled_) { this.buttonDiv_ = this.initControl_(this.visualPositionOffset_); if (this.visualPositionIndex_ !== null) { this.buttonDiv_.index = this.visualPositionIndex_; } this.map_.controls[this.visualPosition_].push(this.buttonDiv_); this.controlIndex_ = this.map_.controls[this.visualPosition_].length - 1; } }; /** * Initializes the visual control and returns its DOM element. * @param {Size} offset The offset of the control from its normal position. * @return {Node} The DOM element containing the visual control. */ DragZoom.prototype.initControl_ = function (offset) { var control; var image; var me = this; control = document.createElement("div"); control.className = this.visualClass_; control.style.position = "relative"; control.style.overflow = "hidden"; control.style.height = this.visualSize_.height + "px"; control.style.width = this.visualSize_.width + "px"; control.title = this.visualTips_.off; image = document.createElement("img"); image.src = this.visualSprite_; image.style.position = "absolute"; image.style.left = -(this.visualSize_.width * 2) + "px"; image.style.top = 0 + "px"; control.appendChild(image); control.onclick = function (e) { me.hotKeyDown_ = !me.hotKeyDown_; if (me.hotKeyDown_) { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px"; me.buttonDiv_.title = me.visualTips_.on; me.activatedByControl_ = true; google.maps.event.trigger(me, "activate"); } else { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px"; me.buttonDiv_.title = me.visualTips_.off; google.maps.event.trigger(me, "deactivate"); } me.onMouseMove_(e); // Updates the veil }; control.onmouseover = function () { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 1) + "px"; }; control.onmouseout = function () { if (me.hotKeyDown_) { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 0) + "px"; me.buttonDiv_.title = me.visualTips_.on; } else { me.buttonDiv_.firstChild.style.left = -(me.visualSize_.width * 2) + "px"; me.buttonDiv_.title = me.visualTips_.off; } }; control.ondragstart = function () { return false; }; setVals(control.style, { cursor: "pointer", marginTop: offset.height + "px", marginLeft: offset.width + "px" }); return control; }; /** * Returns <code>true</code> if the hot key is being pressed when an event occurs. * @param {Event} e The keyboard event. * @return {boolean} Flag indicating whether the hot key is down. */ DragZoom.prototype.isHotKeyDown_ = function (e) { var isHot; e = e || window.event; isHot = (e.shiftKey && this.key_ === "shift") || (e.altKey && this.key_ === "alt") || (e.ctrlKey && this.key_ === "ctrl"); if (!isHot) { // Need to look at keyCode for Opera because it // doesn't set the shiftKey, altKey, ctrlKey properties // unless a non-modifier event is being reported. // // See http://cross-browser.com/x/examples/shift_mode.php // Also see http://unixpapa.com/js/key.html switch (e.keyCode) { case 16: if (this.key_ === "shift") { isHot = true; } break; case 17: if (this.key_ === "ctrl") { isHot = true; } break; case 18: if (this.key_ === "alt") { isHot = true; } break; } } return isHot; }; /** * Returns <code>true</code> if the mouse is on top of the map div. * The position is captured in onMouseMove_. * @return {boolean} */ DragZoom.prototype.isMouseOnMap_ = function () { var mousePosn = this.mousePosn_; if (mousePosn) { var mapPosn = this.mapPosn_; var mapDiv = this.map_.getDiv(); return mousePosn.left > mapPosn.left && mousePosn.left < (mapPosn.left + mapDiv.offsetWidth) && mousePosn.top > mapPosn.top && mousePosn.top < (mapPosn.top + mapDiv.offsetHeight); } else { // if user never moved mouse return false; } }; /** * Show the veil if the hot key is down and the mouse is over the map, * otherwise hide the veil. */ DragZoom.prototype.setVeilVisibility_ = function () { var i; if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) { var mapDiv = this.map_.getDiv(); this.mapWidth_ = mapDiv.offsetWidth - (this.borderWidths_.left + this.borderWidths_.right); this.mapHeight_ = mapDiv.offsetHeight - (this.borderWidths_.top + this.borderWidths_.bottom); if (this.activatedByControl_) { // Veil covers entire map (except control) var left = parseInt(this.buttonDiv_.style.left, 10) + this.visualPositionOffset_.width; var top = parseInt(this.buttonDiv_.style.top, 10) + this.visualPositionOffset_.height; var width = this.visualSize_.width; var height = this.visualSize_.height; // Left veil rectangle: this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.width = left + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; // Right veil rectangle: this.veilDiv_[1].style.top = "0px"; this.veilDiv_[1].style.left = (left + width) + "px"; this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px"; this.veilDiv_[1].style.height = this.mapHeight_ + "px"; // Top veil rectangle: this.veilDiv_[2].style.top = "0px"; this.veilDiv_[2].style.left = left + "px"; this.veilDiv_[2].style.width = width + "px"; this.veilDiv_[2].style.height = top + "px"; // Bottom veil rectangle: this.veilDiv_[3].style.top = (top + height) + "px"; this.veilDiv_[3].style.left = left + "px"; this.veilDiv_[3].style.width = width + "px"; this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px"; for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "block"; } } else { this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.width = this.mapWidth_ + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; for (i = 1; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.width = "0px"; this.veilDiv_[i].style.height = "0px"; } for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "block"; } } } else { for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "none"; } } }; /** * Handle key down. Show the veil if the hot key has been pressed. * @param {Event} e The keyboard event. */ DragZoom.prototype.onKeyDown_ = function (e) { if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.hotKeyDown_ = true; this.activatedByControl_ = false; this.setVeilVisibility_(); /** * This event is fired when the hot key is pressed. * @name DragZoom#activate * @event */ google.maps.event.trigger(this, "activate"); } }; /** * Get the <code>google.maps.Point</code> of the mouse position. * @param {Event} e The mouse event. * @return {Point} The mouse position. */ DragZoom.prototype.getMousePoint_ = function (e) { var mousePosn = getMousePosition(e); var p = new google.maps.Point(); p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left; p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top; p.x = Math.min(p.x, this.mapWidth_); p.y = Math.min(p.y, this.mapHeight_); p.x = Math.max(p.x, 0); p.y = Math.max(p.y, 0); return p; }; /** * Handle mouse down. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseDown_ = function (e) { if (this.map_ && this.hotKeyDown_) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.dragging_ = true; this.startPt_ = this.endPt_ = this.getMousePoint_(e); this.boxDiv_.style.width = this.boxDiv_.style.height = "0px"; var prj = this.prjov_.getProjection(); var latlng = prj.fromContainerPixelToLatLng(this.startPt_); /** * This event is fired when the drag operation begins. * The parameter passed is the geographic position of the starting point. * @name DragZoom#dragstart * @param {LatLng} latlng The geographic position of the starting point. * @event */ google.maps.event.trigger(this, "dragstart", latlng); } }; /** * Handle mouse down at the document level. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseDownDocument_ = function (e) { this.mouseDown_ = true; }; /** * Handle mouse move. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseMove_ = function (e) { this.mousePosn_ = getMousePosition(e); if (this.dragging_) { this.endPt_ = this.getMousePoint_(e); var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); // For benefit of MSIE 7/8 ensure following values are not negative: var boxWidth = Math.max(0, width - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)); var boxHeight = Math.max(0, height - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)); // Left veil rectangle: this.veilDiv_[0].style.top = "0px"; this.veilDiv_[0].style.left = "0px"; this.veilDiv_[0].style.width = left + "px"; this.veilDiv_[0].style.height = this.mapHeight_ + "px"; // Right veil rectangle: this.veilDiv_[1].style.top = "0px"; this.veilDiv_[1].style.left = (left + width) + "px"; this.veilDiv_[1].style.width = (this.mapWidth_ - (left + width)) + "px"; this.veilDiv_[1].style.height = this.mapHeight_ + "px"; // Top veil rectangle: this.veilDiv_[2].style.top = "0px"; this.veilDiv_[2].style.left = left + "px"; this.veilDiv_[2].style.width = width + "px"; this.veilDiv_[2].style.height = top + "px"; // Bottom veil rectangle: this.veilDiv_[3].style.top = (top + height) + "px"; this.veilDiv_[3].style.left = left + "px"; this.veilDiv_[3].style.width = width + "px"; this.veilDiv_[3].style.height = (this.mapHeight_ - (top + height)) + "px"; // Selection rectangle: this.boxDiv_.style.top = top + "px"; this.boxDiv_.style.left = left + "px"; this.boxDiv_.style.width = boxWidth + "px"; this.boxDiv_.style.height = boxHeight + "px"; this.boxDiv_.style.display = "block"; /** * This event is fired repeatedly while the user drags a box across the area of interest. * The southwest and northeast point are passed as parameters of type <code>google.maps.Point</code> * (for performance reasons), relative to the map container. Also passed is the projection object * so that the event listener, if necessary, can convert the pixel positions to geographic * coordinates using <code>google.maps.MapCanvasProjection.fromContainerPixelToLatLng</code>. * @name DragZoom#drag * @param {Point} southwestPixel The southwest point of the selection area. * @param {Point} northeastPixel The northeast point of the selection area. * @param {MapCanvasProjection} prj The projection object. * @event */ google.maps.event.trigger(this, "drag", new google.maps.Point(left, top + height), new google.maps.Point(left + width, top), this.prjov_.getProjection()); } else if (!this.mouseDown_) { this.mapPosn_ = getElementPosition(this.map_.getDiv()); this.setVeilVisibility_(); } }; /** * Handle mouse up. * @param {Event} e The mouse event. */ DragZoom.prototype.onMouseUp_ = function (e) { var z; var me = this; this.mouseDown_ = false; if (this.dragging_) { if ((this.getMousePoint_(e).x === this.startPt_.x) && (this.getMousePoint_(e).y === this.startPt_.y)) { this.onKeyUp_(e); // Cancel event return; } var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); // Google Maps API bug: setCenter() doesn't work as expected if the map has a // border on the left or top. The code here includes a workaround for this problem. var kGoogleCenteringBug = true; if (kGoogleCenteringBug) { left += this.borderWidths_.left; top += this.borderWidths_.top; } var prj = this.prjov_.getProjection(); var sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height)); var ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top)); var bnds = new google.maps.LatLngBounds(sw, ne); if (this.noZoom_) { this.boxDiv_.style.display = "none"; } else { // Sometimes fitBounds causes a zoom OUT, so restore original zoom level if this happens. z = this.map_.getZoom(); this.map_.fitBounds(bnds); if (this.map_.getZoom() < z) { this.map_.setZoom(z); } // Redraw box after zoom: var swPt = prj.fromLatLngToContainerPixel(sw); var nePt = prj.fromLatLngToContainerPixel(ne); if (kGoogleCenteringBug) { swPt.x -= this.borderWidths_.left; swPt.y -= this.borderWidths_.top; nePt.x -= this.borderWidths_.left; nePt.y -= this.borderWidths_.top; } this.boxDiv_.style.left = swPt.x + "px"; this.boxDiv_.style.top = nePt.y + "px"; this.boxDiv_.style.width = (Math.abs(nePt.x - swPt.x) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right)) + "px"; this.boxDiv_.style.height = (Math.abs(nePt.y - swPt.y) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom)) + "px"; // Hide box asynchronously after 1 second: setTimeout(function () { me.boxDiv_.style.display = "none"; }, 1000); } this.dragging_ = false; this.onMouseMove_(e); // Updates the veil /** * This event is fired when the drag operation ends. * The parameter passed is the geographic bounds of the selected area. * Note that this event is <i>not</i> fired if the hot key is released before the drag operation ends. * @name DragZoom#dragend * @param {LatLngBounds} bnds The geographic bounds of the selected area. * @event */ google.maps.event.trigger(this, "dragend", bnds); // if the hot key isn't down, the drag zoom must have been activated by turning // on the visual control. In this case, finish up by simulating a key up event. if (!this.isHotKeyDown_(e)) { this.onKeyUp_(e); } } }; /** * Handle key up. * @param {Event} e The keyboard event. */ DragZoom.prototype.onKeyUp_ = function (e) { var i; var left, top, width, height, prj, sw, ne; var bnds = null; if (this.map_ && this.hotKeyDown_) { this.hotKeyDown_ = false; if (this.dragging_) { this.boxDiv_.style.display = "none"; this.dragging_ = false; // Calculate the bounds when drag zoom was cancelled left = Math.min(this.startPt_.x, this.endPt_.x); top = Math.min(this.startPt_.y, this.endPt_.y); width = Math.abs(this.startPt_.x - this.endPt_.x); height = Math.abs(this.startPt_.y - this.endPt_.y); prj = this.prjov_.getProjection(); sw = prj.fromContainerPixelToLatLng(new google.maps.Point(left, top + height)); ne = prj.fromContainerPixelToLatLng(new google.maps.Point(left + width, top)); bnds = new google.maps.LatLngBounds(sw, ne); } for (i = 0; i < this.veilDiv_.length; i++) { this.veilDiv_[i].style.display = "none"; } if (this.visualEnabled_) { this.buttonDiv_.firstChild.style.left = -(this.visualSize_.width * 2) + "px"; this.buttonDiv_.title = this.visualTips_.off; this.buttonDiv_.style.display = ""; } /** * This event is fired when the hot key is released. * The parameter passed is the geographic bounds of the selected area immediately * before the hot key was released. * @name DragZoom#deactivate * @param {LatLngBounds} bnds The geographic bounds of the selected area immediately * before the hot key was released. * @event */ google.maps.event.trigger(this, "deactivate", bnds); } }; /** * @name google.maps.Map * @class These are new methods added to the Google Maps JavaScript API V3's * <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Map">Map</a> * class. */ /** * Enables drag zoom. The user can zoom to an area of interest by holding down the hot key * <code>(shift | ctrl | alt )</code> while dragging a box around the area or by turning * on the visual control then dragging a box around the area. * @param {KeyDragZoomOptions} opt_zoomOpts The optional parameters. */ google.maps.Map.prototype.enableKeyDragZoom = function (opt_zoomOpts) { this.dragZoom_ = new DragZoom(this, opt_zoomOpts); }; /** * Disables drag zoom. */ google.maps.Map.prototype.disableKeyDragZoom = function () { var i; var d = this.dragZoom_; if (d) { for (i = 0; i < d.listeners_.length; ++i) { google.maps.event.removeListener(d.listeners_[i]); } this.getDiv().removeChild(d.boxDiv_); for (i = 0; i < d.veilDiv_.length; i++) { this.getDiv().removeChild(d.veilDiv_[i]); } if (d.visualEnabled_) { // Remove the custom control: this.controls[d.visualPosition_].removeAt(d.controlIndex_); } d.prjov_.setMap(null); this.dragZoom_ = null; } }; /** * Returns <code>true</code> if the drag zoom feature has been enabled. * @return {boolean} */ google.maps.Map.prototype.keyDragZoomEnabled = function () { return this.dragZoom_ !== null; }; /** * Returns the DragZoom object which is created when <code>google.maps.Map.enableKeyDragZoom</code> is called. * With this object you can use <code>google.maps.event.addListener</code> to attach event listeners * for the "activate", "deactivate", "dragstart", "drag", and "dragend" events. * @return {DragZoom} */ google.maps.Map.prototype.getDragZoomObject = function () { return this.dragZoom_; }; })(); /** * @name MarkerClustererPlus for Google Maps V3 * @version 2.1.1 [November 4, 2013] * @author Gary Little * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of markers. * <p> * This is an enhanced V3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/" * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little. * <p> * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>, * and <code>calculator</code> properties as well as support for four more events. It also allows * greater control over the styling of the text that appears on the cluster marker. The * documentation has been significantly improved and the overall code has been simplified and * polished. Very large numbers of markers can now be managed without causing Javascript timeout * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been * deprecated. The new name is <code>click</code>, so please change your application code now. */ /** * 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. */ /** * @name ClusterIconStyle * @class This class represents the object for values in the <code>styles</code> array passed * to the {@link MarkerClusterer} constructor. The element in this array that is used to * style the cluster icon is determined by calling the <code>calculator</code> function. * * @property {string} url The URL of the cluster icon image file. Required. * @property {number} height The display height (in pixels) of the cluster icon. Required. * @property {number} width The display width (in pixels) of the cluster icon. Required. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code> * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code> * increases to the right of center. The default is <code>[0, 0]</code>. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the * spot on the cluster icon that is to be aligned with the cluster position. The format is * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default * anchor position is the center of the cluster icon. * @property {string} [textColor="black"] The color of the label text shown on the * cluster icon. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the * cluster icon. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code> * property for the label text shown on the cluster icon. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code> * property for the label text shown on the cluster icon. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code> * property for the label text shown on the cluster icon. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code> * property for the label text shown on the cluster icon. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code> * (the same format as for the CSS <code>background-position</code> property). You must set * this property appropriately when the image defined by <code>url</code> represents a sprite * containing multiple images. Note that the position <i>must</i> be specified in px units. */ /** * @name ClusterIconInfo * @class This class is an object containing general information about a cluster icon. This is * the object that a <code>calculator</code> function returns. * * @property {string} text The text of the label to be shown on the cluster icon. * @property {number} index The index plus 1 of the element in the <code>styles</code> * array to be used to style the cluster icon. * @property {string} title The tooltip to display when the mouse moves over the cluster icon. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the * value of the <code>title</code> property passed to the MarkerClusterer. */ /** * A cluster icon. * * @constructor * @extends google.maps.OverlayView * @param {Cluster} cluster The cluster with which the icon is to be associated. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. * @private */ function ClusterIcon(cluster, styles) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.cluster_ = cluster; this.className_ = cluster.getMarkerClusterer().getClusterClass(); this.styles_ = styles; this.center_ = null; this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(cluster.getMap()); // Note: this causes onAdd to be called } /** * Adds the icon to the DOM. */ ClusterIcon.prototype.onAdd = function () { var cClusterIcon = this; var cMouseDownInCluster; var cDraggingMapByCluster; this.div_ = document.createElement("div"); this.div_.className = this.className_; if (this.visible_) { this.show(); } this.getPanes().overlayMouseTarget.appendChild(this.div_); // Fix for Issue 157 this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () { cDraggingMapByCluster = cMouseDownInCluster; }); google.maps.event.addDomListener(this.div_, "mousedown", function () { cMouseDownInCluster = true; cDraggingMapByCluster = false; }); google.maps.event.addDomListener(this.div_, "click", function (e) { cMouseDownInCluster = false; if (!cDraggingMapByCluster) { var theBounds; var mz; var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when a cluster marker is clicked. * @name MarkerClusterer#click * @param {Cluster} c The cluster that was clicked. * @event */ google.maps.event.trigger(mc, "click", cClusterIcon.cluster_); google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name // The default click handler follows. Disable it by setting // the zoomOnClick property to false. if (mc.getZoomOnClick()) { // Zoom into the cluster. mz = mc.getMaxZoom(); theBounds = cClusterIcon.cluster_.getBounds(); mc.getMap().fitBounds(theBounds); // There is a fix for Issue 170 here: setTimeout(function () { mc.getMap().fitBounds(theBounds); // Don't zoom beyond the max zoom level if (mz !== null && (mc.getMap().getZoom() > mz)) { mc.getMap().setZoom(mz + 1); } }, 100); } // Prevent event propagation to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }); google.maps.event.addDomListener(this.div_, "mouseover", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves over a cluster marker. * @name MarkerClusterer#mouseover * @param {Cluster} c The cluster that the mouse moved over. * @event */ google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_); }); google.maps.event.addDomListener(this.div_, "mouseout", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves out of a cluster marker. * @name MarkerClusterer#mouseout * @param {Cluster} c The cluster that the mouse moved out of. * @event */ google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_); }); }; /** * Removes the icon from the DOM. */ ClusterIcon.prototype.onRemove = function () { if (this.div_ && this.div_.parentNode) { this.hide(); google.maps.event.removeListener(this.boundsChangedListener_); google.maps.event.clearInstanceListeners(this.div_); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the icon. */ ClusterIcon.prototype.draw = function () { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + "px"; this.div_.style.left = pos.x + "px"; } }; /** * Hides the icon. */ ClusterIcon.prototype.hide = function () { if (this.div_) { this.div_.style.display = "none"; } this.visible_ = false; }; /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; /** * Sets the icon styles to the appropriate element in the styles array. * * @param {ClusterIconInfo} sums The icon label text and styles index. */ ClusterIcon.prototype.useStyle = function (sums) { this.sums_ = sums; var index = Math.max(0, sums.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style.url; this.height_ = style.height; this.width_ = style.width; this.anchorText_ = style.anchorText || [0, 0]; this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)]; this.textColor_ = style.textColor || "black"; this.textSize_ = style.textSize || 11; this.textDecoration_ = style.textDecoration || "none"; this.fontWeight_ = style.fontWeight || "bold"; this.fontStyle_ = style.fontStyle || "normal"; this.fontFamily_ = style.fontFamily || "Arial,sans-serif"; this.backgroundPosition_ = style.backgroundPosition || "0 0"; }; /** * Sets the position at which to center the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function (center) { this.center_ = center; }; /** * Creates the cssText style parameter based on the position of the icon. * * @param {google.maps.Point} pos The position of the icon. * @return {string} The CSS style text. */ ClusterIcon.prototype.createCss = function (pos) { var style = []; style.push("cursor: pointer;"); style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;"); style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;"); return style.join(""); }; /** * Returns the position at which to place the DIV depending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. */ ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= this.anchorIcon_[1]; pos.y -= this.anchorIcon_[0]; pos.x = parseInt(pos.x, 10); pos.y = parseInt(pos.y, 10); return pos; }; /** * Creates a single cluster that manages a group of proximate markers. * Used internally, do not call this constructor directly. * @constructor * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this * cluster is associated. */ function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); } /** * Returns the number of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {number} The number of markers in the cluster. */ Cluster.prototype.getSize = function () { return this.markers_.length; }; /** * Returns the array of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {Array} The array of markers in the cluster. */ Cluster.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the center of the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {google.maps.LatLng} The center of the cluster. */ Cluster.prototype.getCenter = function () { return this.center_; }; /** * Returns the map with which the cluster is associated. * * @return {google.maps.Map} The map. * @ignore */ Cluster.prototype.getMap = function () { return this.map_; }; /** * Returns the <code>MarkerClusterer</code> object with which the cluster is associated. * * @return {MarkerClusterer} The associated marker clusterer. * @ignore */ Cluster.prototype.getMarkerClusterer = function () { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ Cluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ Cluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = []; delete this.markers_; }; /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ Cluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. for (i = 0; i < mCount; i++) { this.markers_[i].setMap(null); } } else { marker.setMap(null); } this.updateIcon_(); return true; }; /** * Determines if a marker lies within the cluster's bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. * @ignore */ Cluster.prototype.isMarkerInClusterBounds = function (marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Calculates the extended bounds of the cluster with the grid. */ Cluster.prototype.calculateBounds_ = function () { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Updates the cluster icon. */ Cluster.prototype.updateIcon_ = function () { var mCount = this.markers_.length; var mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { this.clusterIcon_.hide(); return; } if (mCount < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.useStyle(sums); this.clusterIcon_.show(); }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) { var i; if (this.markers_.indexOf) { return this.markers_.indexOf(marker) !== -1; } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { return true; } } } return false; }; /** * @name MarkerClustererOptions * @class This class represents the optional parameter passed to * the {@link MarkerClusterer} constructor. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or * <code>null</code> if clustering is to be enabled at all zoom levels. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is * clicked. You may want to set this to <code>false</code> if you have installed a handler * for the <code>click</code> event and it deals with zooming on its own. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be * the average position of all markers in the cluster. If set to <code>false</code>, the * cluster marker is positioned at the location of the first marker added to the cluster. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster * before the markers are hidden and a cluster marker appears. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You * may want to set this to <code>true</code> to ensure that hidden markers are not included * in the marker count that appears on a cluster marker (this count is the value of the * <code>text</code> property of the result returned by the default <code>calculator</code>). * If set to <code>true</code> and you change the visibility of a marker being clustered, be * sure to also call <code>MarkerClusterer.repaint()</code>. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a * different tooltip for each cluster marker.) * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine * the text to be displayed on a cluster marker and the index indicating which style to use * for the cluster marker. The input parameters for the function are (1) the array of markers * represented by a cluster marker and (2) the number of cluster icon styles. It returns a * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a * <code>text</code> property which is the number of markers in the cluster and an * <code>index</code> property which is one higher than the lowest integer such that * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles * array, whichever is less. The <code>styles</code> array element used has an index of * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code> * for a cluster icon representing 125 markers so the element used in the <code>styles</code> * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code> * property that contains the text of the tooltip to be used for the cluster marker. If * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code> * property for the MarkerClusterer. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles * for the cluster markers. Use this class to define CSS styles that are not set up by the code * that processes the <code>styles</code> array. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles * of the cluster markers to be used. The element to be used to style a given cluster marker * is determined by the function defined by the <code>calculator</code> property. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived * from the values for <code>imagePath</code>, <code>imageExtension</code>, and * <code>imageSizes</code>. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that * have sizes that are some multiple (typically double) of their actual display size. Icons such * as these look better when viewed on high-resolution monitors such as Apple's Retina displays. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the * number of markers to be processed in a single batch when using a browser other than * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead). * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is * being used, markers are processed in several batches with a small delay inserted between * each batch in an attempt to avoid Javascript timeout errors. Set this property to the * number of markers to be processed in a single batch; select as high a number as you can * without causing a timeout error in the browser. This number might need to be as low as 100 * if 15,000 markers are being managed, for example. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH] * The full URL of the root name of the group of image files to use for cluster icons. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code> * where n is the image file number (1, 2, etc.). * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION] * The extension name for the cluster icon image files (e.g., <code>"png"</code> or * <code>"jpg"</code>). * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES] * An array of numbers containing the widths of the group of * <code>imagePath</code>n.<code>imageExtension</code> image files. * (The images are assumed to be square.) */ /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. * @constructor * @extends google.maps.OverlayView * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster. * @param {MarkerClustererOptions} [opt_options] The optional parameters. */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); opt_markers = opt_markers || []; opt_options = opt_options || {}; this.markers_ = []; this.clusters_ = []; this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; this.gridSize_ = opt_options.gridSize || 60; this.minClusterSize_ = opt_options.minimumClusterSize || 2; this.maxZoom_ = opt_options.maxZoom || null; this.styles_ = opt_options.styles || []; this.title_ = opt_options.title || ""; this.zoomOnClick_ = true; if (opt_options.zoomOnClick !== undefined) { this.zoomOnClick_ = opt_options.zoomOnClick; } this.averageCenter_ = false; if (opt_options.averageCenter !== undefined) { this.averageCenter_ = opt_options.averageCenter; } this.ignoreHidden_ = false; if (opt_options.ignoreHidden !== undefined) { this.ignoreHidden_ = opt_options.ignoreHidden; } this.enableRetinaIcons_ = false; if (opt_options.enableRetinaIcons !== undefined) { this.enableRetinaIcons_ = opt_options.enableRetinaIcons; } this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH; this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION; this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES; this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR; this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE; this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE; this.clusterClass_ = opt_options.clusterClass || "cluster"; if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize_ = this.batchSizeIE_; } this.setupStyles_(); this.addMarkers(opt_markers, true); this.setMap(map); // Note: this causes onAdd to be called } /** * Implementation of the onAdd interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function () { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }), google.maps.event.addListener(this.getMap(), "idle", function () { cMarkerClusterer.redraw_(); }) ]; }; /** * Implementation of the onRemove interface method. * Removes map event listeners and all cluster icons from the DOM. * All managed markers are also put back on the map. * @ignore */ MarkerClusterer.prototype.onRemove = function () { var i; // Put all the managed markers back on the map: for (i = 0; i < this.markers_.length; i++) { if (this.markers_[i].getMap() !== this.activeMap_) { this.markers_[i].setMap(this.activeMap_); } } // Remove all clusters: for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Remove map event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; }; /** * Implementation of the draw interface method. * @ignore */ MarkerClusterer.prototype.draw = function () {}; /** * Sets up the styles object. */ MarkerClusterer.prototype.setupStyles_ = function () { var i, size; if (this.styles_.length > 0) { return; } for (i = 0; i < this.imageSizes_.length; i++) { size = this.imageSizes_[i]; this.styles_.push({ url: this.imagePath_ + (i + 1) + "." + this.imageExtension_, height: size, width: size }); } }; /** * Fits the map to the bounds of the markers managed by the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function () { var i; var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } this.getMap().fitBounds(bounds); }; /** * Returns the value of the <code>gridSize</code> property. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function () { return this.gridSize_; }; /** * Sets the value of the <code>gridSize</code> property. * * @param {number} gridSize The grid size. */ MarkerClusterer.prototype.setGridSize = function (gridSize) { this.gridSize_ = gridSize; }; /** * Returns the value of the <code>minimumClusterSize</code> property. * * @return {number} The minimum cluster size. */ MarkerClusterer.prototype.getMinimumClusterSize = function () { return this.minClusterSize_; }; /** * Sets the value of the <code>minimumClusterSize</code> property. * * @param {number} minimumClusterSize The minimum cluster size. */ MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) { this.minClusterSize_ = minimumClusterSize; }; /** * Returns the value of the <code>maxZoom</code> property. * * @return {number} The maximum zoom level. */ MarkerClusterer.prototype.getMaxZoom = function () { return this.maxZoom_; }; /** * Sets the value of the <code>maxZoom</code> property. * * @param {number} maxZoom The maximum zoom level. */ MarkerClusterer.prototype.setMaxZoom = function (maxZoom) { this.maxZoom_ = maxZoom; }; /** * Returns the value of the <code>styles</code> property. * * @return {Array} The array of styles defining the cluster markers to be used. */ MarkerClusterer.prototype.getStyles = function () { return this.styles_; }; /** * Sets the value of the <code>styles</code> property. * * @param {Array.<ClusterIconStyle>} styles The array of styles to use. */ MarkerClusterer.prototype.setStyles = function (styles) { this.styles_ = styles; }; /** * Returns the value of the <code>title</code> property. * * @return {string} The content of the title text. */ MarkerClusterer.prototype.getTitle = function () { return this.title_; }; /** * Sets the value of the <code>title</code> property. * * @param {string} title The value of the title property. */ MarkerClusterer.prototype.setTitle = function (title) { this.title_ = title; }; /** * Returns the value of the <code>zoomOnClick</code> property. * * @return {boolean} True if zoomOnClick property is set. */ MarkerClusterer.prototype.getZoomOnClick = function () { return this.zoomOnClick_; }; /** * Sets the value of the <code>zoomOnClick</code> property. * * @param {boolean} zoomOnClick The value of the zoomOnClick property. */ MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) { this.zoomOnClick_ = zoomOnClick; }; /** * Returns the value of the <code>averageCenter</code> property. * * @return {boolean} True if averageCenter property is set. */ MarkerClusterer.prototype.getAverageCenter = function () { return this.averageCenter_; }; /** * Sets the value of the <code>averageCenter</code> property. * * @param {boolean} averageCenter The value of the averageCenter property. */ MarkerClusterer.prototype.setAverageCenter = function (averageCenter) { this.averageCenter_ = averageCenter; }; /** * Returns the value of the <code>ignoreHidden</code> property. * * @return {boolean} True if ignoreHidden property is set. */ MarkerClusterer.prototype.getIgnoreHidden = function () { return this.ignoreHidden_; }; /** * Sets the value of the <code>ignoreHidden</code> property. * * @param {boolean} ignoreHidden The value of the ignoreHidden property. */ MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) { this.ignoreHidden_ = ignoreHidden; }; /** * Returns the value of the <code>enableRetinaIcons</code> property. * * @return {boolean} True if enableRetinaIcons property is set. */ MarkerClusterer.prototype.getEnableRetinaIcons = function () { return this.enableRetinaIcons_; }; /** * Sets the value of the <code>enableRetinaIcons</code> property. * * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property. */ MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) { this.enableRetinaIcons_ = enableRetinaIcons; }; /** * Returns the value of the <code>imageExtension</code> property. * * @return {string} The value of the imageExtension property. */ MarkerClusterer.prototype.getImageExtension = function () { return this.imageExtension_; }; /** * Sets the value of the <code>imageExtension</code> property. * * @param {string} imageExtension The value of the imageExtension property. */ MarkerClusterer.prototype.setImageExtension = function (imageExtension) { this.imageExtension_ = imageExtension; }; /** * Returns the value of the <code>imagePath</code> property. * * @return {string} The value of the imagePath property. */ MarkerClusterer.prototype.getImagePath = function () { return this.imagePath_; }; /** * Sets the value of the <code>imagePath</code> property. * * @param {string} imagePath The value of the imagePath property. */ MarkerClusterer.prototype.setImagePath = function (imagePath) { this.imagePath_ = imagePath; }; /** * Returns the value of the <code>imageSizes</code> property. * * @return {Array} The value of the imageSizes property. */ MarkerClusterer.prototype.getImageSizes = function () { return this.imageSizes_; }; /** * Sets the value of the <code>imageSizes</code> property. * * @param {Array} imageSizes The value of the imageSizes property. */ MarkerClusterer.prototype.setImageSizes = function (imageSizes) { this.imageSizes_ = imageSizes; }; /** * Returns the value of the <code>calculator</code> property. * * @return {function} the value of the calculator property. */ MarkerClusterer.prototype.getCalculator = function () { return this.calculator_; }; /** * Sets the value of the <code>calculator</code> property. * * @param {function(Array.<google.maps.Marker>, number)} calculator The value * of the calculator property. */ MarkerClusterer.prototype.setCalculator = function (calculator) { this.calculator_ = calculator; }; /** * Returns the value of the <code>batchSizeIE</code> property. * * @return {number} the value of the batchSizeIE property. */ MarkerClusterer.prototype.getBatchSizeIE = function () { return this.batchSizeIE_; }; /** * Sets the value of the <code>batchSizeIE</code> property. * * @param {number} batchSizeIE The value of the batchSizeIE property. */ MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) { this.batchSizeIE_ = batchSizeIE; }; /** * Returns the value of the <code>clusterClass</code> property. * * @return {string} the value of the clusterClass property. */ MarkerClusterer.prototype.getClusterClass = function () { return this.clusterClass_; }; /** * Sets the value of the <code>clusterClass</code> property. * * @param {string} clusterClass The value of the clusterClass property. */ MarkerClusterer.prototype.setClusterClass = function (clusterClass) { this.clusterClass_ = clusterClass; }; /** * Returns the array of markers managed by the clusterer. * * @return {Array} The array of markers managed by the clusterer. */ MarkerClusterer.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the number of markers managed by the clusterer. * * @return {number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function () { return this.markers_.length; }; /** * Returns the current array of clusters formed by the clusterer. * * @return {Array} The array of clusters formed by the clusterer. */ MarkerClusterer.prototype.getClusters = function () { return this.clusters_; }; /** * Returns the number of clusters formed by the clusterer. * * @return {number} The number of clusters formed by the clusterer. */ MarkerClusterer.prototype.getTotalClusters = function () { return this.clusters_.length; }; /** * Adds a marker to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw_(); } }; /** * Adds an array of markers to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {Array.<google.maps.Marker>} markers The markers to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) { var key; for (key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo_(markers[key]); } } if (!opt_nodraw) { this.redraw_(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.pushMarkerTo_ = function (marker) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { var cMarkerClusterer = this; google.maps.event.addListener(marker, "dragend", function () { if (cMarkerClusterer.ready_) { this.isAdded = false; cMarkerClusterer.repaint(); } }); } marker.isAdded = false; this.markers_.push(marker); }; /** * Removes a marker from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the * marker was removed from the clusterer. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if the marker was removed from the clusterer. */ MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes an array of markers from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers * were removed from the clusterer. * * @param {Array.<google.maps.Marker>} markers The markers to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if markers were removed from the clusterer. */ MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) { var i, r; var removed = false; for (i = 0; i < markers.length; i++) { r = this.removeMarker_(markers[i]); removed = removed || r; } if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ MarkerClusterer.prototype.removeMarker_ = function (marker) { var i; var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { index = i; break; } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false; } marker.setMap(null); this.markers_.splice(index, 1); // Remove the marker from the list of managed markers return true; }; /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ MarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = []; }; /** * Recalculates and redraws all the marker clusters from scratch. * Call this after changing any properties. */ MarkerClusterer.prototype.repaint = function () { var oldClusters = this.clusters_.slice(); this.clusters_ = []; this.resetViewport_(false); this.redraw_(); // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function () { var i; for (i = 0; i < oldClusters.length; i++) { oldClusters[i].remove(); } }, 0); }; /** * Returns the current bounds extended by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. * @ignore */ MarkerClusterer.prototype.getExtendedBounds = function (bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Redraws all the clusters. */ MarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ MarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. for (i = 0; i < this.markers_.length; i++) { marker = this.markers_[i]; marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } }; /** * Calculates the distance between two latlng locations in km. * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @see http://www.movable-type.co.uk/scripts/latlong.html */ MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) { var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Determines if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. */ MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ MarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * The default function for determining the label text and style * for a cluster icon. * * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster. * @param {number} numStyles The number of marker styles available. * @return {ClusterIconInfo} The information resource for the cluster. * @constant * @ignore */ MarkerClusterer.CALCULATOR = function (markers, numStyles) { var index = 0; var title = ""; var count = markers.length.toString(); var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index, title: title }; }; /** * The number of markers to process in one batch. * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE = 2000; /** * The number of markers to process in one batch (IE only). * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE_IE = 500; /** * The default root name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m"; /** * The default extension name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_EXTENSION = "png"; /** * The default array of sizes for the marker cluster images. * * @type {Array.<number>} * @constant */ MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90]; /** * @name MarkerWithLabel for V3 * @version 1.1.10 [April 8, 2014] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * 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. */ /*jslint browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. * @private */ function inherits(childCtor, parentCtor) { /* @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /* @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; this.labelDiv_.parentNode.removeChild(this.labelDiv_); this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.innerHTML = ""; // Remove current content this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); }; //END REPLACE window.InfoBox = InfoBox; window.Cluster = Cluster; window.ClusterIcon = ClusterIcon; window.MarkerClusterer = MarkerClusterer; window.MarkerLabel_ = MarkerLabel_; window.MarkerWithLabel = MarkerWithLabel; }) }; }); ;/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { angular.module('uiGmapgoogle-maps.wrapped') .service('uiGmapDataStructures', function() { return { Graph: __webpack_require__(1).Graph, Queue: __webpack_require__(1).Queue }; }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { (function() { module.exports = { Graph: __webpack_require__(2), Heap: __webpack_require__(3), LinkedList: __webpack_require__(4), Map: __webpack_require__(5), Queue: __webpack_require__(6), RedBlackTree: __webpack_require__(7), Trie: __webpack_require__(8) }; }).call(this); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* Graph implemented as a modified incidence list. O(1) for every typical operation except `removeNode()` at O(E) where E is the number of edges. ## Overview example: ```js var graph = new Graph; graph.addNode('A'); // => a node object. For more info, log the output or check // the documentation for addNode graph.addNode('B'); graph.addNode('C'); graph.addEdge('A', 'C'); // => an edge object graph.addEdge('A', 'B'); graph.getEdge('B', 'A'); // => undefined. Directed edge! graph.getEdge('A', 'B'); // => the edge object previously added graph.getEdge('A', 'B').weight = 2 // weight is the only built-in handy property // of an edge object. Feel free to attach // other properties graph.getInEdgesOf('B'); // => array of edge objects, in this case only one; // connecting A to B graph.getOutEdgesOf('A'); // => array of edge objects, one to B and one to C graph.getAllEdgesOf('A'); // => all the in and out edges. Edge directed toward // the node itself are only counted once forEachNode(function(nodeObject) { console.log(node); }); forEachEdge(function(edgeObject) { console.log(edgeObject); }); graph.removeNode('C'); // => 'C'. The edge between A and C also removed graph.removeEdge('A', 'B'); // => the edge object removed ``` ## Properties: - nodeSize: total number of nodes. - edgeSize: total number of edges. */ (function() { var Graph, __hasProp = {}.hasOwnProperty; Graph = (function() { function Graph() { this._nodes = {}; this.nodeSize = 0; this.edgeSize = 0; } Graph.prototype.addNode = function(id) { /* The `id` is a unique identifier for the node, and should **not** change after it's added. It will be used for adding, retrieving and deleting related edges too. **Note** that, internally, the ids are kept in an object. JavaScript's object hashes the id `'2'` and `2` to the same key, so please stick to a simple id data type such as number or string. _Returns:_ the node object. Feel free to attach additional custom properties on it for graph algorithms' needs. **Undefined if node id already exists**, as to avoid accidental overrides. */ if (!this._nodes[id]) { this.nodeSize++; return this._nodes[id] = { _outEdges: {}, _inEdges: {} }; } }; Graph.prototype.getNode = function(id) { /* _Returns:_ the node object. Feel free to attach additional custom properties on it for graph algorithms' needs. */ return this._nodes[id]; }; Graph.prototype.removeNode = function(id) { /* _Returns:_ the node object removed, or undefined if it didn't exist in the first place. */ var inEdgeId, nodeToRemove, outEdgeId, _ref, _ref1; nodeToRemove = this._nodes[id]; if (!nodeToRemove) { return; } else { _ref = nodeToRemove._outEdges; for (outEdgeId in _ref) { if (!__hasProp.call(_ref, outEdgeId)) continue; this.removeEdge(id, outEdgeId); } _ref1 = nodeToRemove._inEdges; for (inEdgeId in _ref1) { if (!__hasProp.call(_ref1, inEdgeId)) continue; this.removeEdge(inEdgeId, id); } this.nodeSize--; delete this._nodes[id]; } return nodeToRemove; }; Graph.prototype.addEdge = function(fromId, toId, weight) { var edgeToAdd, fromNode, toNode; if (weight == null) { weight = 1; } /* `fromId` and `toId` are the node id specified when it was created using `addNode()`. `weight` is optional and defaults to 1. Ignoring it effectively makes this an unweighted graph. Under the hood, `weight` is just a normal property of the edge object. _Returns:_ the edge object created. Feel free to attach additional custom properties on it for graph algorithms' needs. **Or undefined** if the nodes of id `fromId` or `toId` aren't found, or if an edge already exists between the two nodes. */ if (this.getEdge(fromId, toId)) { return; } fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; if (!fromNode || !toNode) { return; } edgeToAdd = { weight: weight }; fromNode._outEdges[toId] = edgeToAdd; toNode._inEdges[fromId] = edgeToAdd; this.edgeSize++; return edgeToAdd; }; Graph.prototype.getEdge = function(fromId, toId) { /* _Returns:_ the edge object, or undefined if the nodes of id `fromId` or `toId` aren't found. */ var fromNode, toNode; fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; if (!fromNode || !toNode) { } else { return fromNode._outEdges[toId]; } }; Graph.prototype.removeEdge = function(fromId, toId) { /* _Returns:_ the edge object removed, or undefined of edge wasn't found. */ var edgeToDelete, fromNode, toNode; fromNode = this._nodes[fromId]; toNode = this._nodes[toId]; edgeToDelete = this.getEdge(fromId, toId); if (!edgeToDelete) { return; } delete fromNode._outEdges[toId]; delete toNode._inEdges[fromId]; this.edgeSize--; return edgeToDelete; }; Graph.prototype.getInEdgesOf = function(nodeId) { /* _Returns:_ an array of edge objects that are directed toward the node, or empty array if no such edge or node exists. */ var fromId, inEdges, toNode, _ref; toNode = this._nodes[nodeId]; inEdges = []; _ref = toNode != null ? toNode._inEdges : void 0; for (fromId in _ref) { if (!__hasProp.call(_ref, fromId)) continue; inEdges.push(this.getEdge(fromId, nodeId)); } return inEdges; }; Graph.prototype.getOutEdgesOf = function(nodeId) { /* _Returns:_ an array of edge objects that go out of the node, or empty array if no such edge or node exists. */ var fromNode, outEdges, toId, _ref; fromNode = this._nodes[nodeId]; outEdges = []; _ref = fromNode != null ? fromNode._outEdges : void 0; for (toId in _ref) { if (!__hasProp.call(_ref, toId)) continue; outEdges.push(this.getEdge(nodeId, toId)); } return outEdges; }; Graph.prototype.getAllEdgesOf = function(nodeId) { /* **Note:** not the same as concatenating `getInEdgesOf()` and `getOutEdgesOf()`. Some nodes might have an edge pointing toward itself. This method solves that duplication. _Returns:_ an array of edge objects linked to the node, no matter if they're outgoing or coming. Duplicate edge created by self-pointing nodes are removed. Only one copy stays. Empty array if node has no edge. */ var i, inEdges, outEdges, selfEdge, _i, _ref, _ref1; inEdges = this.getInEdgesOf(nodeId); outEdges = this.getOutEdgesOf(nodeId); if (inEdges.length === 0) { return outEdges; } selfEdge = this.getEdge(nodeId, nodeId); for (i = _i = 0, _ref = inEdges.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { if (inEdges[i] === selfEdge) { _ref1 = [inEdges[inEdges.length - 1], inEdges[i]], inEdges[i] = _ref1[0], inEdges[inEdges.length - 1] = _ref1[1]; inEdges.pop(); break; } } return inEdges.concat(outEdges); }; Graph.prototype.forEachNode = function(operation) { /* Traverse through the graph in an arbitrary manner, visiting each node once. Pass a function of the form `fn(nodeObject, nodeId)`. _Returns:_ undefined. */ var nodeId, nodeObject, _ref; _ref = this._nodes; for (nodeId in _ref) { if (!__hasProp.call(_ref, nodeId)) continue; nodeObject = _ref[nodeId]; operation(nodeObject, nodeId); } }; Graph.prototype.forEachEdge = function(operation) { /* Traverse through the graph in an arbitrary manner, visiting each edge once. Pass a function of the form `fn(edgeObject)`. _Returns:_ undefined. */ var edgeObject, nodeId, nodeObject, toId, _ref, _ref1; _ref = this._nodes; for (nodeId in _ref) { if (!__hasProp.call(_ref, nodeId)) continue; nodeObject = _ref[nodeId]; _ref1 = nodeObject._outEdges; for (toId in _ref1) { if (!__hasProp.call(_ref1, toId)) continue; edgeObject = _ref1[toId]; operation(edgeObject); } } }; return Graph; })(); module.exports = Graph; }).call(this); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* Minimum heap, i.e. smallest node at root. **Note:** does not accept null or undefined. This is by design. Those values cause comparison problems and might report false negative during extraction. ## Overview example: ```js var heap = new Heap([5, 6, 3, 4]); heap.add(10); // => 10 heap.removeMin(); // => 3 heap.peekMin(); // => 4 ``` ## Properties: - size: total number of items. */ (function() { var Heap, _leftChild, _parent, _rightChild; Heap = (function() { function Heap(dataToHeapify) { var i, item, _i, _j, _len, _ref; if (dataToHeapify == null) { dataToHeapify = []; } /* Pass an optional array to be heapified. Takes only O(n) time. */ this._data = [void 0]; for (_i = 0, _len = dataToHeapify.length; _i < _len; _i++) { item = dataToHeapify[_i]; if (item != null) { this._data.push(item); } } if (this._data.length > 1) { for (i = _j = 2, _ref = this._data.length; 2 <= _ref ? _j < _ref : _j > _ref; i = 2 <= _ref ? ++_j : --_j) { this._upHeap(i); } } this.size = this._data.length - 1; } Heap.prototype.add = function(value) { /* **Remember:** rejects null and undefined for mentioned reasons. _Returns:_ the value added. */ if (value == null) { return; } this._data.push(value); this._upHeap(this._data.length - 1); this.size++; return value; }; Heap.prototype.removeMin = function() { /* _Returns:_ the smallest item (the root). */ var min; if (this._data.length === 1) { return; } this.size--; if (this._data.length === 2) { return this._data.pop(); } min = this._data[1]; this._data[1] = this._data.pop(); this._downHeap(); return min; }; Heap.prototype.peekMin = function() { /* Check the smallest item without removing it. _Returns:_ the smallest item (the root). */ return this._data[1]; }; Heap.prototype._upHeap = function(index) { var valueHolder, _ref; valueHolder = this._data[index]; while (this._data[index] < this._data[_parent(index)] && index > 1) { _ref = [this._data[_parent(index)], this._data[index]], this._data[index] = _ref[0], this._data[_parent(index)] = _ref[1]; index = _parent(index); } }; Heap.prototype._downHeap = function() { var currentIndex, smallerChildIndex, _ref; currentIndex = 1; while (_leftChild(currentIndex < this._data.length)) { smallerChildIndex = _leftChild(currentIndex); if (smallerChildIndex < this._data.length - 1) { if (this._data[_rightChild(currentIndex)] < this._data[smallerChildIndex]) { smallerChildIndex = _rightChild(currentIndex); } } if (this._data[smallerChildIndex] < this._data[currentIndex]) { _ref = [this._data[currentIndex], this._data[smallerChildIndex]], this._data[smallerChildIndex] = _ref[0], this._data[currentIndex] = _ref[1]; currentIndex = smallerChildIndex; } else { break; } } }; return Heap; })(); _parent = function(index) { return index >> 1; }; _leftChild = function(index) { return index << 1; }; _rightChild = function(index) { return (index << 1) + 1; }; module.exports = Heap; }).call(this); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* Doubly Linked. ## Overview example: ```js var list = new LinkedList([5, 4, 9]); list.add(12); // => 12 list.head.next.value; // => 4 list.tail.value; // => 12 list.at(-1); // => 12 list.removeAt(2); // => 9 list.remove(4); // => 4 list.indexOf(5); // => 0 list.add(5, 1); // => 5. Second 5 at position 1. list.indexOf(5, 1); // => 1 ``` ## Properties: - head: first item. - tail: last item. - size: total number of items. - item.value: value passed to the item when calling `add()`. - item.prev: previous item. - item.next: next item. */ (function() { var LinkedList; LinkedList = (function() { function LinkedList(valuesToAdd) { var value, _i, _len; if (valuesToAdd == null) { valuesToAdd = []; } /* Can pass an array of elements to link together during `new LinkedList()` initiation. */ this.head = { prev: void 0, value: void 0, next: void 0 }; this.tail = { prev: void 0, value: void 0, next: void 0 }; this.size = 0; for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) { value = valuesToAdd[_i]; this.add(value); } } LinkedList.prototype.at = function(position) { /* Get the item at `position` (optional). Accepts negative index: ```js myList.at(-1); // Returns the last element. ``` However, passing a negative index that surpasses the boundary will return undefined: ```js myList = new LinkedList([2, 6, 8, 3]) myList.at(-5); // Undefined. myList.at(-4); // 2. ``` _Returns:_ item gotten, or undefined if not found. */ var currentNode, i, _i, _j, _ref; if (!((-this.size <= position && position < this.size))) { return; } position = this._adjust(position); if (position * 2 < this.size) { currentNode = this.head; for (i = _i = 1; _i <= position; i = _i += 1) { currentNode = currentNode.next; } } else { currentNode = this.tail; for (i = _j = 1, _ref = this.size - position - 1; _j <= _ref; i = _j += 1) { currentNode = currentNode.prev; } } return currentNode; }; LinkedList.prototype.add = function(value, position) { var currentNode, nodeToAdd, _ref, _ref1, _ref2; if (position == null) { position = this.size; } /* Add a new item at `position` (optional). Defaults to adding at the end. `position`, just like in `at()`, can be negative (within the negative boundary). Position specifies the place the value's going to be, and the old node will be pushed higher. `add(-2)` on list of size 7 is the same as `add(5)`. _Returns:_ item added. */ if (!((-this.size <= position && position <= this.size))) { return; } nodeToAdd = { value: value }; position = this._adjust(position); if (this.size === 0) { this.head = nodeToAdd; } else { if (position === 0) { _ref = [nodeToAdd, this.head, nodeToAdd], this.head.prev = _ref[0], nodeToAdd.next = _ref[1], this.head = _ref[2]; } else { currentNode = this.at(position - 1); _ref1 = [currentNode.next, nodeToAdd, nodeToAdd, currentNode], nodeToAdd.next = _ref1[0], (_ref2 = currentNode.next) != null ? _ref2.prev = _ref1[1] : void 0, currentNode.next = _ref1[2], nodeToAdd.prev = _ref1[3]; } } if (position === this.size) { this.tail = nodeToAdd; } this.size++; return value; }; LinkedList.prototype.removeAt = function(position) { var currentNode, valueToReturn, _ref; if (position == null) { position = this.size - 1; } /* Remove an item at index `position` (optional). Defaults to the last item. Index can be negative (within the boundary). _Returns:_ item removed. */ if (!((-this.size <= position && position < this.size))) { return; } if (this.size === 0) { return; } position = this._adjust(position); if (this.size === 1) { valueToReturn = this.head.value; this.head.value = this.tail.value = void 0; } else { if (position === 0) { valueToReturn = this.head.value; this.head = this.head.next; this.head.prev = void 0; } else { currentNode = this.at(position); valueToReturn = currentNode.value; currentNode.prev.next = currentNode.next; if ((_ref = currentNode.next) != null) { _ref.prev = currentNode.prev; } if (position === this.size - 1) { this.tail = currentNode.prev; } } } this.size--; return valueToReturn; }; LinkedList.prototype.remove = function(value) { /* Remove the item using its value instead of position. **Will remove the fist occurrence of `value`.** _Returns:_ the value, or undefined if value's not found. */ var currentNode; if (value == null) { return; } currentNode = this.head; while (currentNode && currentNode.value !== value) { currentNode = currentNode.next; } if (!currentNode) { return; } if (this.size === 1) { this.head.value = this.tail.value = void 0; } else if (currentNode === this.head) { this.head = this.head.next; this.head.prev = void 0; } else if (currentNode === this.tail) { this.tail = this.tail.prev; this.tail.next = void 0; } else { currentNode.prev.next = currentNode.next; currentNode.next.prev = currentNode.prev; } this.size--; return value; }; LinkedList.prototype.indexOf = function(value, startingPosition) { var currentNode, position; if (startingPosition == null) { startingPosition = 0; } /* Find the index of an item, similarly to `array.indexOf()`. Defaults to start searching from the beginning, by can start at another position by passing `startingPosition`. This parameter can also be negative; but unlike the other methods of this class, `startingPosition` (optional) can be as small as desired; a value of -999 for a list of size 5 will start searching normally, at the beginning. **Note:** searches forwardly, **not** backwardly, i.e: ```js var myList = new LinkedList([2, 3, 1, 4, 3, 5]) myList.indexOf(3, -3); // Returns 4, not 1 ``` _Returns:_ index of item found, or -1 if not found. */ if (((this.head.value == null) && !this.head.next) || startingPosition >= this.size) { return -1; } startingPosition = Math.max(0, this._adjust(startingPosition)); currentNode = this.at(startingPosition); position = startingPosition; while (currentNode) { if (currentNode.value === value) { break; } currentNode = currentNode.next; position++; } if (position === this.size) { return -1; } else { return position; } }; LinkedList.prototype._adjust = function(position) { if (position < 0) { return this.size + position; } else { return position; } }; return LinkedList; })(); module.exports = LinkedList; }).call(this); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* Kind of a stopgap measure for the upcoming [JavaScript Map](http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets) **Note:** due to JavaScript's limitations, hashing something other than Boolean, Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a hidden unique property into the object. This means `set`, `get`, `has` and `delete` must employ the same object, and not a mere identical copy as in the case of, say, a string. ## Overview example: ```js var map = new Map({'alice': 'wonderland', 20: 'ok'}); map.set('20', 5); // => 5 map.get('20'); // => 5 map.has('alice'); // => true map.delete(20) // => true var arr = [1, 2]; map.add(arr, 'goody'); // => 'goody' map.has(arr); // => true map.has([1, 2]); // => false. Needs to compare by reference map.forEach(function(key, value) { console.log(key, value); }); ``` ## Properties: - size: The total number of `(key, value)` pairs. */ (function() { var Map, SPECIAL_TYPE_KEY_PREFIX, _extractDataType, _isSpecialType, __hasProp = {}.hasOwnProperty; SPECIAL_TYPE_KEY_PREFIX = '_mapId_'; Map = (function() { Map._mapIdTracker = 0; Map._newMapId = function() { return this._mapIdTracker++; }; function Map(objectToMap) { /* Pass an optional object whose (key, value) pair will be hashed. **Careful** not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's native object behavior will crush the first 5 property before it gets to constructor. */ var key, value; this._content = {}; this._itemId = 0; this._id = Map._newMapId(); this.size = 0; for (key in objectToMap) { if (!__hasProp.call(objectToMap, key)) continue; value = objectToMap[key]; this.set(key, value); } } Map.prototype.hash = function(key, makeHash) { var propertyForMap, type; if (makeHash == null) { makeHash = false; } /* The hash function for hashing keys is public. Feel free to replace it with your own. The `makeHash` parameter is optional and accepts a boolean (defaults to `false`) indicating whether or not to produce a new hash (for the first use, naturally). _Returns:_ the hash. */ type = _extractDataType(key); if (_isSpecialType(key)) { propertyForMap = SPECIAL_TYPE_KEY_PREFIX + this._id; if (makeHash && !key[propertyForMap]) { key[propertyForMap] = this._itemId++; } return propertyForMap + '_' + key[propertyForMap]; } else { return type + '_' + key; } }; Map.prototype.set = function(key, value) { /* _Returns:_ value. */ if (!this.has(key)) { this.size++; } this._content[this.hash(key, true)] = [value, key]; return value; }; Map.prototype.get = function(key) { /* _Returns:_ value corresponding to the key, or undefined if not found. */ var _ref; return (_ref = this._content[this.hash(key)]) != null ? _ref[0] : void 0; }; Map.prototype.has = function(key) { /* Check whether a value exists for the key. _Returns:_ true or false. */ return this.hash(key) in this._content; }; Map.prototype["delete"] = function(key) { /* Remove the (key, value) pair. _Returns:_ **true or false**. Unlike most of this library, this method doesn't return the deleted value. This is so that it conforms to the future JavaScript `map.delete()`'s behavior. */ var hashedKey; hashedKey = this.hash(key); if (hashedKey in this._content) { delete this._content[hashedKey]; if (_isSpecialType(key)) { delete key[SPECIAL_TYPE_KEY_PREFIX + this._id]; } this.size--; return true; } return false; }; Map.prototype.forEach = function(operation) { /* Traverse through the map. Pass a function of the form `fn(key, value)`. _Returns:_ undefined. */ var key, value, _ref; _ref = this._content; for (key in _ref) { if (!__hasProp.call(_ref, key)) continue; value = _ref[key]; operation(value[1], value[0]); } }; return Map; })(); _isSpecialType = function(key) { var simpleHashableTypes, simpleType, type, _i, _len; simpleHashableTypes = ['Boolean', 'Number', 'String', 'Undefined', 'Null', 'RegExp', 'Function']; type = _extractDataType(key); for (_i = 0, _len = simpleHashableTypes.length; _i < _len; _i++) { simpleType = simpleHashableTypes[_i]; if (type === simpleType) { return false; } } return true; }; _extractDataType = function(type) { return Object.prototype.toString.apply(type).match(/\[object (.+)\]/)[1]; }; module.exports = Map; }).call(this); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* Amortized O(1) dequeue! ## Overview example: ```js var queue = new Queue([1, 6, 4]); queue.enqueue(10); // => 10 queue.dequeue(); // => 1 queue.dequeue(); // => 6 queue.dequeue(); // => 4 queue.peek(); // => 10 queue.dequeue(); // => 10 queue.peek(); // => undefined ``` ## Properties: - size: The total number of items. */ (function() { var Queue; Queue = (function() { function Queue(initialArray) { if (initialArray == null) { initialArray = []; } /* Pass an optional array to be transformed into a queue. The item at index 0 is the first to be dequeued. */ this._content = initialArray; this._dequeueIndex = 0; this.size = this._content.length; } Queue.prototype.enqueue = function(item) { /* _Returns:_ the item. */ this.size++; this._content.push(item); return item; }; Queue.prototype.dequeue = function() { /* _Returns:_ the dequeued item. */ var itemToDequeue; if (this.size === 0) { return; } this.size--; itemToDequeue = this._content[this._dequeueIndex]; this._dequeueIndex++; if (this._dequeueIndex * 2 > this._content.length) { this._content = this._content.slice(this._dequeueIndex); this._dequeueIndex = 0; } return itemToDequeue; }; Queue.prototype.peek = function() { /* Check the next item to be dequeued, without removing it. _Returns:_ the item. */ return this._content[this._dequeueIndex]; }; return Queue; })(); module.exports = Queue; }).call(this); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* Credit to Wikipedia's article on [Red-black tree](http://en.wikipedia.org/wiki/Red–black_tree) **Note:** doesn't handle duplicate entries, undefined and null. This is by design. ## Overview example: ```js var rbt = new RedBlackTree([7, 5, 1, 8]); rbt.add(2); // => 2 rbt.add(10); // => 10 rbt.has(5); // => true rbt.peekMin(); // => 1 rbt.peekMax(); // => 10 rbt.removeMin(); // => 1 rbt.removeMax(); // => 10 rbt.remove(8); // => 8 ``` ## Properties: - size: The total number of items. */ (function() { var BLACK, NODE_FOUND, NODE_TOO_BIG, NODE_TOO_SMALL, RED, RedBlackTree, STOP_SEARCHING, _findNode, _grandParentOf, _isLeft, _leftOrRight, _peekMaxNode, _peekMinNode, _siblingOf, _uncleOf; NODE_FOUND = 0; NODE_TOO_BIG = 1; NODE_TOO_SMALL = 2; STOP_SEARCHING = 3; RED = 1; BLACK = 2; RedBlackTree = (function() { function RedBlackTree(valuesToAdd) { var value, _i, _len; if (valuesToAdd == null) { valuesToAdd = []; } /* Pass an optional array to be turned into binary tree. **Note:** does not accept duplicate, undefined and null. */ this._root; this.size = 0; for (_i = 0, _len = valuesToAdd.length; _i < _len; _i++) { value = valuesToAdd[_i]; if (value != null) { this.add(value); } } } RedBlackTree.prototype.add = function(value) { /* Again, make sure to not pass a value already in the tree, or undefined, or null. _Returns:_ value added. */ var currentNode, foundNode, nodeToInsert, _ref; if (value == null) { return; } this.size++; nodeToInsert = { value: value, _color: RED }; if (!this._root) { this._root = nodeToInsert; } else { foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else { if (value < node.value) { if (node._left) { return NODE_TOO_BIG; } else { nodeToInsert._parent = node; node._left = nodeToInsert; return STOP_SEARCHING; } } else { if (node._right) { return NODE_TOO_SMALL; } else { nodeToInsert._parent = node; node._right = nodeToInsert; return STOP_SEARCHING; } } } }); if (foundNode != null) { return; } } currentNode = nodeToInsert; while (true) { if (currentNode === this._root) { currentNode._color = BLACK; break; } if (currentNode._parent._color === BLACK) { break; } if (((_ref = _uncleOf(currentNode)) != null ? _ref._color : void 0) === RED) { currentNode._parent._color = BLACK; _uncleOf(currentNode)._color = BLACK; _grandParentOf(currentNode)._color = RED; currentNode = _grandParentOf(currentNode); continue; } if (!_isLeft(currentNode) && _isLeft(currentNode._parent)) { this._rotateLeft(currentNode._parent); currentNode = currentNode._left; } else if (_isLeft(currentNode) && !_isLeft(currentNode._parent)) { this._rotateRight(currentNode._parent); currentNode = currentNode._right; } currentNode._parent._color = BLACK; _grandParentOf(currentNode)._color = RED; if (_isLeft(currentNode)) { this._rotateRight(_grandParentOf(currentNode)); } else { this._rotateLeft(_grandParentOf(currentNode)); } break; } return value; }; RedBlackTree.prototype.has = function(value) { /* _Returns:_ true or false. */ var foundNode; foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else if (value < node.value) { return NODE_TOO_BIG; } else { return NODE_TOO_SMALL; } }); if (foundNode) { return true; } else { return false; } }; RedBlackTree.prototype.peekMin = function() { /* Check the minimum value without removing it. _Returns:_ the minimum value. */ var _ref; return (_ref = _peekMinNode(this._root)) != null ? _ref.value : void 0; }; RedBlackTree.prototype.peekMax = function() { /* Check the maximum value without removing it. _Returns:_ the maximum value. */ var _ref; return (_ref = _peekMaxNode(this._root)) != null ? _ref.value : void 0; }; RedBlackTree.prototype.remove = function(value) { /* _Returns:_ the value removed, or undefined if the value's not found. */ var foundNode; foundNode = _findNode(this._root, function(node) { if (value === node.value) { return NODE_FOUND; } else if (value < node.value) { return NODE_TOO_BIG; } else { return NODE_TOO_SMALL; } }); if (!foundNode) { return; } this._removeNode(this._root, foundNode); this.size--; return value; }; RedBlackTree.prototype.removeMin = function() { /* _Returns:_ smallest item removed, or undefined if tree's empty. */ var nodeToRemove, valueToReturn; nodeToRemove = _peekMinNode(this._root); if (!nodeToRemove) { return; } valueToReturn = nodeToRemove.value; this._removeNode(this._root, nodeToRemove); return valueToReturn; }; RedBlackTree.prototype.removeMax = function() { /* _Returns:_ biggest item removed, or undefined if tree's empty. */ var nodeToRemove, valueToReturn; nodeToRemove = _peekMaxNode(this._root); if (!nodeToRemove) { return; } valueToReturn = nodeToRemove.value; this._removeNode(this._root, nodeToRemove); return valueToReturn; }; RedBlackTree.prototype._removeNode = function(root, node) { var sibling, successor, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; if (node._left && node._right) { successor = _peekMinNode(node._right); node.value = successor.value; node = successor; } successor = node._left || node._right; if (!successor) { successor = { color: BLACK, _right: void 0, _left: void 0, isLeaf: true }; } successor._parent = node._parent; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = successor; } if (node._color === BLACK) { if (successor._color === RED) { successor._color = BLACK; if (!successor._parent) { this._root = successor; } } else { while (true) { if (!successor._parent) { if (!successor.isLeaf) { this._root = successor; } else { this._root = void 0; } break; } sibling = _siblingOf(successor); if ((sibling != null ? sibling._color : void 0) === RED) { successor._parent._color = RED; sibling._color = BLACK; if (_isLeft(successor)) { this._rotateLeft(successor._parent); } else { this._rotateRight(successor._parent); } } sibling = _siblingOf(successor); if (successor._parent._color === BLACK && (!sibling || (sibling._color === BLACK && (!sibling._left || sibling._left._color === BLACK) && (!sibling._right || sibling._right._color === BLACK)))) { if (sibling != null) { sibling._color = RED; } if (successor.isLeaf) { successor._parent[_leftOrRight(successor)] = void 0; } successor = successor._parent; continue; } if (successor._parent._color === RED && (!sibling || (sibling._color === BLACK && (!sibling._left || ((_ref1 = sibling._left) != null ? _ref1._color : void 0) === BLACK) && (!sibling._right || ((_ref2 = sibling._right) != null ? _ref2._color : void 0) === BLACK)))) { if (sibling != null) { sibling._color = RED; } successor._parent._color = BLACK; break; } if ((sibling != null ? sibling._color : void 0) === BLACK) { if (_isLeft(successor) && (!sibling._right || sibling._right._color === BLACK) && ((_ref3 = sibling._left) != null ? _ref3._color : void 0) === RED) { sibling._color = RED; if ((_ref4 = sibling._left) != null) { _ref4._color = BLACK; } this._rotateRight(sibling); } else if (!_isLeft(successor) && (!sibling._left || sibling._left._color === BLACK) && ((_ref5 = sibling._right) != null ? _ref5._color : void 0) === RED) { sibling._color = RED; if ((_ref6 = sibling._right) != null) { _ref6._color = BLACK; } this._rotateLeft(sibling); } break; } sibling = _siblingOf(successor); sibling._color = successor._parent._color; if (_isLeft(successor)) { sibling._right._color = BLACK; this._rotateRight(successor._parent); } else { sibling._left._color = BLACK; this._rotateLeft(successor._parent); } } } } if (successor.isLeaf) { return (_ref7 = successor._parent) != null ? _ref7[_leftOrRight(successor)] = void 0 : void 0; } }; RedBlackTree.prototype._rotateLeft = function(node) { var _ref, _ref1; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = node._right; } node._right._parent = node._parent; node._parent = node._right; node._right = node._right._left; node._parent._left = node; if ((_ref1 = node._right) != null) { _ref1._parent = node; } if (node._parent._parent == null) { return this._root = node._parent; } }; RedBlackTree.prototype._rotateRight = function(node) { var _ref, _ref1; if ((_ref = node._parent) != null) { _ref[_leftOrRight(node)] = node._left; } node._left._parent = node._parent; node._parent = node._left; node._left = node._left._right; node._parent._right = node; if ((_ref1 = node._left) != null) { _ref1._parent = node; } if (node._parent._parent == null) { return this._root = node._parent; } }; return RedBlackTree; })(); _isLeft = function(node) { return node === node._parent._left; }; _leftOrRight = function(node) { if (_isLeft(node)) { return '_left'; } else { return '_right'; } }; _findNode = function(startingNode, comparator) { var comparisonResult, currentNode, foundNode; currentNode = startingNode; foundNode = void 0; while (currentNode) { comparisonResult = comparator(currentNode); if (comparisonResult === NODE_FOUND) { foundNode = currentNode; break; } if (comparisonResult === NODE_TOO_BIG) { currentNode = currentNode._left; } else if (comparisonResult === NODE_TOO_SMALL) { currentNode = currentNode._right; } else if (comparisonResult === STOP_SEARCHING) { break; } } return foundNode; }; _peekMinNode = function(startingNode) { return _findNode(startingNode, function(node) { if (node._left) { return NODE_TOO_BIG; } else { return NODE_FOUND; } }); }; _peekMaxNode = function(startingNode) { return _findNode(startingNode, function(node) { if (node._right) { return NODE_TOO_SMALL; } else { return NODE_FOUND; } }); }; _grandParentOf = function(node) { var _ref; return (_ref = node._parent) != null ? _ref._parent : void 0; }; _uncleOf = function(node) { if (!_grandParentOf(node)) { return; } if (_isLeft(node._parent)) { return _grandParentOf(node)._right; } else { return _grandParentOf(node)._left; } }; _siblingOf = function(node) { if (_isLeft(node)) { return node._parent._right; } else { return node._parent._left; } }; module.exports = RedBlackTree; }).call(this); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* Good for fast insertion/removal/lookup of strings. ## Overview example: ```js var trie = new Trie(['bear', 'beer']); trie.add('hello'); // => 'hello' trie.add('helloha!'); // => 'helloha!' trie.has('bears'); // => false trie.longestPrefixOf('beatrice'); // => 'bea' trie.wordsWithPrefix('hel'); // => ['hello', 'helloha!'] trie.remove('beers'); // => undefined. 'beer' still exists trie.remove('Beer') // => undefined. Case-sensitive trie.remove('beer') // => 'beer'. Removed ``` ## Properties: - size: The total number of words. */ (function() { var Queue, Trie, WORD_END, _hasAtLeastNChildren, __hasProp = {}.hasOwnProperty; Queue = __webpack_require__(6); WORD_END = 'end'; Trie = (function() { function Trie(words) { var word, _i, _len; if (words == null) { words = []; } /* Pass an optional array of strings to be inserted initially. */ this._root = {}; this.size = 0; for (_i = 0, _len = words.length; _i < _len; _i++) { word = words[_i]; this.add(word); } } Trie.prototype.add = function(word) { /* Add a whole string to the trie. _Returns:_ the word added. Will return undefined (without adding the value) if the word passed is null or undefined. */ var currentNode, letter, _i, _len; if (word == null) { return; } this.size++; currentNode = this._root; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { currentNode[letter] = {}; } currentNode = currentNode[letter]; } currentNode[WORD_END] = true; return word; }; Trie.prototype.has = function(word) { /* __Returns:_ true or false. */ var currentNode, letter, _i, _len; if (word == null) { return false; } currentNode = this._root; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { return false; } currentNode = currentNode[letter]; } if (currentNode[WORD_END]) { return true; } else { return false; } }; Trie.prototype.longestPrefixOf = function(word) { /* Find all words containing the prefix. The word itself counts as a prefix. ```js var trie = new Trie; trie.add('hello'); trie.longestPrefixOf('he'); // 'he' trie.longestPrefixOf('hello'); // 'hello' trie.longestPrefixOf('helloha!'); // 'hello' ``` _Returns:_ the prefix string, or empty string if no prefix found. */ var currentNode, letter, prefix, _i, _len; if (word == null) { return ''; } currentNode = this._root; prefix = ''; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { break; } prefix += letter; currentNode = currentNode[letter]; } return prefix; }; Trie.prototype.wordsWithPrefix = function(prefix) { /* Find all words containing the prefix. The word itself counts as a prefix. **Watch out for edge cases.** ```js var trie = new Trie; trie.wordsWithPrefix(''); // []. Check later case below. trie.add(''); trie.wordsWithPrefix(''); // [''] trie.add('he'); trie.add('hello'); trie.add('hell'); trie.add('bear'); trie.add('z'); trie.add('zebra'); trie.wordsWithPrefix('hel'); // ['hell', 'hello'] ``` _Returns:_ an array of strings, or empty array if no word found. */ var accumulatedLetters, currentNode, letter, node, queue, subNode, words, _i, _len, _ref; if (prefix == null) { return []; } (prefix != null) || (prefix = ''); words = []; currentNode = this._root; for (_i = 0, _len = prefix.length; _i < _len; _i++) { letter = prefix[_i]; currentNode = currentNode[letter]; if (currentNode == null) { return []; } } queue = new Queue(); queue.enqueue([currentNode, '']); while (queue.size !== 0) { _ref = queue.dequeue(), node = _ref[0], accumulatedLetters = _ref[1]; if (node[WORD_END]) { words.push(prefix + accumulatedLetters); } for (letter in node) { if (!__hasProp.call(node, letter)) continue; subNode = node[letter]; queue.enqueue([subNode, accumulatedLetters + letter]); } } return words; }; Trie.prototype.remove = function(word) { /* _Returns:_ the string removed, or undefined if the word in its whole doesn't exist. **Note:** this means removing `beers` when only `beer` exists will return undefined and conserve `beer`. */ var currentNode, i, letter, prefix, _i, _j, _len, _ref; if (word == null) { return; } currentNode = this._root; prefix = []; for (_i = 0, _len = word.length; _i < _len; _i++) { letter = word[_i]; if (currentNode[letter] == null) { return; } currentNode = currentNode[letter]; prefix.push([letter, currentNode]); } if (!currentNode[WORD_END]) { return; } this.size--; delete currentNode[WORD_END]; if (_hasAtLeastNChildren(currentNode, 1)) { return word; } for (i = _j = _ref = prefix.length - 1; _ref <= 1 ? _j <= 1 : _j >= 1; i = _ref <= 1 ? ++_j : --_j) { if (!_hasAtLeastNChildren(prefix[i][1], 1)) { delete prefix[i - 1][1][prefix[i][0]]; } else { break; } } if (!_hasAtLeastNChildren(this._root[prefix[0][0]], 1)) { delete this._root[prefix[0][0]]; } return word; }; return Trie; })(); _hasAtLeastNChildren = function(node, n) { var child, childCount; if (n === 0) { return true; } childCount = 0; for (child in node) { if (!__hasProp.call(node, child)) continue; childCount++; if (childCount >= n) { return true; } } return false; }; module.exports = Trie; }).call(this); /***/ } /******/ ]);;/** * Performance overrides on MarkerClusterer custom to Angular Google Maps * * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14. */ angular.module('uiGmapgoogle-maps.extensions') .service('uiGmapExtendMarkerClusterer',['uiGmapLodash', 'uiGmapPropMap', function (uiGmapLodash, PropMap) { return { init: _.once(function () { (function () { var __hasProp = {}.hasOwnProperty, __extends = function (child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.NgMapCluster = (function (_super) { __extends(NgMapCluster, _super); function NgMapCluster(opts) { NgMapCluster.__super__.constructor.call(this, opts); this.markers_ = new PropMap(); } /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ NgMapCluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { var oldMarker = this.markers_.get(marker.key); if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. this.markers_.each(function (m) { m.setMap(null); }); } else { marker.setMap(null); } //this.updateIcon_(); return true; }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) { return uiGmapLodash.isNullOrUndefined(this.markers_.get(marker.key)); }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ NgMapCluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.getMarkers().each(function(m){ bounds.extend(m.getPosition()); }); return bounds; }; /** * Removes the cluster from the map. * * @ignore */ NgMapCluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = new PropMap(); delete this.markers_; }; return NgMapCluster; })(Cluster); window.NgMapMarkerClusterer = (function (_super) { __extends(NgMapMarkerClusterer, _super); function NgMapMarkerClusterer(map, opt_markers, opt_options) { NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options); this.markers_ = new PropMap(); } /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ NgMapMarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = new PropMap(); }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) { if (!this.markers_.get(marker.key)) { return false; } marker.setMap(null); this.markers_.remove(marker.key); // Remove the marker from the list of managed markers return true; }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringbegin', this); if (typeof this.timerRefStatic !== 'undefined') { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); var _ms = this.markers_.values(); for (i = iFirst; i < iLast; i++) { marker = _ms[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { // custom addition by ui-gmap // update icon for all clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].updateIcon_(); } delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, 'clusteringend', this); } }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new NgMapCluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Redraws all the clusters. */ NgMapMarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. this.markers_.each(function (marker) { marker.isAdded = false; if (opt_hide) { marker.setMap(null); } }); }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { if (property !== 'constructor') this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; //////////////////////////////////////////////////////////////////////////////// /* Other overrides relevant to MarkerClusterPlus */ //////////////////////////////////////////////////////////////////////////////// /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } // ADDED FOR RETINA SUPPORT else { img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;"; } // END ADD img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; //END OTHER OVERRIDES //////////////////////////////////////////////////////////////////////////////// return NgMapMarkerClusterer; })(MarkerClusterer); }).call(this); }) }; }]); }( window,angular)); //# sourceMappingURL=angular-google-maps_dev_mapped.js.map
examples/blockly-react/src/Blockly/index.js
google/blockly-samples
/** * @license * * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview XML wrappers for block, category, value, field and shadow. * @author [email protected] (Sam El-Husseini) */ import React from 'react'; import BlocklyComponent from './BlocklyComponent'; export default BlocklyComponent; const Block = (p) => { const { children, ...props } = p; props.is = "blockly"; return React.createElement("block", props, children); }; const Category = (p) => { const { children, ...props } = p; props.is = "blockly"; return React.createElement("category", props, children); }; const Value = (p) => { const { children, ...props } = p; props.is = "blockly"; return React.createElement("value", props, children); }; const Field = (p) => { const { children, ...props } = p; props.is = "blockly"; return React.createElement("field", props, children); }; const Shadow = (p) => { const { children, ...props } = p; props.is = "blockly"; return React.createElement("shadow", props, children); }; export { Block, Category, Value, Field, Shadow }
src/index.js
react-hack-night/reactSocial
// Import NPM dependencies like this: import React from 'react'; import ReactDOM from 'react-dom'; import {Grid} from 'react-bootstrap'; // Import styles like this: import './styles/main.scss'; import Main from './components/main'; import Insta from './components/instagram'; // Import dependencies like this: import Giphy from './components/giphy.js'; class App extends React.Component { render() { return ( <Grid> <Main /> </Grid> ); } } ReactDOM.render(<App />, document.getElementById('app'));
ajax/libs/vis/3.5.0/vis.js
nareshs435/cdnjs
/** * vis.js * https://github.com/almende/vis * * A dynamic, browser-based visualization library. * * @version 3.5.0 * @date 2014-09-16 * * @license * Copyright (C) 2011-2014 Almende B.V, http://almende.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["vis"] = factory(); else root["vis"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { // utils exports.util = __webpack_require__(1); exports.DOMutil = __webpack_require__(2); // data exports.DataSet = __webpack_require__(3); exports.DataView = __webpack_require__(4); // Graph3d exports.Graph3d = __webpack_require__(5); exports.graph3d = { Camera: __webpack_require__(6), Filter: __webpack_require__(7), Point2d: __webpack_require__(8), Point3d: __webpack_require__(9), Slider: __webpack_require__(10), StepNumber: __webpack_require__(11) }; // Timeline exports.Timeline = __webpack_require__(12); exports.Graph2d = __webpack_require__(13); exports.timeline = { DataStep: __webpack_require__(14), Range: __webpack_require__(15), stack: __webpack_require__(16), TimeStep: __webpack_require__(17), components: { items: { Item: __webpack_require__(28), BackgroundItem: __webpack_require__(29), BoxItem: __webpack_require__(30), PointItem: __webpack_require__(31), RangeItem: __webpack_require__(32) }, Component: __webpack_require__(18), CurrentTime: __webpack_require__(19), CustomTime: __webpack_require__(20), DataAxis: __webpack_require__(21), GraphGroup: __webpack_require__(22), Group: __webpack_require__(23), ItemSet: __webpack_require__(24), Legend: __webpack_require__(25), LineGraph: __webpack_require__(26), TimeAxis: __webpack_require__(27) } }; // Network exports.Network = __webpack_require__(33); exports.network = { Edge: __webpack_require__(34), Groups: __webpack_require__(35), Images: __webpack_require__(36), Node: __webpack_require__(37), Popup: __webpack_require__(38), dotparser: __webpack_require__(39), gephiParser: __webpack_require__(40) }; // Deprecated since v3.0.0 exports.Graph = function () { throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)'); }; // bundled external libraries exports.moment = __webpack_require__(41); exports.hammer = __webpack_require__(42); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // utility functions // first check if moment.js is already loaded in the browser window, if so, // use this instance. Else, load via commonjs. var moment = __webpack_require__(41); /** * Test whether given object is a number * @param {*} object * @return {Boolean} isNumber */ exports.isNumber = function(object) { return (object instanceof Number || typeof object == 'number'); }; /** * Test whether given object is a string * @param {*} object * @return {Boolean} isString */ exports.isString = function(object) { return (object instanceof String || typeof object == 'string'); }; /** * Test whether given object is a Date, or a String containing a Date * @param {Date | String} object * @return {Boolean} isDate */ exports.isDate = function(object) { if (object instanceof Date) { return true; } else if (exports.isString(object)) { // test whether this string contains a date var match = ASPDateRegex.exec(object); if (match) { return true; } else if (!isNaN(Date.parse(object))) { return true; } } return false; }; /** * Test whether given object is an instance of google.visualization.DataTable * @param {*} object * @return {Boolean} isDataTable */ exports.isDataTable = function(object) { return (typeof (google) !== 'undefined') && (google.visualization) && (google.visualization.DataTable) && (object instanceof google.visualization.DataTable); }; /** * Create a semi UUID * source: http://stackoverflow.com/a/105074/1262753 * @return {String} uuid */ exports.randomUUID = function() { var S4 = function () { return Math.floor( Math.random() * 0x10000 /* 65536 */ ).toString(16); }; return ( S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() ); }; /** * Extend object a with the properties of object b or a series of objects * Only properties with defined values are copied * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.extend = function (a, b) { for (var i = 1, len = arguments.length; i < len; i++) { var other = arguments[i]; for (var prop in other) { if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveExtend = function (props, a, b) { if (!Array.isArray(props)) { throw new Error('Array with property names expected as first argument'); } for (var i = 2; i < arguments.length; i++) { var other = arguments[i]; for (var p = 0; p < props.length; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveDeepExtend = function (props, a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var i = 2; i < arguments.length; i++) { var other = arguments[i]; for (var p = 0; p < props.length; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveNotDeepExtend = function (props, a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (props.indexOf(prop) == -1) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } } return a; }; /** * Deep extend an object a with the properties of object b * @param {Object} a * @param {Object} b * @returns {Object} */ exports.deepExtend = function(a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } return a; }; /** * Test whether all elements in two arrays are equal. * @param {Array} a * @param {Array} b * @return {boolean} Returns true if both arrays have the same length and same * elements. */ exports.equalArray = function (a, b) { if (a.length != b.length) return false; for (var i = 0, len = a.length; i < len; i++) { if (a[i] != b[i]) return false; } return true; }; /** * Convert an object to another type * @param {Boolean | Number | String | Date | Moment | Null | undefined} object * @param {String | undefined} type Name of the type. Available types: * 'Boolean', 'Number', 'String', * 'Date', 'Moment', ISODate', 'ASPDate'. * @return {*} object * @throws Error */ exports.convert = function(object, type) { var match; if (object === undefined) { return undefined; } if (object === null) { return null; } if (!type) { return object; } if (!(typeof type === 'string') && !(type instanceof String)) { throw new Error('Type must be a string'); } //noinspection FallthroughInSwitchStatementJS switch (type) { case 'boolean': case 'Boolean': return Boolean(object); case 'number': case 'Number': return Number(object.valueOf()); case 'string': case 'String': return String(object); case 'Date': if (exports.isNumber(object)) { return new Date(object); } if (object instanceof Date) { return new Date(object.valueOf()); } else if (moment.isMoment(object)) { return new Date(object.valueOf()); } if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])); // parse number } else { return moment(object).toDate(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type Date'); } case 'Moment': if (exports.isNumber(object)) { return moment(object); } if (object instanceof Date) { return moment(object.valueOf()); } else if (moment.isMoment(object)) { return moment(object); } if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return moment(Number(match[1])); // parse number } else { return moment(object); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type Date'); } case 'ISODate': if (exports.isNumber(object)) { return new Date(object); } else if (object instanceof Date) { return object.toISOString(); } else if (moment.isMoment(object)) { return object.toDate().toISOString(); } else if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])).toISOString(); // parse number } else { return new Date(object).toISOString(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type ISODate'); } case 'ASPDate': if (exports.isNumber(object)) { return '/Date(' + object + ')/'; } else if (object instanceof Date) { return '/Date(' + object.valueOf() + ')/'; } else if (exports.isString(object)) { match = ASPDateRegex.exec(object); var value; if (match) { // object is an ASP date value = new Date(Number(match[1])).valueOf(); // parse number } else { value = new Date(object).valueOf(); // parse string } return '/Date(' + value + ')/'; } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate'); } default: throw new Error('Unknown type "' + type + '"'); } }; // parse ASP.Net Date pattern, // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/' // code from http://momentjs.com/ var ASPDateRegex = /^\/?Date\((\-?\d+)/i; /** * Get the type of an object, for example exports.getType([]) returns 'Array' * @param {*} object * @return {String} type */ exports.getType = function(object) { var type = typeof object; if (type == 'object') { if (object == null) { return 'null'; } if (object instanceof Boolean) { return 'Boolean'; } if (object instanceof Number) { return 'Number'; } if (object instanceof String) { return 'String'; } if (object instanceof Array) { return 'Array'; } if (object instanceof Date) { return 'Date'; } return 'Object'; } else if (type == 'number') { return 'Number'; } else if (type == 'boolean') { return 'Boolean'; } else if (type == 'string') { return 'String'; } return type; }; /** * Retrieve the absolute left value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} left The absolute left position of this element * in the browser page. */ exports.getAbsoluteLeft = function(elem) { return elem.getBoundingClientRect().left + window.pageXOffset; }; /** * Retrieve the absolute top value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} top The absolute top position of this element * in the browser page. */ exports.getAbsoluteTop = function(elem) { return elem.getBoundingClientRect().top + window.pageYOffset; }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ exports.addClassName = function(elem, className) { var classes = elem.className.split(' '); if (classes.indexOf(className) == -1) { classes.push(className); // add the class to the array elem.className = classes.join(' '); } }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ exports.removeClassName = function(elem, className) { var classes = elem.className.split(' '); var index = classes.indexOf(className); if (index != -1) { classes.splice(index, 1); // remove the class from the array elem.className = classes.join(' '); } }; /** * For each method for both arrays and objects. * In case of an array, the built-in Array.forEach() is applied. * In case of an Object, the method loops over all properties of the object. * @param {Object | Array} object An Object or Array * @param {function} callback Callback method, called for each item in * the object or array with three parameters: * callback(value, index, object) */ exports.forEach = function(object, callback) { var i, len; if (object instanceof Array) { // array for (i = 0, len = object.length; i < len; i++) { callback(object[i], i, object); } } else { // object for (i in object) { if (object.hasOwnProperty(i)) { callback(object[i], i, object); } } } }; /** * Convert an object into an array: all objects properties are put into the * array. The resulting array is unordered. * @param {Object} object * @param {Array} array */ exports.toArray = function(object) { var array = []; for (var prop in object) { if (object.hasOwnProperty(prop)) array.push(object[prop]); } return array; } /** * Update a property in an object * @param {Object} object * @param {String} key * @param {*} value * @return {Boolean} changed */ exports.updateProperty = function(object, key, value) { if (object[key] !== value) { object[key] = value; return true; } else { return false; } }; /** * Add and event listener. Works for all browsers * @param {Element} element An html element * @param {string} action The action, for example "click", * without the prefix "on" * @param {function} listener The callback function to be executed * @param {boolean} [useCapture] */ exports.addEventListener = function(element, action, listener, useCapture) { if (element.addEventListener) { if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.addEventListener(action, listener, useCapture); } else { element.attachEvent("on" + action, listener); // IE browsers } }; /** * Remove an event listener from an element * @param {Element} element An html dom element * @param {string} action The name of the event, for example "mousedown" * @param {function} listener The listener function * @param {boolean} [useCapture] */ exports.removeEventListener = function(element, action, listener, useCapture) { if (element.removeEventListener) { // non-IE browsers if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.removeEventListener(action, listener, useCapture); } else { // IE browsers element.detachEvent("on" + action, listener); } }; /** * Cancels the event if it is cancelable, without stopping further propagation of the event. */ exports.preventDefault = function (event) { if (!event) event = window.event; if (event.preventDefault) { event.preventDefault(); // non-IE browsers } else { event.returnValue = false; // IE browsers } }; /** * Get HTML element which is the target of the event * @param {Event} event * @return {Element} target element */ exports.getTarget = function(event) { // code from http://www.quirksmode.org/js/events_properties.html if (!event) { event = window.event; } var target; if (event.target) { target = event.target; } else if (event.srcElement) { target = event.srcElement; } if (target.nodeType != undefined && target.nodeType == 3) { // defeat Safari bug target = target.parentNode; } return target; }; exports.option = {}; /** * Convert a value into a boolean * @param {Boolean | function | undefined} value * @param {Boolean} [defaultValue] * @returns {Boolean} bool */ exports.option.asBoolean = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return (value != false); } return defaultValue || null; }; /** * Convert a value into a number * @param {Boolean | function | undefined} value * @param {Number} [defaultValue] * @returns {Number} number */ exports.option.asNumber = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return Number(value) || defaultValue || null; } return defaultValue || null; }; /** * Convert a value into a string * @param {String | function | undefined} value * @param {String} [defaultValue] * @returns {String} str */ exports.option.asString = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return String(value); } return defaultValue || null; }; /** * Convert a size or location into a string with pixels or a percentage * @param {String | Number | function | undefined} value * @param {String} [defaultValue] * @returns {String} size */ exports.option.asSize = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (exports.isString(value)) { return value; } else if (exports.isNumber(value)) { return value + 'px'; } else { return defaultValue || null; } }; /** * Convert a value into a DOM element * @param {HTMLElement | function | undefined} value * @param {HTMLElement} [defaultValue] * @returns {HTMLElement | null} dom */ exports.option.asElement = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } return value || defaultValue || null; }; exports.GiveDec = function(Hex) { var Value; if (Hex == "A") Value = 10; else if (Hex == "B") Value = 11; else if (Hex == "C") Value = 12; else if (Hex == "D") Value = 13; else if (Hex == "E") Value = 14; else if (Hex == "F") Value = 15; else Value = eval(Hex); return Value; }; exports.GiveHex = function(Dec) { var Value; if(Dec == 10) Value = "A"; else if (Dec == 11) Value = "B"; else if (Dec == 12) Value = "C"; else if (Dec == 13) Value = "D"; else if (Dec == 14) Value = "E"; else if (Dec == 15) Value = "F"; else Value = "" + Dec; return Value; }; /** * Parse a color property into an object with border, background, and * highlight colors * @param {Object | String} color * @return {Object} colorObject */ exports.parseColor = function(color) { var c; if (exports.isString(color)) { if (exports.isValidRGB(color)) { var rgb = color.substr(4).substr(0,color.length-5).split(','); color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]); } if (exports.isValidHex(color)) { var hsv = exports.hexToHSV(color); var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)}; var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6}; var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v); var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v); c = { background: color, border:darkerColorHex, highlight: { background:lighterColorHex, border:darkerColorHex }, hover: { background:lighterColorHex, border:darkerColorHex } }; } else { c = { background:color, border:color, highlight: { background:color, border:color }, hover: { background:color, border:color } }; } } else { c = {}; c.background = color.background || 'white'; c.border = color.border || c.background; if (exports.isString(color.highlight)) { c.highlight = { border: color.highlight, background: color.highlight } } else { c.highlight = {}; c.highlight.background = color.highlight && color.highlight.background || c.background; c.highlight.border = color.highlight && color.highlight.border || c.border; } if (exports.isString(color.hover)) { c.hover = { border: color.hover, background: color.hover } } else { c.hover = {}; c.hover.background = color.hover && color.hover.background || c.background; c.hover.border = color.hover && color.hover.border || c.border; } } return c; }; /** * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php * * @param {String} hex * @returns {{r: *, g: *, b: *}} */ exports.hexToRGB = function(hex) { hex = hex.replace("#","").toUpperCase(); var a = exports.GiveDec(hex.substring(0, 1)); var b = exports.GiveDec(hex.substring(1, 2)); var c = exports.GiveDec(hex.substring(2, 3)); var d = exports.GiveDec(hex.substring(3, 4)); var e = exports.GiveDec(hex.substring(4, 5)); var f = exports.GiveDec(hex.substring(5, 6)); var r = (a * 16) + b; var g = (c * 16) + d; var b = (e * 16) + f; return {r:r,g:g,b:b}; }; exports.RGBToHex = function(red,green,blue) { var a = exports.GiveHex(Math.floor(red / 16)); var b = exports.GiveHex(red % 16); var c = exports.GiveHex(Math.floor(green / 16)); var d = exports.GiveHex(green % 16); var e = exports.GiveHex(Math.floor(blue / 16)); var f = exports.GiveHex(blue % 16); var hex = a + b + c + d + e + f; return "#" + hex; }; /** * http://www.javascripter.net/faq/rgb2hsv.htm * * @param red * @param green * @param blue * @returns {*} * @constructor */ exports.RGBToHSV = function(red,green,blue) { red=red/255; green=green/255; blue=blue/255; var minRGB = Math.min(red,Math.min(green,blue)); var maxRGB = Math.max(red,Math.max(green,blue)); // Black-gray-white if (minRGB == maxRGB) { return {h:0,s:0,v:minRGB}; } // Colors other than black-gray-white: var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red); var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5); var hue = 60*(h - d/(maxRGB - minRGB))/360; var saturation = (maxRGB - minRGB)/maxRGB; var value = maxRGB; return {h:hue,s:saturation,v:value}; }; /** * https://gist.github.com/mjijackson/5311256 * @param h * @param s * @param v * @returns {{r: number, g: number, b: number}} * @constructor */ exports.HSVToRGB = function(h, s, v) { var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) }; }; exports.HSVToHex = function(h, s, v) { var rgb = exports.HSVToRGB(h, s, v); return exports.RGBToHex(rgb.r, rgb.g, rgb.b); }; exports.hexToHSV = function(hex) { var rgb = exports.hexToRGB(hex); return exports.RGBToHSV(rgb.r, rgb.g, rgb.b); }; exports.isValidHex = function(hex) { var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex); return isOk; }; exports.isValidRGB = function(rgb) { rgb = rgb.replace(" ",""); var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb); return isOk; } /** * This recursively redirects the prototype of JSON objects to the referenceObject * This is used for default options. * * @param referenceObject * @returns {*} */ exports.selectiveBridgeObject = function(fields, referenceObject) { if (typeof referenceObject == "object") { var objectTo = Object.create(referenceObject); for (var i = 0; i < fields.length; i++) { if (referenceObject.hasOwnProperty(fields[i])) { if (typeof referenceObject[fields[i]] == "object") { objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]); } } } return objectTo; } else { return null; } }; /** * This recursively redirects the prototype of JSON objects to the referenceObject * This is used for default options. * * @param referenceObject * @returns {*} */ exports.bridgeObject = function(referenceObject) { if (typeof referenceObject == "object") { var objectTo = Object.create(referenceObject); for (var i in referenceObject) { if (referenceObject.hasOwnProperty(i)) { if (typeof referenceObject[i] == "object") { objectTo[i] = exports.bridgeObject(referenceObject[i]); } } } return objectTo; } else { return null; } }; /** * this is used to set the options of subobjects in the options object. A requirement of these subobjects * is that they have an 'enabled' element which is optional for the user but mandatory for the program. * * @param [object] mergeTarget | this is either this.options or the options used for the groups. * @param [object] options | options * @param [String] option | this is the option key in the options argument * @private */ exports.mergeOptions = function (mergeTarget, options, option) { if (options[option] !== undefined) { if (typeof options[option] == 'boolean') { mergeTarget[option].enabled = options[option]; } else { mergeTarget[option].enabled = true; for (prop in options[option]) { if (options[option].hasOwnProperty(prop)) { mergeTarget[option][prop] = options[option][prop]; } } } } } /** * this is used to set the options of subobjects in the options object. A requirement of these subobjects * is that they have an 'enabled' element which is optional for the user but mandatory for the program. * * @param [object] mergeTarget | this is either this.options or the options used for the groups. * @param [object] options | options * @param [String] option | this is the option key in the options argument * @private */ exports.mergeOptions = function (mergeTarget, options, option) { if (options[option] !== undefined) { if (typeof options[option] == 'boolean') { mergeTarget[option].enabled = options[option]; } else { mergeTarget[option].enabled = true; for (prop in options[option]) { if (options[option].hasOwnProperty(prop)) { mergeTarget[option][prop] = options[option][prop]; } } } } } /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the RangeItem that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {Item[]} orderedItems Items ordered by start * @param {{start: number, end: number}} range * @param {String} field * @param {String} field2 * @returns {number} * @private */ exports.binarySearch = function(orderedItems, range, field, field2) { var array = orderedItems; var maxIterations = 10000; var iteration = 0; var found = false; var low = 0; var high = array.length; var newLow = low; var newHigh = high; var guess = Math.floor(0.5*(high+low)); var value; if (high == 0) { guess = -1; } else if (high == 1) { if (array[guess].isVisible(range)) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false && iteration < maxIterations) { value = field2 === undefined ? array[guess][field] : array[guess][field][field2]; if (array[guess].isVisible(range)) { found = true; } else { if (value < range.start) { // it is too small --> increase low newLow = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high newHigh = Math.floor(0.5*(high+low)); } // not in list; if (low == newLow && high == newHigh) { guess = -1; found = true; } else { high = newHigh; low = newLow; guess = Math.floor(0.5*(high+low)); } } iteration++; } if (iteration >= maxIterations) { console.log("BinarySearch too many iterations. Aborting."); } } return guess; }; /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the RangeItem that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {Array} orderedItems * @param {{start: number, end: number}} target * @param {String} field * @param {String} sidePreference 'before' or 'after' * @returns {number} * @private */ exports.binarySearchGeneric = function(orderedItems, target, field, sidePreference) { var maxIterations = 10000; var iteration = 0; var array = orderedItems; var found = false; var low = 0; var high = array.length; var newLow = low; var newHigh = high; var guess = Math.floor(0.5*(high+low)); var newGuess; var prevValue, value, nextValue; if (high == 0) {guess = -1;} else if (high == 1) { value = array[guess][field]; if (value == target) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false && iteration < maxIterations) { prevValue = array[Math.max(0,guess - 1)][field]; value = array[guess][field]; nextValue = array[Math.min(array.length-1,guess + 1)][field]; if (value == target || prevValue < target && value > target || value < target && nextValue > target) { found = true; if (value != target) { if (sidePreference == 'before') { if (prevValue < target && value > target) { guess = Math.max(0,guess - 1); } } else { if (value < target && nextValue > target) { guess = Math.min(array.length-1,guess + 1); } } } } else { if (value < target) { // it is too small --> increase low newLow = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high newHigh = Math.floor(0.5*(high+low)); } newGuess = Math.floor(0.5*(high+low)); // not in list; if (low == newLow && high == newHigh) { guess = -1; found = true; } else { high = newHigh; low = newLow; guess = Math.floor(0.5*(high+low)); } } iteration++; } if (iteration >= maxIterations) { console.log("BinarySearch too many iterations. Aborting."); } } return guess; }; /** * Quadratic ease-in-out * http://gizma.com/easing/ * @param {number} t Current time * @param {number} start Start value * @param {number} end End value * @param {number} duration Duration * @returns {number} Value corresponding with current time */ exports.easeInOutQuad = function (t, start, end, duration) { var change = end - start; t /= duration/2; if (t < 1) return change/2*t*t + start; t--; return -change/2 * (t*(t-2) - 1) + start; }; /* * Easing Functions - inspired from http://gizma.com/easing/ * only considering the t value for the range [0, 1] => [0, 1] * https://gist.github.com/gre/1650294 */ exports.easingFunctions = { // no easing, no acceleration linear: function (t) { return t }, // accelerating from zero velocity easeInQuad: function (t) { return t * t }, // decelerating to zero velocity easeOutQuad: function (t) { return t * (2 - t) }, // acceleration until halfway, then deceleration easeInOutQuad: function (t) { return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t }, // accelerating from zero velocity easeInCubic: function (t) { return t * t * t }, // decelerating to zero velocity easeOutCubic: function (t) { return (--t) * t * t + 1 }, // acceleration until halfway, then deceleration easeInOutCubic: function (t) { return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 }, // accelerating from zero velocity easeInQuart: function (t) { return t * t * t * t }, // decelerating to zero velocity easeOutQuart: function (t) { return 1 - (--t) * t * t * t }, // acceleration until halfway, then deceleration easeInOutQuart: function (t) { return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t }, // accelerating from zero velocity easeInQuint: function (t) { return t * t * t * t * t }, // decelerating to zero velocity easeOutQuint: function (t) { return 1 + (--t) * t * t * t * t }, // acceleration until halfway, then deceleration easeInOutQuint: function (t) { return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t } }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // DOM utility methods /** * this prepares the JSON container for allocating SVG elements * @param JSONcontainer * @private */ exports.prepareElements = function(JSONcontainer) { // cleanup the redundant svgElements; for (var elementType in JSONcontainer) { if (JSONcontainer.hasOwnProperty(elementType)) { JSONcontainer[elementType].redundant = JSONcontainer[elementType].used; JSONcontainer[elementType].used = []; } } }; /** * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from * which to remove the redundant elements. * * @param JSONcontainer * @private */ exports.cleanupElements = function(JSONcontainer) { // cleanup the redundant svgElements; for (var elementType in JSONcontainer) { if (JSONcontainer.hasOwnProperty(elementType)) { if (JSONcontainer[elementType].redundant) { for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) { JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]); } JSONcontainer[elementType].redundant = []; } } } }; /** * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this. * * @param elementType * @param JSONcontainer * @param svgContainer * @returns {*} * @private */ exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) { var element; // allocate SVG element, if it doesnt yet exist, create one. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before // check if there is an redundant element if (JSONcontainer[elementType].redundant.length > 0) { element = JSONcontainer[elementType].redundant[0]; JSONcontainer[elementType].redundant.shift(); } else { // create a new element and add it to the SVG element = document.createElementNS('http://www.w3.org/2000/svg', elementType); svgContainer.appendChild(element); } } else { // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it. element = document.createElementNS('http://www.w3.org/2000/svg', elementType); JSONcontainer[elementType] = {used: [], redundant: []}; svgContainer.appendChild(element); } JSONcontainer[elementType].used.push(element); return element; }; /** * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this. * * @param elementType * @param JSONcontainer * @param DOMContainer * @returns {*} * @private */ exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) { var element; // allocate DOM element, if it doesnt yet exist, create one. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before // check if there is an redundant element if (JSONcontainer[elementType].redundant.length > 0) { element = JSONcontainer[elementType].redundant[0]; JSONcontainer[elementType].redundant.shift(); } else { // create a new element and add it to the SVG element = document.createElement(elementType); if (insertBefore !== undefined) { DOMContainer.insertBefore(element, insertBefore); } else { DOMContainer.appendChild(element); } } } else { // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it. element = document.createElement(elementType); JSONcontainer[elementType] = {used: [], redundant: []}; if (insertBefore !== undefined) { DOMContainer.insertBefore(element, insertBefore); } else { DOMContainer.appendChild(element); } } JSONcontainer[elementType].used.push(element); return element; }; /** * draw a point object. this is a seperate function because it can also be called by the legend. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions * as well. * * @param x * @param y * @param group * @param JSONcontainer * @param svgContainer * @returns {*} */ exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) { var point; if (group.options.drawPoints.style == 'circle') { point = exports.getSVGElement('circle',JSONcontainer,svgContainer); point.setAttributeNS(null, "cx", x); point.setAttributeNS(null, "cy", y); point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size); point.setAttributeNS(null, "class", group.className + " point"); } else { point = exports.getSVGElement('rect',JSONcontainer,svgContainer); point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size); point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size); point.setAttributeNS(null, "width", group.options.drawPoints.size); point.setAttributeNS(null, "height", group.options.drawPoints.size); point.setAttributeNS(null, "class", group.className + " point"); } return point; }; /** * draw a bar SVG element centered on the X coordinate * * @param x * @param y * @param className */ exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) { // if (height != 0) { var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer); rect.setAttributeNS(null, "x", x - 0.5 * width); rect.setAttributeNS(null, "y", y); rect.setAttributeNS(null, "width", width); rect.setAttributeNS(null, "height", height); rect.setAttributeNS(null, "class", className); // } }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * DataSet * * Usage: * var dataSet = new DataSet({ * fieldId: '_id', * type: { * // ... * } * }); * * dataSet.add(item); * dataSet.add(data); * dataSet.update(item); * dataSet.update(data); * dataSet.remove(id); * dataSet.remove(ids); * var data = dataSet.get(); * var data = dataSet.get(id); * var data = dataSet.get(ids); * var data = dataSet.get(ids, options, data); * dataSet.clear(); * * A data set can: * - add/remove/update data * - gives triggers upon changes in the data * - can import/export data in various data formats * * @param {Array | DataTable} [data] Optional array with initial data * @param {Object} [options] Available options: * {String} fieldId Field name of the id in the * items, 'id' by default. * {Object.<String, String} type * A map with field names as key, * and the field type as value. * @constructor DataSet */ // TODO: add a DataSet constructor DataSet(data, options) function DataSet (data, options) { // correctly read optional arguments if (data && !Array.isArray(data) && !util.isDataTable(data)) { options = data; data = null; } this._options = options || {}; this._data = {}; // map with data indexed by id this._fieldId = this._options.fieldId || 'id'; // name of the field containing id this._type = {}; // internal field types (NOTE: this can differ from this._options.type) // all variants of a Date are internally stored as Date, so we can convert // from everything to everything (also from ISODate to Number for example) if (this._options.type) { for (var field in this._options.type) { if (this._options.type.hasOwnProperty(field)) { var value = this._options.type[field]; if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') { this._type[field] = 'Date'; } else { this._type[field] = value; } } } } // TODO: deprecated since version 1.1.1 (or 2.0.0?) if (this._options.convert) { throw new Error('Option "convert" is deprecated. Use "type" instead.'); } this._subscribers = {}; // event subscribers // add initial data when provided if (data) { this.add(data); } } /** * Subscribe to an event, add an event listener * @param {String} event Event name. Available events: 'put', 'update', * 'remove' * @param {function} callback Callback method. Called with three parameters: * {String} event * {Object | null} params * {String | Number} senderId */ DataSet.prototype.on = function(event, callback) { var subscribers = this._subscribers[event]; if (!subscribers) { subscribers = []; this._subscribers[event] = subscribers; } subscribers.push({ callback: callback }); }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.subscribe = DataSet.prototype.on; /** * Unsubscribe from an event, remove an event listener * @param {String} event * @param {function} callback */ DataSet.prototype.off = function(event, callback) { var subscribers = this._subscribers[event]; if (subscribers) { this._subscribers[event] = subscribers.filter(function (listener) { return (listener.callback != callback); }); } }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.unsubscribe = DataSet.prototype.off; /** * Trigger an event * @param {String} event * @param {Object | null} params * @param {String} [senderId] Optional id of the sender. * @private */ DataSet.prototype._trigger = function (event, params, senderId) { if (event == '*') { throw new Error('Cannot trigger event *'); } var subscribers = []; if (event in this._subscribers) { subscribers = subscribers.concat(this._subscribers[event]); } if ('*' in this._subscribers) { subscribers = subscribers.concat(this._subscribers['*']); } for (var i = 0; i < subscribers.length; i++) { var subscriber = subscribers[i]; if (subscriber.callback) { subscriber.callback(event, params, senderId || null); } } }; /** * Add data. * Adding an item will fail when there already is an item with the same id. * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} addedIds Array with the ids of the added items */ DataSet.prototype.add = function (data, senderId) { var addedIds = [], id, me = this; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { id = me._addItem(data[i]); addedIds.push(id); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } id = me._addItem(item); addedIds.push(id); } } else if (data instanceof Object) { // Single item id = me._addItem(data); addedIds.push(id); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } return addedIds; }; /** * Update existing items. When an item does not exist, it will be created * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} updatedIds The ids of the added or updated items */ DataSet.prototype.update = function (data, senderId) { var addedIds = [], updatedIds = [], me = this, fieldId = me._fieldId; var addOrUpdate = function (item) { var id = item[fieldId]; if (me._data[id]) { // update item id = me._updateItem(item); updatedIds.push(id); } else { // add new item id = me._addItem(item); addedIds.push(id); } }; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { addOrUpdate(data[i]); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } addOrUpdate(item); } } else if (data instanceof Object) { // Single item addOrUpdate(data); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } if (updatedIds.length) { this._trigger('update', {items: updatedIds}, senderId); } return addedIds.concat(updatedIds); }; /** * Get a data item or multiple items. * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number | String) * get(id: Number | String, options: Object) * get(id: Number | String, options: Object, data: Array | DataTable) * * get(ids: Number[] | String[]) * get(ids: Number[] | String[], options: Object) * get(ids: Number[] | String[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [returnType] Type of data to be * returned. Can be 'DataTable' or 'Array' (default) * {Object.<String, String>} [type] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * * @throws Error */ DataSet.prototype.get = function (args) { var me = this; // parse the arguments var id, ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number') { // get(id [, options] [, data]) id = arguments[0]; options = arguments[1]; data = arguments[2]; } else if (firstType == 'Array') { // get(ids [, options] [, data]) ids = arguments[0]; options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // determine the return type var returnType; if (options && options.returnType) { var allowedValues = ["DataTable", "Array", "Object"]; returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType; if (data && (returnType != util.getType(data))) { throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' + 'does not correspond with specified options.type (' + options.type + ')'); } if (returnType == 'DataTable' && !util.isDataTable(data)) { throw new Error('Parameter "data" must be a DataTable ' + 'when options.type is "DataTable"'); } } else if (data) { returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array'; } else { returnType = 'Array'; } // build options var type = options && options.type || this._options.type; var filter = options && options.filter; var items = [], item, itemId, i, len; // convert items if (id != undefined) { // return a single item item = me._getItem(id, type); if (filter && !filter(item)) { item = null; } } else if (ids != undefined) { // return a subset of items for (i = 0, len = ids.length; i < len; i++) { item = me._getItem(ids[i], type); if (!filter || filter(item)) { items.push(item); } } } else { // return all items for (itemId in this._data) { if (this._data.hasOwnProperty(itemId)) { item = me._getItem(itemId, type); if (!filter || filter(item)) { items.push(item); } } } } // order the results if (options && options.order && id == undefined) { this._sort(items, options.order); } // filter fields of the items if (options && options.fields) { var fields = options.fields; if (id != undefined) { item = this._filterFields(item, fields); } else { for (i = 0, len = items.length; i < len; i++) { items[i] = this._filterFields(items[i], fields); } } } // return the results if (returnType == 'DataTable') { var columns = this._getColumnNames(data); if (id != undefined) { // append a single item to the data table me._appendRow(data, columns, item); } else { // copy the items to the provided data table for (i = 0; i < items.length; i++) { me._appendRow(data, columns, items[i]); } } return data; } else if (returnType == "Object") { var result = {}; for (i = 0; i < items.length; i++) { result[items[i].id] = items[i]; } return result; } else { // return an array if (id != undefined) { // a single item return item; } else { // multiple items if (data) { // copy the items to the provided array for (i = 0, len = items.length; i < len; i++) { data.push(items[i]); } return data; } else { // just return our array return items; } } } }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataSet.prototype.getIds = function (options) { var data = this._data, filter = options && options.filter, order = options && options.order, type = options && options.type || this._options.type, i, len, id, item, items, ids = []; if (filter) { // get filtered items if (order) { // create ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { items.push(item); } } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { ids.push(item[this._fieldId]); } } } } } else { // get all items if (order) { // create an ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { items.push(data[id]); } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = data[id]; ids.push(item[this._fieldId]); } } } } return ids; }; /** * Returns the DataSet itself. Is overwritten for example by the DataView, * which returns the DataSet it is connected to instead. */ DataSet.prototype.getDataSet = function () { return this; }; /** * Execute a callback function for every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. */ DataSet.prototype.forEach = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, data = this._data, item, id; if (options && options.order) { // execute forEach on ordered list var items = this.get(options); for (var i = 0, len = items.length; i < len; i++) { item = items[i]; id = item[this._fieldId]; callback(item, id); } } else { // unordered for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { callback(item, id); } } } } }; /** * Map every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Object[]} mappedItems */ DataSet.prototype.map = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, mappedItems = [], data = this._data, item; // convert and filter items for (var id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { mappedItems.push(callback(item, id)); } } } // order items if (options && options.order) { this._sort(mappedItems, options.order); } return mappedItems; }; /** * Filter the fields of an item * @param {Object} item * @param {String[]} fields Field names * @return {Object} filteredItem * @private */ DataSet.prototype._filterFields = function (item, fields) { var filteredItem = {}; for (var field in item) { if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) { filteredItem[field] = item[field]; } } return filteredItem; }; /** * Sort the provided array with items * @param {Object[]} items * @param {String | function} order A field name or custom sort function. * @private */ DataSet.prototype._sort = function (items, order) { if (util.isString(order)) { // order by provided field name var name = order; // field name items.sort(function (a, b) { var av = a[name]; var bv = b[name]; return (av > bv) ? 1 : ((av < bv) ? -1 : 0); }); } else if (typeof order === 'function') { // order by sort function items.sort(order); } // TODO: extend order by an Object {field:String, direction:String} // where direction can be 'asc' or 'desc' else { throw new TypeError('Order must be a function or a string'); } }; /** * Remove an object by pointer or by id * @param {String | Number | Object | Array} id Object or id, or an array with * objects or ids to be removed * @param {String} [senderId] Optional sender id * @return {Array} removedIds */ DataSet.prototype.remove = function (id, senderId) { var removedIds = [], i, len, removedId; if (Array.isArray(id)) { for (i = 0, len = id.length; i < len; i++) { removedId = this._remove(id[i]); if (removedId != null) { removedIds.push(removedId); } } } else { removedId = this._remove(id); if (removedId != null) { removedIds.push(removedId); } } if (removedIds.length) { this._trigger('remove', {items: removedIds}, senderId); } return removedIds; }; /** * Remove an item by its id * @param {Number | String | Object} id id or item * @returns {Number | String | null} id * @private */ DataSet.prototype._remove = function (id) { if (util.isNumber(id) || util.isString(id)) { if (this._data[id]) { delete this._data[id]; return id; } } else if (id instanceof Object) { var itemId = id[this._fieldId]; if (itemId && this._data[itemId]) { delete this._data[itemId]; return itemId; } } return null; }; /** * Clear the data * @param {String} [senderId] Optional sender id * @return {Array} removedIds The ids of all removed items */ DataSet.prototype.clear = function (senderId) { var ids = Object.keys(this._data); this._data = {}; this._trigger('remove', {items: ids}, senderId); return ids; }; /** * Find the item with maximum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.max = function (field) { var data = this._data, max = null, maxField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!max || itemField > maxField)) { max = item; maxField = itemField; } } } return max; }; /** * Find the item with minimum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.min = function (field) { var data = this._data, min = null, minField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!min || itemField < minField)) { min = item; minField = itemField; } } } return min; }; /** * Find all distinct values of a specified field * @param {String} field * @return {Array} values Array containing all distinct values. If data items * do not contain the specified field are ignored. * The returned array is unordered. */ DataSet.prototype.distinct = function (field) { var data = this._data; var values = []; var fieldType = this._options.type && this._options.type[field] || null; var count = 0; var i; for (var prop in data) { if (data.hasOwnProperty(prop)) { var item = data[prop]; var value = item[field]; var exists = false; for (i = 0; i < count; i++) { if (values[i] == value) { exists = true; break; } } if (!exists && (value !== undefined)) { values[count] = value; count++; } } } if (fieldType) { for (i = 0; i < values.length; i++) { values[i] = util.convert(values[i], fieldType); } } return values; }; /** * Add a single item. Will fail when an item with the same id already exists. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._addItem = function (item) { var id = item[this._fieldId]; if (id != undefined) { // check whether this id is already taken if (this._data[id]) { // item already exists throw new Error('Cannot add item: item with id ' + id + ' already exists'); } } else { // generate an id id = util.randomUUID(); item[this._fieldId] = id; } var d = {}; for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } this._data[id] = d; return id; }; /** * Get an item. Fields can be converted to a specific type * @param {String} id * @param {Object.<String, String>} [types] field types to convert * @return {Object | null} item * @private */ DataSet.prototype._getItem = function (id, types) { var field, value; // get the item from the dataset var raw = this._data[id]; if (!raw) { return null; } // convert the items field types var converted = {}; if (types) { for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = util.convert(value, types[field]); } } } else { // no field types specified, no converting needed for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = value; } } } return converted; }; /** * Update a single item: merge with existing item. * Will fail when the item has no id, or when there does not exist an item * with the same id. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._updateItem = function (item) { var id = item[this._fieldId]; if (id == undefined) { throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')'); } var d = this._data[id]; if (!d) { // item doesn't exist throw new Error('Cannot update item: no item with id ' + id + ' found'); } // merge with current item for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } return id; }; /** * Get an array with the column names of a Google DataTable * @param {DataTable} dataTable * @return {String[]} columnNames * @private */ DataSet.prototype._getColumnNames = function (dataTable) { var columns = []; for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) { columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col); } return columns; }; /** * Append an item as a row to the dataTable * @param dataTable * @param columns * @param item * @private */ DataSet.prototype._appendRow = function (dataTable, columns, item) { var row = dataTable.addRow(); for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; dataTable.setValue(row, col, item[field]); } }; module.exports = DataSet; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DataSet = __webpack_require__(3); /** * DataView * * a dataview offers a filtered view on a dataset or an other dataview. * * @param {DataSet | DataView} data * @param {Object} [options] Available options: see method get * * @constructor DataView */ function DataView (data, options) { this._data = null; this._ids = {}; // ids of the items currently in memory (just contains a boolean true) this._options = options || {}; this._fieldId = 'id'; // name of the field containing id this._subscribers = {}; // event subscribers var me = this; this.listener = function () { me._onEvent.apply(me, arguments); }; this.setData(data); } // TODO: implement a function .config() to dynamically update things like configured filter // and trigger changes accordingly /** * Set a data source for the view * @param {DataSet | DataView} data */ DataView.prototype.setData = function (data) { var ids, i, len; if (this._data) { // unsubscribe from current dataset if (this._data.unsubscribe) { this._data.unsubscribe('*', this.listener); } // trigger a remove of all items in memory ids = []; for (var id in this._ids) { if (this._ids.hasOwnProperty(id)) { ids.push(id); } } this._ids = {}; this._trigger('remove', {items: ids}); } this._data = data; if (this._data) { // update fieldId this._fieldId = this._options.fieldId || (this._data && this._data.options && this._data.options.fieldId) || 'id'; // trigger an add of all added items ids = this._data.getIds({filter: this._options && this._options.filter}); for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; this._ids[id] = true; } this._trigger('add', {items: ids}); // subscribe to new dataset if (this._data.on) { this._data.on('*', this.listener); } } }; /** * Get data from the data view * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number) * get(id: Number, options: Object) * get(id: Number, options: Object, data: Array | DataTable) * * get(ids: Number[]) * get(ids: Number[], options: Object) * get(ids: Number[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [type] Type of data to be returned. Can * be 'DataTable' or 'Array' (default) * {Object.<String, String>} [convert] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * @param args */ DataView.prototype.get = function (args) { var me = this; // parse the arguments var ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') { // get(id(s) [, options] [, data]) ids = arguments[0]; // can be a single id or an array with ids options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // extend the options with the default options and provided options var viewOptions = util.extend({}, this._options, options); // create a combined filter method when needed if (this._options.filter && options && options.filter) { viewOptions.filter = function (item) { return me._options.filter(item) && options.filter(item); } } // build up the call to the linked data set var getArguments = []; if (ids != undefined) { getArguments.push(ids); } getArguments.push(viewOptions); getArguments.push(data); return this._data && this._data.get.apply(this._data, getArguments); }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataView.prototype.getIds = function (options) { var ids; if (this._data) { var defaultFilter = this._options.filter; var filter; if (options && options.filter) { if (defaultFilter) { filter = function (item) { return defaultFilter(item) && options.filter(item); } } else { filter = options.filter; } } else { filter = defaultFilter; } ids = this._data.getIds({ filter: filter, order: options && options.order }); } else { ids = []; } return ids; }; /** * Get the DataSet to which this DataView is connected. In case there is a chain * of multiple DataViews, the root DataSet of this chain is returned. * @return {DataSet} dataSet */ DataView.prototype.getDataSet = function () { var dataSet = this; while (dataSet instanceof DataView) { dataSet = dataSet._data; } return dataSet || null; }; /** * Event listener. Will propagate all events from the connected data set to * the subscribers of the DataView, but will filter the items and only trigger * when there are changes in the filtered data set. * @param {String} event * @param {Object | null} params * @param {String} senderId * @private */ DataView.prototype._onEvent = function (event, params, senderId) { var i, len, id, item, ids = params && params.items, data = this._data, added = [], updated = [], removed = []; if (ids && data) { switch (event) { case 'add': // filter the ids of the added items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { this._ids[id] = true; added.push(id); } } break; case 'update': // determine the event from the views viewpoint: an updated // item can be added, updated, or removed from this view. for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { if (this._ids[id]) { updated.push(id); } else { this._ids[id] = true; added.push(id); } } else { if (this._ids[id]) { delete this._ids[id]; removed.push(id); } else { // nothing interesting for me :-( } } } break; case 'remove': // filter the ids of the removed items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; if (this._ids[id]) { delete this._ids[id]; removed.push(id); } } break; } if (added.length) { this._trigger('add', {items: added}, senderId); } if (updated.length) { this._trigger('update', {items: updated}, senderId); } if (removed.length) { this._trigger('remove', {items: removed}, senderId); } } }; // copy subscription functionality from DataSet DataView.prototype.on = DataSet.prototype.on; DataView.prototype.off = DataSet.prototype.off; DataView.prototype._trigger = DataSet.prototype._trigger; // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5) DataView.prototype.subscribe = DataView.prototype.on; DataView.prototype.unsubscribe = DataView.prototype.off; module.exports = DataView; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(50); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var util = __webpack_require__(1); var Point3d = __webpack_require__(9); var Point2d = __webpack_require__(8); var Camera = __webpack_require__(6); var Filter = __webpack_require__(7); var Slider = __webpack_require__(10); var StepNumber = __webpack_require__(11); /** * @constructor Graph3d * Graph3d displays data in 3d. * * Graph3d is developed in javascript as a Google Visualization Chart. * * @param {Element} container The DOM element in which the Graph3d will * be created. Normally a div element. * @param {DataSet | DataView | Array} [data] * @param {Object} [options] */ function Graph3d(container, data, options) { if (!(this instanceof Graph3d)) { throw new SyntaxError('Constructor must be called with the new operator'); } // create variables and set default values this.containerElement = container; this.width = '400px'; this.height = '400px'; this.margin = 10; // px this.defaultXCenter = '55%'; this.defaultYCenter = '50%'; this.xLabel = 'x'; this.yLabel = 'y'; this.zLabel = 'z'; this.filterLabel = 'time'; this.legendLabel = 'value'; this.style = Graph3d.STYLE.DOT; this.showPerspective = true; this.showGrid = true; this.keepAspectRatio = true; this.showShadow = false; this.showGrayBottom = false; // TODO: this does not work correctly this.showTooltip = false; this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' this.animationInterval = 1000; // milliseconds this.animationPreload = false; this.camera = new Camera(); this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? this.dataTable = null; // The original data table this.dataPoints = null; // The table with point objects // the column indexes this.colX = undefined; this.colY = undefined; this.colZ = undefined; this.colValue = undefined; this.colFilter = undefined; this.xMin = 0; this.xStep = undefined; // auto by default this.xMax = 1; this.yMin = 0; this.yStep = undefined; // auto by default this.yMax = 1; this.zMin = 0; this.zStep = undefined; // auto by default this.zMax = 1; this.valueMin = 0; this.valueMax = 1; this.xBarWidth = 1; this.yBarWidth = 1; // TODO: customize axis range // constants this.colorAxis = '#4D4D4D'; this.colorGrid = '#D3D3D3'; this.colorDot = '#7DC1FF'; this.colorDotBorder = '#3267D2'; // create a frame and canvas this.create(); // apply options (also when undefined) this.setOptions(options); // apply data if (data) { this.setData(data); } } // Extend Graph3d with an Emitter mixin Emitter(Graph3d.prototype); /** * Calculate the scaling values, dependent on the range in x, y, and z direction */ Graph3d.prototype._setScale = function() { this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); // keep aspect ration between x and y scale if desired if (this.keepAspectRatio) { if (this.scale.x < this.scale.y) { //noinspection JSSuspiciousNameCombination this.scale.y = this.scale.x; } else { //noinspection JSSuspiciousNameCombination this.scale.x = this.scale.y; } } // scale the vertical axis this.scale.z *= this.verticalRatio; // TODO: can this be automated? verticalRatio? // determine scale for (optional) value this.scale.value = 1 / (this.valueMax - this.valueMin); // position the camera arm var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; this.camera.setArmLocation(xCenter, yCenter, zCenter); }; /** * Convert a 3D location to a 2D location on screen * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convert3Dto2D = function(point3d) { var translation = this._convertPointToTranslation(point3d); return this._convertTranslationToScreen(translation); }; /** * Convert a 3D location its translation seen from the camera * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera */ Graph3d.prototype._convertPointToTranslation = function(point3d) { var ax = point3d.x * this.scale.x, ay = point3d.y * this.scale.y, az = point3d.z * this.scale.z, cx = this.camera.getCameraLocation().x, cy = this.camera.getCameraLocation().y, cz = this.camera.getCameraLocation().z, // calculate angles sinTx = Math.sin(this.camera.getCameraRotation().x), cosTx = Math.cos(this.camera.getCameraRotation().x), sinTy = Math.sin(this.camera.getCameraRotation().y), cosTy = Math.cos(this.camera.getCameraRotation().y), sinTz = Math.sin(this.camera.getCameraRotation().z), cosTz = Math.cos(this.camera.getCameraRotation().z), // calculate translation dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)), dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx)); return new Point3d(dx, dy, dz); }; /** * Convert a translation point to a point on the screen * @param {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convertTranslationToScreen = function(translation) { var ex = this.eye.x, ey = this.eye.y, ez = this.eye.z, dx = translation.x, dy = translation.y, dz = translation.z; // calculate position on screen from translation var bx; var by; if (this.showPerspective) { bx = (dx - ex) * (ez / dz); by = (dy - ey) * (ez / dz); } else { bx = dx * -(ez / this.camera.getArmLength()); by = dy * -(ez / this.camera.getArmLength()); } // shift and scale the point to the center of the screen // use the width of the graph to scale both horizontally and vertically. return new Point2d( this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); }; /** * Set the background styling for the graph * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor */ Graph3d.prototype._setBackgroundColor = function(backgroundColor) { var fill = 'white'; var stroke = 'gray'; var strokeWidth = 1; if (typeof(backgroundColor) === 'string') { fill = backgroundColor; stroke = 'none'; strokeWidth = 0; } else if (typeof(backgroundColor) === 'object') { if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; } else if (backgroundColor === undefined) { // use use defaults } else { throw 'Unsupported type of backgroundColor'; } this.frame.style.backgroundColor = fill; this.frame.style.borderColor = stroke; this.frame.style.borderWidth = strokeWidth + 'px'; this.frame.style.borderStyle = 'solid'; }; /// enumerate the available styles Graph3d.STYLE = { BAR: 0, BARCOLOR: 1, BARSIZE: 2, DOT : 3, DOTLINE : 4, DOTCOLOR: 5, DOTSIZE: 6, GRID : 7, LINE: 8, SURFACE : 9 }; /** * Retrieve the style index from given styleName * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line' * @return {Number} styleNumber Enumeration value representing the style, or -1 * when not found */ Graph3d.prototype._getStyleNumber = function(styleName) { switch (styleName) { case 'dot': return Graph3d.STYLE.DOT; case 'dot-line': return Graph3d.STYLE.DOTLINE; case 'dot-color': return Graph3d.STYLE.DOTCOLOR; case 'dot-size': return Graph3d.STYLE.DOTSIZE; case 'line': return Graph3d.STYLE.LINE; case 'grid': return Graph3d.STYLE.GRID; case 'surface': return Graph3d.STYLE.SURFACE; case 'bar': return Graph3d.STYLE.BAR; case 'bar-color': return Graph3d.STYLE.BARCOLOR; case 'bar-size': return Graph3d.STYLE.BARSIZE; } return -1; }; /** * Determine the indexes of the data columns, based on the given style and data * @param {DataSet} data * @param {Number} style */ Graph3d.prototype._determineColumnIndexes = function(data, style) { if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { // 3 columns expected, and optionally a 4th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = undefined; if (data.getNumberOfColumns() > 3) { this.colFilter = 3; } } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // 4 columns expected, and optionally a 5th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = 3; if (data.getNumberOfColumns() > 4) { this.colFilter = 4; } } else { throw 'Unknown style "' + this.style + '"'; } }; Graph3d.prototype.getNumberOfRows = function(data) { return data.length; } Graph3d.prototype.getNumberOfColumns = function(data) { var counter = 0; for (var column in data[0]) { if (data[0].hasOwnProperty(column)) { counter++; } } return counter; } Graph3d.prototype.getDistinctValues = function(data, column) { var distinctValues = []; for (var i = 0; i < data.length; i++) { if (distinctValues.indexOf(data[i][column]) == -1) { distinctValues.push(data[i][column]); } } return distinctValues; } Graph3d.prototype.getColumnRange = function(data,column) { var minMax = {min:data[0][column],max:data[0][column]}; for (var i = 0; i < data.length; i++) { if (minMax.min > data[i][column]) { minMax.min = data[i][column]; } if (minMax.max < data[i][column]) { minMax.max = data[i][column]; } } return minMax; }; /** * Initialize the data from the data table. Calculate minimum and maximum values * and column index values * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. * @param {Number} style Style Number */ Graph3d.prototype._dataInitialize = function (rawData, style) { var me = this; // unsubscribe from the dataTable if (this.dataSet) { this.dataSet.off('*', this._onChange); } if (rawData === undefined) return; if (Array.isArray(rawData)) { rawData = new DataSet(rawData); } var data; if (rawData instanceof DataSet || rawData instanceof DataView) { data = rawData.get(); } else { throw new Error('Array, DataSet, or DataView expected'); } if (data.length == 0) return; this.dataSet = rawData; this.dataTable = data; // subscribe to changes in the dataset this._onChange = function () { me.setData(me.dataSet); }; this.dataSet.on('*', this._onChange); // _determineColumnIndexes // getNumberOfRows (points) // getNumberOfColumns (x,y,z,v,t,t1,t2...) // getDistinctValues (unique values?) // getColumnRange // determine the location of x,y,z,value,filter columns this.colX = 'x'; this.colY = 'y'; this.colZ = 'z'; this.colValue = 'style'; this.colFilter = 'filter'; // check if a filter column is provided if (data[0].hasOwnProperty('filter')) { if (this.dataFilter === undefined) { this.dataFilter = new Filter(rawData, this.colFilter, this); this.dataFilter.setOnLoadCallback(function() {me.redraw();}); } } var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; // determine barWidth from data if (withBars) { if (this.defaultXBarWidth !== undefined) { this.xBarWidth = this.defaultXBarWidth; } else { var dataX = this.getDistinctValues(data,this.colX); this.xBarWidth = (dataX[1] - dataX[0]) || 1; } if (this.defaultYBarWidth !== undefined) { this.yBarWidth = this.defaultYBarWidth; } else { var dataY = this.getDistinctValues(data,this.colY); this.yBarWidth = (dataY[1] - dataY[0]) || 1; } } // calculate minimums and maximums var xRange = this.getColumnRange(data,this.colX); if (withBars) { xRange.min -= this.xBarWidth / 2; xRange.max += this.xBarWidth / 2; } this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min; this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max; if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5; var yRange = this.getColumnRange(data,this.colY); if (withBars) { yRange.min -= this.yBarWidth / 2; yRange.max += this.yBarWidth / 2; } this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min; this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max; if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5; var zRange = this.getColumnRange(data,this.colZ); this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min; this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max; if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5; if (this.colValue !== undefined) { var valueRange = this.getColumnRange(data,this.colValue); this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min; this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max; if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; } // set the scale dependent on the ranges. this._setScale(); }; /** * Filter the data based on the current filter * @param {Array} data * @return {Array} dataPoints Array with point objects which can be drawn on screen */ Graph3d.prototype._getDataPoints = function (data) { // TODO: store the created matrix dataPoints in the filters instead of reloading each time var x, y, i, z, obj, point; var dataPoints = []; if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { // copy all values from the google data table to a matrix // the provided values are supposed to form a grid of (x,y) positions // create two lists with all present x and y values var dataX = []; var dataY = []; for (i = 0; i < this.getNumberOfRows(data); i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; if (dataX.indexOf(x) === -1) { dataX.push(x); } if (dataY.indexOf(y) === -1) { dataY.push(y); } } function sortNumber(a, b) { return a - b; } dataX.sort(sortNumber); dataY.sort(sortNumber); // create a grid, a 2d matrix, with all values. var dataMatrix = []; // temporary data matrix for (i = 0; i < data.length; i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; z = data[i][this.colZ] || 0; var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer var yIndex = dataY.indexOf(y); if (dataMatrix[xIndex] === undefined) { dataMatrix[xIndex] = []; } var point3d = new Point3d(); point3d.x = x; point3d.y = y; point3d.z = z; obj = {}; obj.point = point3d; obj.trans = undefined; obj.screen = undefined; obj.bottom = new Point3d(x, y, this.zMin); dataMatrix[xIndex][yIndex] = obj; dataPoints.push(obj); } // fill in the pointers to the neighbors. for (x = 0; x < dataMatrix.length; x++) { for (y = 0; y < dataMatrix[x].length; y++) { if (dataMatrix[x][y]) { dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined; dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined; dataMatrix[x][y].pointCross = (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ? dataMatrix[x+1][y+1] : undefined; } } } } else { // 'dot', 'dot-line', etc. // copy all values from the google data table to a list with Point3d objects for (i = 0; i < data.length; i++) { point = new Point3d(); point.x = data[i][this.colX] || 0; point.y = data[i][this.colY] || 0; point.z = data[i][this.colZ] || 0; if (this.colValue !== undefined) { point.value = data[i][this.colValue] || 0; } obj = {}; obj.point = point; obj.bottom = new Point3d(point.x, point.y, this.zMin); obj.trans = undefined; obj.screen = undefined; dataPoints.push(obj); } } return dataPoints; }; /** * Create the main frame for the Graph3d. * This function is executed once when a Graph3d object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. */ Graph3d.prototype.create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the graph canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); //if (!this.frame.canvas.getContext) { { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } this.frame.filter = document.createElement( 'div' ); this.frame.filter.style.position = 'absolute'; this.frame.filter.style.bottom = '0px'; this.frame.filter.style.left = '0px'; this.frame.filter.style.width = '100%'; this.frame.appendChild(this.frame.filter); // add event listeners to handle moving and zooming the contents var me = this; var onmousedown = function (event) {me._onMouseDown(event);}; var ontouchstart = function (event) {me._onTouchStart(event);}; var onmousewheel = function (event) {me._onWheel(event);}; var ontooltip = function (event) {me._onTooltip(event);}; // TODO: these events are never cleaned up... can give a 'memory leakage' util.addEventListener(this.frame.canvas, 'keydown', onkeydown); util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); // add the new graph to the container element this.containerElement.appendChild(this.frame); }; /** * Set a new size for the graph * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Graph3d.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this._resizeCanvas(); }; /** * Resize the canvas to the current size of the frame */ Graph3d.prototype._resizeCanvas = function() { this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; // adjust with for margin this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px'; }; /** * Start animation */ Graph3d.prototype.animationStart = function() { if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; this.frame.filter.slider.play(); }; /** * Stop animation */ Graph3d.prototype.animationStop = function() { if (!this.frame.filter || !this.frame.filter.slider) return; this.frame.filter.slider.stop(); }; /** * Resize the center position based on the current values in this.defaultXCenter * and this.defaultYCenter (which are strings with a percentage or a value * in pixels). The center positions are the variables this.xCenter * and this.yCenter */ Graph3d.prototype._resizeCenter = function() { // calculate the horizontal center position if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') { this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; } else { this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px } // calculate the vertical center position if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') { this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); } else { this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px } }; /** * Set the rotation and distance of the camera * @param {Object} pos An object with the camera position. The object * contains three parameters: * - horizontal {Number} * The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * - vertical {Number} * The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. * - distance {Number} * The (normalized) distance of the camera to the * center of the graph, a value between 0.71 and 5.0. * Optional, can be left undefined. */ Graph3d.prototype.setCameraPosition = function(pos) { if (pos === undefined) { return; } if (pos.horizontal !== undefined && pos.vertical !== undefined) { this.camera.setArmRotation(pos.horizontal, pos.vertical); } if (pos.distance !== undefined) { this.camera.setArmLength(pos.distance); } this.redraw(); }; /** * Retrieve the current camera rotation * @return {object} An object with parameters horizontal, vertical, and * distance */ Graph3d.prototype.getCameraPosition = function() { var pos = this.camera.getArmRotation(); pos.distance = this.camera.getArmLength(); return pos; }; /** * Load data into the 3D Graph */ Graph3d.prototype._readData = function(data) { // read the data this._dataInitialize(data, this.style); if (this.dataFilter) { // apply filtering this.dataPoints = this.dataFilter._getDataPoints(); } else { // no filtering. load all data this.dataPoints = this._getDataPoints(this.dataTable); } // draw the filter this._redrawFilter(); }; /** * Replace the dataset of the Graph3d * @param {Array | DataSet | DataView} data */ Graph3d.prototype.setData = function (data) { this._readData(data); this.redraw(); // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Update the options. Options will be merged with current options * @param {Object} options */ Graph3d.prototype.setOptions = function (options) { var cameraPosition = undefined; this.animationStop(); if (options !== undefined) { // retrieve parameter values if (options.width !== undefined) this.width = options.width; if (options.height !== undefined) this.height = options.height; if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; if (options.xLabel !== undefined) this.xLabel = options.xLabel; if (options.yLabel !== undefined) this.yLabel = options.yLabel; if (options.zLabel !== undefined) this.zLabel = options.zLabel; if (options.style !== undefined) { var styleNumber = this._getStyleNumber(options.style); if (styleNumber !== -1) { this.style = styleNumber; } } if (options.showGrid !== undefined) this.showGrid = options.showGrid; if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; if (options.showShadow !== undefined) this.showShadow = options.showShadow; if (options.tooltip !== undefined) this.showTooltip = options.tooltip; if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart; if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; if (options.xMin !== undefined) this.defaultXMin = options.xMin; if (options.xStep !== undefined) this.defaultXStep = options.xStep; if (options.xMax !== undefined) this.defaultXMax = options.xMax; if (options.yMin !== undefined) this.defaultYMin = options.yMin; if (options.yStep !== undefined) this.defaultYStep = options.yStep; if (options.yMax !== undefined) this.defaultYMax = options.yMax; if (options.zMin !== undefined) this.defaultZMin = options.zMin; if (options.zStep !== undefined) this.defaultZStep = options.zStep; if (options.zMax !== undefined) this.defaultZMax = options.zMax; if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; if (cameraPosition !== undefined) { this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); this.camera.setArmLength(cameraPosition.distance); } else { this.camera.setArmRotation(1.0, 0.5); this.camera.setArmLength(1.7); } } this._setBackgroundColor(options && options.backgroundColor); this.setSize(this.width, this.height); // re-load the data if (this.dataTable) { this.setData(this.dataTable); } // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Redraw the Graph. */ Graph3d.prototype.redraw = function() { if (this.dataPoints === undefined) { throw 'Error: graph data not initialized'; } this._resizeCanvas(); this._resizeCenter(); this._redrawSlider(); this._redrawClear(); this._redrawAxis(); if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { this._redrawDataGrid(); } else if (this.style === Graph3d.STYLE.LINE) { this._redrawDataLine(); } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { this._redrawDataBar(); } else { // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE this._redrawDataDot(); } this._redrawInfo(); this._redrawLegend(); }; /** * Clear the canvas before redrawing */ Graph3d.prototype._redrawClear = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); }; /** * Redraw the legend showing the colors */ Graph3d.prototype._redrawLegend = function() { var y; if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { var dotSize = this.frame.clientWidth * 0.02; var widthMin, widthMax; if (this.style === Graph3d.STYLE.DOTSIZE) { widthMin = dotSize / 2; // px widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function } else { widthMin = 20; // px widthMax = 20; // px } var height = Math.max(this.frame.clientHeight * 0.25, 100); var top = this.margin; var right = this.frame.clientWidth - this.margin; var left = right - widthMax; var bottom = top + height; } var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.lineWidth = 1; ctx.font = '14px arial'; // TODO: put in options if (this.style === Graph3d.STYLE.DOTCOLOR) { // draw the color bar var ymin = 0; var ymax = height; // Todo: make height customizable for (y = ymin; y < ymax; y++) { var f = (y - ymin) / (ymax - ymin); //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function var hue = f * 240; var color = this._hsv2rgb(hue, 1, 1); ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(left, top + y); ctx.lineTo(right, top + y); ctx.stroke(); } ctx.strokeStyle = this.colorAxis; ctx.strokeRect(left, top, widthMax, height); } if (this.style === Graph3d.STYLE.DOTSIZE) { // draw border around color bar ctx.strokeStyle = this.colorAxis; ctx.fillStyle = this.colorDot; ctx.beginPath(); ctx.moveTo(left, top); ctx.lineTo(right, top); ctx.lineTo(right - widthMax + widthMin, bottom); ctx.lineTo(left, bottom); ctx.closePath(); ctx.fill(); ctx.stroke(); } if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { // print values along the color bar var gridLineLen = 5; // px var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true); step.start(); if (step.getCurrent() < this.valueMin) { step.next(); } while (!step.end()) { y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; ctx.beginPath(); ctx.moveTo(left - gridLineLen, y); ctx.lineTo(left, y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); step.next(); } ctx.textAlign = 'right'; ctx.textBaseline = 'top'; var label = this.legendLabel; ctx.fillText(label, right, bottom + this.margin); } }; /** * Redraw the filter */ Graph3d.prototype._redrawFilter = function() { this.frame.filter.innerHTML = ''; if (this.dataFilter) { var options = { 'visible': this.showAnimationControls }; var slider = new Slider(this.frame.filter, options); this.frame.filter.slider = slider; // TODO: css here is not nice here... this.frame.filter.style.padding = '10px'; //this.frame.filter.style.backgroundColor = '#EFEFEF'; slider.setValues(this.dataFilter.values); slider.setPlayInterval(this.animationInterval); // create an event handler var me = this; var onchange = function () { var index = slider.getIndex(); me.dataFilter.selectValue(index); me.dataPoints = me.dataFilter._getDataPoints(); me.redraw(); }; slider.setOnChangeCallback(onchange); } else { this.frame.filter.slider = undefined; } }; /** * Redraw the slider */ Graph3d.prototype._redrawSlider = function() { if ( this.frame.filter.slider !== undefined) { this.frame.filter.slider.redraw(); } }; /** * Redraw common information */ Graph3d.prototype._redrawInfo = function() { if (this.dataFilter) { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.font = '14px arial'; // TODO: put in options ctx.lineStyle = 'gray'; ctx.fillStyle = 'gray'; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var x = this.margin; var y = this.margin; ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); } }; /** * Redraw the axis */ Graph3d.prototype._redrawAxis = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), from, to, step, prettyStep, text, xText, yText, zText, offset, xOffset, yOffset, xMin2d, xMax2d; // TODO: get the actual rendered style of the containerElement //ctx.font = this.containerElement.style.font; ctx.font = 24 / this.camera.getArmLength() + 'px arial'; // calculate the length for the short grid lines var gridLenX = 0.025 / this.scale.x; var gridLenY = 0.025 / this.scale.y; var textMargin = 5 / this.camera.getArmLength(); // px var armAngle = this.camera.getArmRotation().horizontal; // draw x-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultXStep === undefined); step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); step.start(); if (step.getCurrent() < this.xMin) { step.next(); } while (!step.end()) { var x = step.getCurrent(); if (this.showGrid) { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax; text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw y-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultYStep === undefined); step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); step.start(); if (step.getCurrent() < this.yMin) { step.next(); } while (!step.end()) { if (this.showGrid) { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax; text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw z-grid lines and axis ctx.lineWidth = 1; prettyStep = (this.defaultZStep === undefined); step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); step.start(); if (step.getCurrent() < this.zMin) { step.next(); } xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; while (!step.end()) { // TODO: make z-grid lines really 3d? from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(from.x - textMargin, from.y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent() + ' ', from.x - 5, from.y); step.next(); } ctx.lineWidth = 1; from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-axis ctx.lineWidth = 1; // line at yMin xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // line at ymax xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // draw y-axis ctx.lineWidth = 1; // line at xMin from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // line at xMax from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-label var xLabel = this.xLabel; if (xLabel.length > 0) { yOffset = 0.1 / this.scale.y; xText = (this.xMin + this.xMax) / 2; yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(xLabel, text.x, text.y); } // draw y-label var yLabel = this.yLabel; if (yLabel.length > 0) { xOffset = 0.1 / this.scale.x; xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset; yText = (this.yMin + this.yMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(yLabel, text.x, text.y); } // draw z-label var zLabel = this.zLabel; if (zLabel.length > 0) { offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; zText = (this.zMin + this.zMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, zText)); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(zLabel, text.x - offset, text.y); } }; /** * Calculate the color based on the given value. * @param {Number} H Hue, a value be between 0 and 360 * @param {Number} S Saturation, a value between 0 and 1 * @param {Number} V Value, a value between 0 and 1 */ Graph3d.prototype._hsv2rgb = function(H, S, V) { var R, G, B, C, Hi, X; C = V * S; Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5 X = C * (1 - Math.abs(((H/60) % 2) - 1)); switch (Hi) { case 0: R = C; G = X; B = 0; break; case 1: R = X; G = C; B = 0; break; case 2: R = 0; G = C; B = X; break; case 3: R = 0; G = X; B = C; break; case 4: R = X; G = 0; B = C; break; case 5: R = C; G = 0; B = X; break; default: R = 0; G = 0; B = 0; break; } return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')'; }; /** * Draw all datapoints as a grid * This function can be used when the style is 'grid' */ Graph3d.prototype._redrawDataGrid = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, right, top, cross, i, topSideVisible, fillStyle, strokeStyle, lineWidth, h, s, v, zAvg; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations and screen position of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the translation of the point at the bottom (needed for sorting) var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // sort the points on depth of their (x,y) position (not on z) var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); if (this.style === Graph3d.STYLE.SURFACE) { for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; cross = this.dataPoints[i].pointCross; if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { if (this.showGrayBottom || this.showShadow) { // calculate the cross product of the two vectors from center // to left and right, in order to know whether we are looking at the // bottom or at the top side. We can also use the cross product // for calculating light intensity var aDiff = Point3d.subtract(cross.trans, point.trans); var bDiff = Point3d.subtract(top.trans, right.trans); var crossproduct = Point3d.crossProduct(aDiff, bDiff); var len = crossproduct.length(); // FIXME: there is a bug with determining the surface side (shadow or colored) topSideVisible = (crossproduct.z > 0); } else { topSideVisible = true; } if (topSideVisible) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; s = 1; // saturation if (this.showShadow) { v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale fillStyle = this._hsv2rgb(h, s, v); strokeStyle = fillStyle; } else { v = 1; fillStyle = this._hsv2rgb(h, s, v); strokeStyle = this.colorAxis; } } else { fillStyle = 'gray'; strokeStyle = this.colorAxis; } lineWidth = 0.5; ctx.lineWidth = lineWidth; ctx.fillStyle = fillStyle; ctx.strokeStyle = strokeStyle; ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.lineTo(cross.screen.x, cross.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.closePath(); ctx.fill(); ctx.stroke(); } } } else { // grid style for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; if (point !== undefined) { if (this.showPerspective) { lineWidth = 2 / -point.trans.z; } else { lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); } } if (point !== undefined && right !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.stroke(); } if (point !== undefined && top !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + top.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.stroke(); } } } }; /** * Draw all datapoints as dots. * This function can be used when the style is 'dot' or 'dot-line' */ Graph3d.prototype._redrawDataDot = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as colored circles var dotSize = this.frame.clientWidth * 0.02; // px for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; if (this.style === Graph3d.STYLE.DOTLINE) { // draw a vertical line from the bottom to the graph value //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); var from = this._convert3Dto2D(point.bottom); ctx.lineWidth = 1; ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(point.screen.x, point.screen.y); ctx.stroke(); } // calculate radius for the circle var size; if (this.style === Graph3d.STYLE.DOTSIZE) { size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); } else { size = dotSize; } var radius; if (this.showPerspective) { radius = size / -point.trans.z; } else { radius = size * -(this.eye.z / this.camera.getArmLength()); } if (radius < 0) { radius = 0; } var hue, color, borderColor; if (this.style === Graph3d.STYLE.DOTCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.DOTSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // draw the circle ctx.lineWidth = 1.0; ctx.strokeStyle = borderColor; ctx.fillStyle = color; ctx.beginPath(); ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true); ctx.fill(); ctx.stroke(); } }; /** * Draw all datapoints as bars. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' */ Graph3d.prototype._redrawDataBar = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i, j, surface, corners; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as bars var xWidth = this.xBarWidth / 2; var yWidth = this.yBarWidth / 2; for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; // determine color var hue, color, borderColor; if (this.style === Graph3d.STYLE.BARCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.BARSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // calculate size for the bar if (this.style === Graph3d.STYLE.BARSIZE) { xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); } // calculate all corner points var me = this; var point3d = point.point; var top = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)} ]; var bottom = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)} ]; // calculate screen location of the points top.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); bottom.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); // create five sides, calculate both corner points and center points var surfaces = [ {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)}, {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)}, {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)}, {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)}, {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)} ]; point.surfaces = surfaces; // calculate the distance of each of the surface centers to the camera for (j = 0; j < surfaces.length; j++) { surface = surfaces[j]; var transCenter = this._convertPointToTranslation(surface.center); surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; // TODO: this dept calculation doesn't work 100% of the cases due to perspective, // but the current solution is fast/simple and works in 99.9% of all cases // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) } // order the surfaces by their (translated) depth surfaces.sort(function (a, b) { var diff = b.dist - a.dist; if (diff) return diff; // if equal depth, sort the top surface last if (a.corners === top) return 1; if (b.corners === top) return -1; // both are equal return 0; }); // draw the ordered surfaces ctx.lineWidth = 1; ctx.strokeStyle = borderColor; ctx.fillStyle = color; // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside for (j = 2; j < surfaces.length; j++) { surface = surfaces[j]; corners = surface.corners; ctx.beginPath(); ctx.moveTo(corners[3].screen.x, corners[3].screen.y); ctx.lineTo(corners[0].screen.x, corners[0].screen.y); ctx.lineTo(corners[1].screen.x, corners[1].screen.y); ctx.lineTo(corners[2].screen.x, corners[2].screen.y); ctx.lineTo(corners[3].screen.x, corners[3].screen.y); ctx.fill(); ctx.stroke(); } } }; /** * Draw a line through all datapoints. * This function can be used when the style is 'line' */ Graph3d.prototype._redrawDataLine = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; } // start the line if (this.dataPoints.length > 0) { point = this.dataPoints[0]; ctx.lineWidth = 1; // TODO: make customizable ctx.strokeStyle = 'blue'; // TODO: make customizable ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); } // draw the datapoints as colored circles for (i = 1; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; ctx.lineTo(point.screen.x, point.screen.y); } // finish the line if (this.dataPoints.length > 0) { ctx.stroke(); } }; /** * Start a moving operation inside the provided parent element * @param {Event} event The event that occurred (required for * retrieving the mouse position) */ Graph3d.prototype._onMouseDown = function(event) { event = event || window.event; // check if mouse is still down (may be up when focus is lost for example // in an iframe) if (this.leftButtonDown) { this._onMouseUp(event); } // only react on left mouse button down this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!this.leftButtonDown && !this.touchDown) return; // get mouse position (different code for IE and all other browsers) this.startMouseX = getMouseX(event); this.startMouseY = getMouseY(event); this.startStart = new Date(this.start); this.startEnd = new Date(this.end); this.startArmRotation = this.camera.getArmRotation(); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; util.addEventListener(document, 'mousemove', me.onmousemove); util.addEventListener(document, 'mouseup', me.onmouseup); util.preventDefault(event); }; /** * Perform moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {Event} event Well, eehh, the event */ Graph3d.prototype._onMouseMove = function (event) { event = event || window.event; // calculate change in mouse position var diffX = parseFloat(getMouseX(event)) - this.startMouseX; var diffY = parseFloat(getMouseY(event)) - this.startMouseY; var horizontalNew = this.startArmRotation.horizontal + diffX / 200; var verticalNew = this.startArmRotation.vertical + diffY / 200; var snapAngle = 4; // degrees var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... // the -0.001 is to take care that the vertical axis is always drawn at the left front corner if (Math.abs(Math.sin(horizontalNew)) < snapValue) { horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001; } if (Math.abs(Math.cos(horizontalNew)) < snapValue) { horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001; } // snap vertically to nice angles if (Math.abs(Math.sin(verticalNew)) < snapValue) { verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI; } if (Math.abs(Math.cos(verticalNew)) < snapValue) { verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI; } this.camera.setArmRotation(horizontalNew, verticalNew); this.redraw(); // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); util.preventDefault(event); }; /** * Stop moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {event} event The event */ Graph3d.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; this.leftButtonDown = false; // remove event listeners here util.removeEventListener(document, 'mousemove', this.onmousemove); util.removeEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(event); }; /** * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point * @param {Event} event A mouse move event */ Graph3d.prototype._onTooltip = function (event) { var delay = 300; // ms var mouseX = getMouseX(event) - util.getAbsoluteLeft(this.frame); var mouseY = getMouseY(event) - util.getAbsoluteTop(this.frame); if (!this.showTooltip) { return; } if (this.tooltipTimeout) { clearTimeout(this.tooltipTimeout); } // (delayed) display of a tooltip only if no mouse button is down if (this.leftButtonDown) { this._hideTooltip(); return; } if (this.tooltip && this.tooltip.dataPoint) { // tooltip is currently visible var dataPoint = this._dataPointFromXY(mouseX, mouseY); if (dataPoint !== this.tooltip.dataPoint) { // datapoint changed if (dataPoint) { this._showTooltip(dataPoint); } else { this._hideTooltip(); } } } else { // tooltip is currently not visible var me = this; this.tooltipTimeout = setTimeout(function () { me.tooltipTimeout = null; // show a tooltip if we have a data point var dataPoint = me._dataPointFromXY(mouseX, mouseY); if (dataPoint) { me._showTooltip(dataPoint); } }, delay); } }; /** * Event handler for touchstart event on mobile devices */ Graph3d.prototype._onTouchStart = function(event) { this.touchDown = true; var me = this; this.ontouchmove = function (event) {me._onTouchMove(event);}; this.ontouchend = function (event) {me._onTouchEnd(event);}; util.addEventListener(document, 'touchmove', me.ontouchmove); util.addEventListener(document, 'touchend', me.ontouchend); this._onMouseDown(event); }; /** * Event handler for touchmove event on mobile devices */ Graph3d.prototype._onTouchMove = function(event) { this._onMouseMove(event); }; /** * Event handler for touchend event on mobile devices */ Graph3d.prototype._onTouchEnd = function(event) { this.touchDown = false; util.removeEventListener(document, 'touchmove', this.ontouchmove); util.removeEventListener(document, 'touchend', this.ontouchend); this._onMouseUp(event); }; /** * Event handler for mouse wheel event, used to zoom the graph * Code from http://adomas.org/javascript-mouse-wheel/ * @param {event} event The event */ Graph3d.prototype._onWheel = function(event) { if (!event) /* For IE. */ event = window.event; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { var oldLength = this.camera.getArmLength(); var newLength = oldLength * (1 - delta / 10); this.camera.setArmLength(newLength); this.redraw(); this._hideTooltip(); } // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); // Prevent default actions caused by mouse wheel. // That might be ugly, but we handle scrolls somehow // anyway, so don't bother here.. util.preventDefault(event); }; /** * Test whether a point lies inside given 2D triangle * @param {Point2d} point * @param {Point2d[]} triangle * @return {boolean} Returns true if given point lies inside or on the edge of the triangle * @private */ Graph3d.prototype._insideTriangle = function (point, triangle) { var a = triangle[0], b = triangle[1], c = triangle[2]; function sign (x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); // each of the three signs must be either equal to each other or zero return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); }; /** * Find a data point close to given screen position (x, y) * @param {Number} x * @param {Number} y * @return {Object | null} The closest data point or null if not close to any data point * @private */ Graph3d.prototype._dataPointFromXY = function (x, y) { var i, distMax = 100, // px dataPoint = null, closestDataPoint = null, closestDist = null, center = new Point2d(x, y); if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // the data points are ordered from far away to closest for (i = this.dataPoints.length - 1; i >= 0; i--) { dataPoint = this.dataPoints[i]; var surfaces = dataPoint.surfaces; if (surfaces) { for (var s = surfaces.length - 1; s >= 0; s--) { // split each surface in two triangles, and see if the center point is inside one of these var surface = surfaces[s]; var corners = surface.corners; var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { // return immediately at the first hit return dataPoint; } } } } } else { // find the closest data point, using distance to the center of the point on 2d screen for (i = 0; i < this.dataPoints.length; i++) { dataPoint = this.dataPoints[i]; var point = dataPoint.screen; if (point) { var distX = Math.abs(x - point.x); var distY = Math.abs(y - point.y); var dist = Math.sqrt(distX * distX + distY * distY); if ((closestDist === null || dist < closestDist) && dist < distMax) { closestDist = dist; closestDataPoint = dataPoint; } } } } return closestDataPoint; }; /** * Display a tooltip for given data point * @param {Object} dataPoint * @private */ Graph3d.prototype._showTooltip = function (dataPoint) { var content, line, dot; if (!this.tooltip) { content = document.createElement('div'); content.style.position = 'absolute'; content.style.padding = '10px'; content.style.border = '1px solid #4d4d4d'; content.style.color = '#1a1a1a'; content.style.background = 'rgba(255,255,255,0.7)'; content.style.borderRadius = '2px'; content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; line = document.createElement('div'); line.style.position = 'absolute'; line.style.height = '40px'; line.style.width = '0'; line.style.borderLeft = '1px solid #4d4d4d'; dot = document.createElement('div'); dot.style.position = 'absolute'; dot.style.height = '0'; dot.style.width = '0'; dot.style.border = '5px solid #4d4d4d'; dot.style.borderRadius = '5px'; this.tooltip = { dataPoint: null, dom: { content: content, line: line, dot: dot } }; } else { content = this.tooltip.dom.content; line = this.tooltip.dom.line; dot = this.tooltip.dom.dot; } this._hideTooltip(); this.tooltip.dataPoint = dataPoint; if (typeof this.showTooltip === 'function') { content.innerHTML = this.showTooltip(dataPoint.point); } else { content.innerHTML = '<table>' + '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' + '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' + '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' + '</table>'; } content.style.left = '0'; content.style.top = '0'; this.frame.appendChild(content); this.frame.appendChild(line); this.frame.appendChild(dot); // calculate sizes var contentWidth = content.offsetWidth; var contentHeight = content.offsetHeight; var lineHeight = line.offsetHeight; var dotWidth = dot.offsetWidth; var dotHeight = dot.offsetHeight; var left = dataPoint.screen.x - contentWidth / 2; left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); line.style.left = dataPoint.screen.x + 'px'; line.style.top = (dataPoint.screen.y - lineHeight) + 'px'; content.style.left = left + 'px'; content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px'; dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px'; dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px'; }; /** * Hide the tooltip when displayed * @private */ Graph3d.prototype._hideTooltip = function () { if (this.tooltip) { this.tooltip.dataPoint = null; for (var prop in this.tooltip.dom) { if (this.tooltip.dom.hasOwnProperty(prop)) { var elem = this.tooltip.dom[prop]; if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } } } }; /**--------------------------------------------------------------------------**/ /** * Get the horizontal mouse position from a mouse event * @param {Event} event * @return {Number} mouse x */ getMouseX = function(event) { if ('clientX' in event) return event.clientX; return event.targetTouches[0] && event.targetTouches[0].clientX || 0; }; /** * Get the vertical mouse position from a mouse event * @param {Event} event * @return {Number} mouse y */ getMouseY = function(event) { if ('clientY' in event) return event.clientY; return event.targetTouches[0] && event.targetTouches[0].clientY || 0; }; module.exports = Graph3d; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var Point3d = __webpack_require__(9); /** * @class Camera * The camera is mounted on a (virtual) camera arm. The camera arm can rotate * The camera is always looking in the direction of the origin of the arm. * This way, the camera always rotates around one fixed point, the location * of the camera arm. * * Documentation: * http://en.wikipedia.org/wiki/3D_projection */ Camera = function () { this.armLocation = new Point3d(); this.armRotation = {}; this.armRotation.horizontal = 0; this.armRotation.vertical = 0; this.armLength = 1.7; this.cameraLocation = new Point3d(); this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0); this.calculateCameraOrientation(); }; /** * Set the location (origin) of the arm * @param {Number} x Normalized value of x * @param {Number} y Normalized value of y * @param {Number} z Normalized value of z */ Camera.prototype.setArmLocation = function(x, y, z) { this.armLocation.x = x; this.armLocation.y = y; this.armLocation.z = z; this.calculateCameraOrientation(); }; /** * Set the rotation of the camera arm * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. */ Camera.prototype.setArmRotation = function(horizontal, vertical) { if (horizontal !== undefined) { this.armRotation.horizontal = horizontal; } if (vertical !== undefined) { this.armRotation.vertical = vertical; if (this.armRotation.vertical < 0) this.armRotation.vertical = 0; if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI; } if (horizontal !== undefined || vertical !== undefined) { this.calculateCameraOrientation(); } }; /** * Retrieve the current arm rotation * @return {object} An object with parameters horizontal and vertical */ Camera.prototype.getArmRotation = function() { var rot = {}; rot.horizontal = this.armRotation.horizontal; rot.vertical = this.armRotation.vertical; return rot; }; /** * Set the (normalized) length of the camera arm. * @param {Number} length A length between 0.71 and 5.0 */ Camera.prototype.setArmLength = function(length) { if (length === undefined) return; this.armLength = length; // Radius must be larger than the corner of the graph, // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the // graph if (this.armLength < 0.71) this.armLength = 0.71; if (this.armLength > 5.0) this.armLength = 5.0; this.calculateCameraOrientation(); }; /** * Retrieve the arm length * @return {Number} length */ Camera.prototype.getArmLength = function() { return this.armLength; }; /** * Retrieve the camera location * @return {Point3d} cameraLocation */ Camera.prototype.getCameraLocation = function() { return this.cameraLocation; }; /** * Retrieve the camera rotation * @return {Point3d} cameraRotation */ Camera.prototype.getCameraRotation = function() { return this.cameraRotation; }; /** * Calculate the location and rotation of the camera based on the * position and orientation of the camera arm */ Camera.prototype.calculateCameraOrientation = function() { // calculate location of the camera this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical); // calculate rotation of the camera this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical; this.cameraRotation.y = 0; this.cameraRotation.z = -this.armRotation.horizontal; }; module.exports = Camera; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(4); /** * @class Filter * * @param {DataSet} data The google data table * @param {Number} column The index of the column to be filtered * @param {Graph} graph The graph */ function Filter (data, column, graph) { this.data = data; this.column = column; this.graph = graph; // the parent graph this.index = undefined; this.value = undefined; // read all distinct values and select the first one this.values = graph.getDistinctValues(data.get(), this.column); // sort both numeric and string values correctly this.values.sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); if (this.values.length > 0) { this.selectValue(0); } // create an array with the filtered datapoints. this will be loaded afterwards this.dataPoints = []; this.loaded = false; this.onLoadCallback = undefined; if (graph.animationPreload) { this.loaded = false; this.loadInBackground(); } else { this.loaded = true; } }; /** * Return the label * @return {string} label */ Filter.prototype.isLoaded = function() { return this.loaded; }; /** * Return the loaded progress * @return {Number} percentage between 0 and 100 */ Filter.prototype.getLoadedProgress = function() { var len = this.values.length; var i = 0; while (this.dataPoints[i]) { i++; } return Math.round(i / len * 100); }; /** * Return the label * @return {string} label */ Filter.prototype.getLabel = function() { return this.graph.filterLabel; }; /** * Return the columnIndex of the filter * @return {Number} columnIndex */ Filter.prototype.getColumn = function() { return this.column; }; /** * Return the currently selected value. Returns undefined if there is no selection * @return {*} value */ Filter.prototype.getSelectedValue = function() { if (this.index === undefined) return undefined; return this.values[this.index]; }; /** * Retrieve all values of the filter * @return {Array} values */ Filter.prototype.getValues = function() { return this.values; }; /** * Retrieve one value of the filter * @param {Number} index * @return {*} value */ Filter.prototype.getValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; return this.values[index]; }; /** * Retrieve the (filtered) dataPoints for the currently selected filter index * @param {Number} [index] (optional) * @return {Array} dataPoints */ Filter.prototype._getDataPoints = function(index) { if (index === undefined) index = this.index; if (index === undefined) return []; var dataPoints; if (this.dataPoints[index]) { dataPoints = this.dataPoints[index]; } else { var f = {}; f.column = this.column; f.value = this.values[index]; var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get(); dataPoints = this.graph._getDataPoints(dataView); this.dataPoints[index] = dataPoints; } return dataPoints; }; /** * Set a callback function when the filter is fully loaded. */ Filter.prototype.setOnLoadCallback = function(callback) { this.onLoadCallback = callback; }; /** * Add a value to the list with available values for this filter * No double entries will be created. * @param {Number} index */ Filter.prototype.selectValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; this.index = index; this.value = this.values[index]; }; /** * Load all filtered rows in the background one by one * Start this method without providing an index! */ Filter.prototype.loadInBackground = function(index) { if (index === undefined) index = 0; var frame = this.graph.frame; if (index < this.values.length) { var dataPointsTemp = this._getDataPoints(index); //this.graph.redrawInfo(); // TODO: not neat // create a progress box if (frame.progress === undefined) { frame.progress = document.createElement('DIV'); frame.progress.style.position = 'absolute'; frame.progress.style.color = 'gray'; frame.appendChild(frame.progress); } var progress = this.getLoadedProgress(); frame.progress.innerHTML = 'Loading animation... ' + progress + '%'; // TODO: this is no nice solution... frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider frame.progress.style.left = 10 + 'px'; var me = this; setTimeout(function() {me.loadInBackground(index+1);}, 10); this.loaded = false; } else { this.loaded = true; // remove the progress box if (frame.progress !== undefined) { frame.removeChild(frame.progress); frame.progress = undefined; } if (this.onLoadCallback) this.onLoadCallback(); } }; module.exports = Filter; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype Point2d * @param {Number} [x] * @param {Number} [y] */ Point2d = function (x, y) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; }; module.exports = Point2d; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype Point3d * @param {Number} [x] * @param {Number} [y] * @param {Number} [z] */ function Point3d(x, y, z) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; this.z = z !== undefined ? z : 0; }; /** * Subtract the two provided points, returns a-b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a-b */ Point3d.subtract = function(a, b) { var sub = new Point3d(); sub.x = a.x - b.x; sub.y = a.y - b.y; sub.z = a.z - b.z; return sub; }; /** * Add the two provided points, returns a+b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a+b */ Point3d.add = function(a, b) { var sum = new Point3d(); sum.x = a.x + b.x; sum.y = a.y + b.y; sum.z = a.z + b.z; return sum; }; /** * Calculate the average of two 3d points * @param {Point3d} a * @param {Point3d} b * @return {Point3d} The average, (a+b)/2 */ Point3d.avg = function(a, b) { return new Point3d( (a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2 ); }; /** * Calculate the cross product of the two provided points, returns axb * Documentation: http://en.wikipedia.org/wiki/Cross_product * @param {Point3d} a * @param {Point3d} b * @return {Point3d} cross product axb */ Point3d.crossProduct = function(a, b) { var crossproduct = new Point3d(); crossproduct.x = a.y * b.z - a.z * b.y; crossproduct.y = a.z * b.x - a.x * b.z; crossproduct.z = a.x * b.y - a.y * b.x; return crossproduct; }; /** * Rtrieve the length of the vector (or the distance from this point to the origin * @return {Number} length */ Point3d.prototype.length = function() { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }; module.exports = Point3d; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @constructor Slider * * An html slider control with start/stop/prev/next buttons * @param {Element} container The element where the slider will be created * @param {Object} options Available options: * {boolean} visible If true (default) the * slider is visible. */ function Slider(container, options) { if (container === undefined) { throw 'Error: No container element defined'; } this.container = container; this.visible = (options && options.visible != undefined) ? options.visible : true; if (this.visible) { this.frame = document.createElement('DIV'); //this.frame.style.backgroundColor = '#E5E5E5'; this.frame.style.width = '100%'; this.frame.style.position = 'relative'; this.container.appendChild(this.frame); this.frame.prev = document.createElement('INPUT'); this.frame.prev.type = 'BUTTON'; this.frame.prev.value = 'Prev'; this.frame.appendChild(this.frame.prev); this.frame.play = document.createElement('INPUT'); this.frame.play.type = 'BUTTON'; this.frame.play.value = 'Play'; this.frame.appendChild(this.frame.play); this.frame.next = document.createElement('INPUT'); this.frame.next.type = 'BUTTON'; this.frame.next.value = 'Next'; this.frame.appendChild(this.frame.next); this.frame.bar = document.createElement('INPUT'); this.frame.bar.type = 'BUTTON'; this.frame.bar.style.position = 'absolute'; this.frame.bar.style.border = '1px solid red'; this.frame.bar.style.width = '100px'; this.frame.bar.style.height = '6px'; this.frame.bar.style.borderRadius = '2px'; this.frame.bar.style.MozBorderRadius = '2px'; this.frame.bar.style.border = '1px solid #7F7F7F'; this.frame.bar.style.backgroundColor = '#E5E5E5'; this.frame.appendChild(this.frame.bar); this.frame.slide = document.createElement('INPUT'); this.frame.slide.type = 'BUTTON'; this.frame.slide.style.margin = '0px'; this.frame.slide.value = ' '; this.frame.slide.style.position = 'relative'; this.frame.slide.style.left = '-100px'; this.frame.appendChild(this.frame.slide); // create events var me = this; this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);}; this.frame.prev.onclick = function (event) {me.prev(event);}; this.frame.play.onclick = function (event) {me.togglePlay(event);}; this.frame.next.onclick = function (event) {me.next(event);}; } this.onChangeCallback = undefined; this.values = []; this.index = undefined; this.playTimeout = undefined; this.playInterval = 1000; // milliseconds this.playLoop = true; } /** * Select the previous index */ Slider.prototype.prev = function() { var index = this.getIndex(); if (index > 0) { index--; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.next = function() { var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.playNext = function() { var start = new Date(); var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } else if (this.playLoop) { // jump to the start index = 0; this.setIndex(index); } var end = new Date(); var diff = (end - start); // calculate how much time it to to set the index and to execute the callback // function. var interval = Math.max(this.playInterval - diff, 0); // document.title = diff // TODO: cleanup var me = this; this.playTimeout = setTimeout(function() {me.playNext();}, interval); }; /** * Toggle start or stop playing */ Slider.prototype.togglePlay = function() { if (this.playTimeout === undefined) { this.play(); } else { this.stop(); } }; /** * Start playing */ Slider.prototype.play = function() { // Test whether already playing if (this.playTimeout) return; this.playNext(); if (this.frame) { this.frame.play.value = 'Stop'; } }; /** * Stop playing */ Slider.prototype.stop = function() { clearInterval(this.playTimeout); this.playTimeout = undefined; if (this.frame) { this.frame.play.value = 'Play'; } }; /** * Set a callback function which will be triggered when the value of the * slider bar has changed. */ Slider.prototype.setOnChangeCallback = function(callback) { this.onChangeCallback = callback; }; /** * Set the interval for playing the list * @param {Number} interval The interval in milliseconds */ Slider.prototype.setPlayInterval = function(interval) { this.playInterval = interval; }; /** * Retrieve the current play interval * @return {Number} interval The interval in milliseconds */ Slider.prototype.getPlayInterval = function(interval) { return this.playInterval; }; /** * Set looping on or off * @pararm {boolean} doLoop If true, the slider will jump to the start when * the end is passed, and will jump to the end * when the start is passed. */ Slider.prototype.setPlayLoop = function(doLoop) { this.playLoop = doLoop; }; /** * Execute the onchange callback function */ Slider.prototype.onChange = function() { if (this.onChangeCallback !== undefined) { this.onChangeCallback(); } }; /** * redraw the slider on the correct place */ Slider.prototype.redraw = function() { if (this.frame) { // resize the bar this.frame.bar.style.top = (this.frame.clientHeight/2 - this.frame.bar.offsetHeight/2) + 'px'; this.frame.bar.style.width = (this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30) + 'px'; // position the slider button var left = this.indexToLeft(this.index); this.frame.slide.style.left = (left) + 'px'; } }; /** * Set the list with values for the slider * @param {Array} values A javascript array with values (any type) */ Slider.prototype.setValues = function(values) { this.values = values; if (this.values.length > 0) this.setIndex(0); else this.index = undefined; }; /** * Select a value by its index * @param {Number} index */ Slider.prototype.setIndex = function(index) { if (index < this.values.length) { this.index = index; this.redraw(); this.onChange(); } else { throw 'Error: index out of range'; } }; /** * retrieve the index of the currently selected vaue * @return {Number} index */ Slider.prototype.getIndex = function() { return this.index; }; /** * retrieve the currently selected value * @return {*} value */ Slider.prototype.get = function() { return this.values[this.index]; }; Slider.prototype._onMouseDown = function(event) { // only react on left mouse button down var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!leftButtonDown) return; this.startClientX = event.clientX; this.startSlideX = parseFloat(this.frame.slide.style.left); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; util.addEventListener(document, 'mousemove', this.onmousemove); util.addEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(event); }; Slider.prototype.leftToIndex = function (left) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = left - 3; var index = Math.round(x / width * (this.values.length-1)); if (index < 0) index = 0; if (index > this.values.length-1) index = this.values.length-1; return index; }; Slider.prototype.indexToLeft = function (index) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = index / (this.values.length-1) * width; var left = x + 3; return left; }; Slider.prototype._onMouseMove = function (event) { var diff = event.clientX - this.startClientX; var x = this.startSlideX + diff; var index = this.leftToIndex(x); this.setIndex(index); util.preventDefault(); }; Slider.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; // remove event listeners util.removeEventListener(document, 'mousemove', this.onmousemove); util.removeEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(); }; module.exports = Slider; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype StepNumber * The class StepNumber is an iterator for Numbers. You provide a start and end * value, and a best step size. StepNumber itself rounds to fixed values and * a finds the step that best fits the provided step. * * If prettyStep is true, the step size is chosen as close as possible to the * provided step, but being a round value like 1, 2, 5, 10, 20, 50, .... * * Example usage: * var step = new StepNumber(0, 10, 2.5, true); * step.start(); * while (!step.end()) { * alert(step.getCurrent()); * step.next(); * } * * Version: 1.0 * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ function StepNumber(start, end, step, prettyStep) { // set default values this._start = 0; this._end = 0; this._step = 1; this.prettyStep = true; this.precision = 5; this._current = 0; this.setRange(start, end, step, prettyStep); }; /** * Set a new range: start, end and step. * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setRange = function(start, end, step, prettyStep) { this._start = start ? start : 0; this._end = end ? end : 0; this.setStep(step, prettyStep); }; /** * Set a new step size * @param {Number} step New step size. Must be a positive value * @param {boolean} prettyStep Optional. If true, the provided step is rounded * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setStep = function(step, prettyStep) { if (step === undefined || step <= 0) return; if (prettyStep !== undefined) this.prettyStep = prettyStep; if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step); else this._step = step; }; /** * Calculate a nice step size, closest to the desired step size. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an * integer Number. For example 1, 2, 5, 10, 20, 50, etc... * @param {Number} step Desired step size * @return {Number} Nice step size */ StepNumber.calculatePrettyStep = function (step) { var log10 = function (x) {return Math.log(x) / Math.LN10;}; // try three steps (multiple of 1, 2, or 5 var step1 = Math.pow(10, Math.round(log10(step))), step2 = 2 * Math.pow(10, Math.round(log10(step / 2))), step5 = 5 * Math.pow(10, Math.round(log10(step / 5))); // choose the best step (closest to minimum step) var prettyStep = step1; if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2; if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5; // for safety if (prettyStep <= 0) { prettyStep = 1; } return prettyStep; }; /** * returns the current value of the step * @return {Number} current value */ StepNumber.prototype.getCurrent = function () { return parseFloat(this._current.toPrecision(this.precision)); }; /** * returns the current step size * @return {Number} current step size */ StepNumber.prototype.getStep = function () { return this._step; }; /** * Set the current value to the largest value smaller than start, which * is a multiple of the step size */ StepNumber.prototype.start = function() { this._current = this._start - this._start % this._step; }; /** * Do a step, add the step size to the current value */ StepNumber.prototype.next = function () { this._current += this._step; }; /** * Returns true whether the end is reached * @return {boolean} True if the current value has passed the end value. */ StepNumber.prototype.end = function () { return (this._current > this._end); }; module.exports = StepNumber; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(50); var Hammer = __webpack_require__(42); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var Core = __webpack_require__(44); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var ItemSet = __webpack_require__(24); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Timeline.setOptions for the available options. * @constructor * @extends Core */ function Timeline (container, items, options) { if (!(this instanceof Timeline)) { throw new SyntaxError('Constructor must be called with the new operator'); } var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.itemSet = new ItemSet(this.body); this.components.push(this.itemSet); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // Extend the functionality from Core Timeline.prototype = new Core(); /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Timeline.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.itemSet && this.itemSet.setItems(newDataSet); if (initialLoad) { if (this.options.start != undefined || this.options.end != undefined) { var start = this.options.start != undefined ? this.options.start : null; var end = this.options.end != undefined ? this.options.end : null; this.setWindow(start, end, {animate: false}); } else { this.fit({animate: false}); } } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Timeline.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.itemSet.setGroups(newDataSet); }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {string[] | string} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. * @param {Object} [options] Available options: * `focus: boolean` * If true, focus will be set to the selected item(s) * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. * Only applicable when option focus is true. */ Timeline.prototype.setSelection = function(ids, options) { this.itemSet && this.itemSet.setSelection(ids); if (options && options.focus) { this.focus(ids, options); } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ Timeline.prototype.getSelection = function() { return this.itemSet && this.itemSet.getSelection() || []; }; /** * Adjust the visible window such that the selected item (or multiple items) * are centered on screen. * @param {String | String[]} id An item id or array with item ids * @param {Object} [options] Available options: * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. * Only applicable when option focus is true */ Timeline.prototype.focus = function(id, options) { if (!this.itemsData || id == undefined) return; var ids = Array.isArray(id) ? id : [id]; // get the specified item(s) var itemsData = this.itemsData.getDataSet().get(ids, { type: { start: 'Date', end: 'Date' } }); // calculate minimum start and maximum end of specified items var start = null; var end = null; itemsData.forEach(function (itemData) { var s = itemData.start.valueOf(); var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); if (start === null || s < start) { start = s; } if (end === null || e > end) { end = e; } }); if (start !== null && end !== null) { // calculate the new middle and interval for the window var middle = (start + end) / 2; var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1); var animate = (options && options.animate !== undefined) ? options.animate : true; this.range.setRange(middle - interval / 2, middle + interval / 2, animate); } }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Timeline.prototype.getItemRange = function() { // calculate min from start filed var dataset = this.itemsData.getDataSet(), min = null, max = null; if (dataset) { // calculate the minimum value of the field 'start' var minItem = dataset.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = dataset.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = dataset.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; module.exports = Timeline; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(50); var Hammer = __webpack_require__(42); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var Core = __webpack_require__(44); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var LineGraph = __webpack_require__(26); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Graph2d.setOptions for the available options. * @constructor * @extends Core */ function Graph2d (container, items, options, groups) { var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.linegraph = new LineGraph(this.body); this.components.push(this.linegraph); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! if (groups) { this.setGroups(groups); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // Extend the functionality from Core Graph2d.prototype = new Core(); /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Graph2d.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.linegraph && this.linegraph.setItems(newDataSet); if (initialLoad && ('start' in this.options || 'end' in this.options)) { this.fit(); var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; this.setWindow(start, end); } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Graph2d.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.linegraph.setGroups(newDataSet); }; /** * Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). * @param groupId * @param width * @param height */ Graph2d.prototype.getLegend = function(groupId, width, height) { if (width === undefined) {width = 15;} if (height === undefined) {height = 15;} if (this.linegraph.groups[groupId] !== undefined) { return this.linegraph.groups[groupId].getLegend(width,height); } else { return "cannot find group:" + groupId; } } /** * This checks if the visible option of the supplied group (by ID) is true or false. * @param groupId * @returns {*} */ Graph2d.prototype.isGroupVisible = function(groupId) { if (this.linegraph.groups[groupId] !== undefined) { return (this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true)); } else { return false; } } /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Graph2d.prototype.getItemRange = function() { var min = null; var max = null; // calculate min from start filed for (var groupId in this.linegraph.groups) { if (this.linegraph.groups.hasOwnProperty(groupId)) { if (this.linegraph.groups[groupId].visible == true) { for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) { var item = this.linegraph.groups[groupId].itemsData[i]; var value = util.convert(item.x, 'Date').valueOf(); min = min == null ? value : min > value ? value : min; max = max == null ? value : max < value ? value : max; } } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; module.exports = Graph2d; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * @constructor DataStep * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an * end data point. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The DataStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function DataStep(start, end, minimumStep, containerHeight, customRange) { // variables this.current = 0; this.autoScale = true; this.stepIndex = 0; this.step = 1; this.scale = 1; this.marginStart; this.marginEnd; this.deadSpace = 0; this.majorSteps = [1, 2, 5, 10]; this.minorSteps = [0.25, 0.5, 1, 2]; this.setRange(start, end, minimumStep, containerHeight, customRange); } /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Number} [start] The start date and time. * @param {Number} [end] The end date and time. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, customRange) { this._start = customRange.min === undefined ? start : customRange.min; this._end = customRange.max === undefined ? end : customRange.max; if (this._start == this._end) { this._start -= 0.75; this._end += 1; } if (this.autoScale) { this.setMinimumStep(minimumStep, containerHeight); } this.setFirst(customRange); }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) { // round to floor var size = this._end - this._start; var safeSize = size * 1.2; var minimumStepValue = minimumStep * (safeSize / containerHeight); var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10); var minorStepIdx = -1; var magnitudefactor = Math.pow(10,orderOfMagnitude); var start = 0; if (orderOfMagnitude < 0) { start = orderOfMagnitude; } var solutionFound = false; for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { magnitudefactor = Math.pow(10,i); for (var j = 0; j < this.minorSteps.length; j++) { var stepSize = magnitudefactor * this.minorSteps[j]; if (stepSize >= minimumStepValue) { solutionFound = true; minorStepIdx = j; break; } } if (solutionFound == true) { break; } } this.stepIndex = minorStepIdx; this.scale = magnitudefactor; this.step = magnitudefactor * this.minorSteps[minorStepIdx]; }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ DataStep.prototype.setFirst = function(customRange) { if (customRange === undefined) { customRange = {}; } var niceStart = customRange.min === undefined ? this._start - (this.scale * 2 * this.minorSteps[this.stepIndex]) : customRange.min; var niceEnd = customRange.max === undefined ? this._end + (this.scale * this.minorSteps[this.stepIndex]) : customRange.max; this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max; this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min; this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart; this.marginRange = this.marginEnd - this.marginStart; this.current = this.marginEnd; }; DataStep.prototype.roundToMinor = function(value) { var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex])); if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { return rounded + (this.scale * this.minorSteps[this.stepIndex]); } else { return rounded; } } /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ DataStep.prototype.hasNext = function () { return (this.current >= this.marginStart); }; /** * Do the next step */ DataStep.prototype.next = function() { var prev = this.current; this.current -= this.step; // safety mechanism: if current time is still unchanged, move to the end if (this.current == prev) { this.current = this._end; } }; /** * Do the next step */ DataStep.prototype.previous = function() { this.current += this.step; this.marginEnd += this.step; this.marginRange = this.marginEnd - this.marginStart; }; /** * Get the current datetime * @return {String} current The current date */ DataStep.prototype.getCurrent = function() { var toPrecision = '' + Number(this.current).toPrecision(5); if (toPrecision.indexOf(",") != -1 || toPrecision.indexOf(".") != -1) { for (var i = toPrecision.length-1; i > 0; i--) { if (toPrecision[i] == "0") { toPrecision = toPrecision.slice(0,i); } else if (toPrecision[i] == "." || toPrecision[i] == ",") { toPrecision = toPrecision.slice(0,i); break; } else{ break; } } } return toPrecision; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ DataStep.prototype.snap = function(date) { }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ DataStep.prototype.isMajor = function() { return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0); }; module.exports = DataStep; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var hammerUtil = __webpack_require__(43); var moment = __webpack_require__(41); var Component = __webpack_require__(18); /** * @constructor Range * A Range controls a numeric range with a start and end value. * The Range adjusts the range based on mouse events or programmatic changes, * and triggers events when the range is changing or has been changed. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body * @param {Object} [options] See description at Range.setOptions */ function Range(body, options) { var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); this.start = now.clone().add(-3, 'days').valueOf(); // Number this.end = now.clone().add(4, 'days').valueOf(); // Number this.body = body; // default options this.defaultOptions = { start: null, end: null, direction: 'horizontal', // 'horizontal' or 'vertical' moveable: true, zoomable: true, min: null, max: null, zoomMin: 10, // milliseconds zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds }; this.options = util.extend({}, this.defaultOptions); this.props = { touch: {} }; this.animateTimer = null; // drag listeners for dragging this.body.emitter.on('dragstart', this._onDragStart.bind(this)); this.body.emitter.on('drag', this._onDrag.bind(this)); this.body.emitter.on('dragend', this._onDragEnd.bind(this)); // ignore dragging when holding this.body.emitter.on('hold', this._onHold.bind(this)); // mouse wheel for zooming this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF // pinch to zoom this.body.emitter.on('touch', this._onTouch.bind(this)); this.body.emitter.on('pinch', this._onPinch.bind(this)); this.setOptions(options); } Range.prototype = new Component(); /** * Set options for the range controller * @param {Object} options Available options: * {Number | Date | String} start Start date for the range * {Number | Date | String} end End date for the range * {Number} min Minimum value for start * {Number} max Maximum value for end * {Number} zoomMin Set a minimum value for * (end - start). * {Number} zoomMax Set a maximum value for * (end - start). * {Boolean} moveable Enable moving of the range * by dragging. True by default * {Boolean} zoomable Enable zooming of the range * by pinching/scrolling. True by default */ Range.prototype.setOptions = function (options) { if (options) { // copy the options that we know var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate']; util.selectiveExtend(fields, this.options, options); if ('start' in options || 'end' in options) { // apply a new range. both start and end are optional this.setRange(options.start, options.end); } } }; /** * Test whether direction has a valid value * @param {String} direction 'horizontal' or 'vertical' */ function validateDirection (direction) { if (direction != 'horizontal' && direction != 'vertical') { throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".'); } } /** * Set a new start and end range * @param {Date | Number | String} [start] * @param {Date | Number | String} [end] * @param {boolean | number} [animate=false] If true, the range is animated * smoothly to the new window. * If animate is a number, the * number is taken as duration * Default duration is 500 ms. * */ Range.prototype.setRange = function(start, end, animate) { var _start = start != undefined ? util.convert(start, 'Date').valueOf() : null; var _end = end != undefined ? util.convert(end, 'Date').valueOf() : null; this._cancelAnimation(); if (animate) { var me = this; var initStart = this.start; var initEnd = this.end; var duration = typeof animate === 'number' ? animate : 500; var initTime = new Date().valueOf(); var anyChanged = false; function next() { if (!me.props.touch.dragging) { var now = new Date().valueOf(); var time = now - initTime; var done = time > duration; var s = (done || _start === null) ? _start : util.easeInOutQuad(time, initStart, _start, duration); var e = (done || _end === null) ? _end : util.easeInOutQuad(time, initEnd, _end, duration); changed = me._applyRange(s, e); anyChanged = anyChanged || changed; if (changed) { me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end)}); } if (done) { if (anyChanged) { me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end)}); } } else { // animate with as high as possible frame rate, leave 20 ms in between // each to prevent the browser from blocking me.animateTimer = setTimeout(next, 20); } } } return next(); } else { var changed = this._applyRange(_start, _end); if (changed) { var params = {start: new Date(this.start), end: new Date(this.end)}; this.body.emitter.emit('rangechange', params); this.body.emitter.emit('rangechanged', params); } } }; /** * Stop an animation * @private */ Range.prototype._cancelAnimation = function () { if (this.animateTimer) { clearTimeout(this.animateTimer); this.animateTimer = null; } }; /** * Set a new start and end range. This method is the same as setRange, but * does not trigger a range change and range changed event, and it returns * true when the range is changed * @param {Number} [start] * @param {Number} [end] * @return {Boolean} changed * @private */ Range.prototype._applyRange = function(start, end) { var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start, newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end, max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null, min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null, diff; // check for valid number if (isNaN(newStart) || newStart === null) { throw new Error('Invalid start "' + start + '"'); } if (isNaN(newEnd) || newEnd === null) { throw new Error('Invalid end "' + end + '"'); } // prevent start < end if (newEnd < newStart) { newEnd = newStart; } // prevent start < min if (min !== null) { if (newStart < min) { diff = (min - newStart); newStart += diff; newEnd += diff; // prevent end > max if (max != null) { if (newEnd > max) { newEnd = max; } } } } // prevent end > max if (max !== null) { if (newEnd > max) { diff = (newEnd - max); newStart -= diff; newEnd -= diff; // prevent start < min if (min != null) { if (newStart < min) { newStart = min; } } } } // prevent (end-start) < zoomMin if (this.options.zoomMin !== null) { var zoomMin = parseFloat(this.options.zoomMin); if (zoomMin < 0) { zoomMin = 0; } if ((newEnd - newStart) < zoomMin) { if ((this.end - this.start) === zoomMin) { // ignore this action, we are already zoomed to the minimum newStart = this.start; newEnd = this.end; } else { // zoom to the minimum diff = (zoomMin - (newEnd - newStart)); newStart -= diff / 2; newEnd += diff / 2; } } } // prevent (end-start) > zoomMax if (this.options.zoomMax !== null) { var zoomMax = parseFloat(this.options.zoomMax); if (zoomMax < 0) { zoomMax = 0; } if ((newEnd - newStart) > zoomMax) { if ((this.end - this.start) === zoomMax) { // ignore this action, we are already zoomed to the maximum newStart = this.start; newEnd = this.end; } else { // zoom to the maximum diff = ((newEnd - newStart) - zoomMax); newStart += diff / 2; newEnd -= diff / 2; } } } var changed = (this.start != newStart || this.end != newEnd); this.start = newStart; this.end = newEnd; return changed; }; /** * Retrieve the current range. * @return {Object} An object with start and end properties */ Range.prototype.getRange = function() { return { start: this.start, end: this.end }; }; /** * Calculate the conversion offset and scale for current range, based on * the provided width * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.prototype.conversion = function (width) { return Range.conversion(this.start, this.end, width); }; /** * Static method to calculate the conversion offset and scale for a range, * based on the provided start, end, and width * @param {Number} start * @param {Number} end * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.conversion = function (start, end, width) { if (width != 0 && (end - start != 0)) { return { offset: start, scale: width / (end - start) } } else { return { offset: 0, scale: 1 }; } }; /** * Start dragging horizontally or vertically * @param {Event} event * @private */ Range.prototype._onDragStart = function(event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; this.props.touch.start = this.start; this.props.touch.end = this.end; this.props.touch.dragging = true; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'move'; } }; /** * Perform dragging operation * @param {Event} event * @private */ Range.prototype._onDrag = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; var direction = this.options.direction; validateDirection(direction); // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY; var interval = (this.props.touch.end - this.props.touch.start); var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height; var diffRange = -delta / width * interval; this._applyRange(this.props.touch.start + diffRange, this.props.touch.end + diffRange); // fire a rangechange event this.body.emitter.emit('rangechange', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Stop dragging operation * @param {event} event * @private */ Range.prototype._onDragEnd = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; this.props.touch.dragging = false; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'auto'; } // fire a rangechanged event this.body.emitter.emit('rangechanged', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Event handler for mouse wheel event, used to zoom * Code from http://adomas.org/javascript-mouse-wheel/ * @param {Event} event * @private */ Range.prototype._onMouseWheel = function(event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta / 120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail / 3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // perform the zoom action. Delta is normally 1 or -1 // adjust a negative delta such that zooming in with delta 0.1 // equals zooming out with a delta -0.1 var scale; if (delta < 0) { scale = 1 - (delta / 5); } else { scale = 1 / (1 + (delta / 5)) ; } // calculate center, the date to zoom around var gesture = hammerUtil.fakeGesture(this, event), pointer = getPointer(gesture.center, this.body.dom.center), pointerDate = this._pointerToDate(pointer); this.zoom(scale, pointerDate); } // Prevent default actions caused by mouse wheel // (else the page and timeline both zoom and scroll) event.preventDefault(); }; /** * Start of a touch gesture * @private */ Range.prototype._onTouch = function (event) { this.props.touch.start = this.start; this.props.touch.end = this.end; this.props.touch.allowDragging = true; this.props.touch.center = null; }; /** * On start of a hold gesture * @private */ Range.prototype._onHold = function () { this.props.touch.allowDragging = false; }; /** * Handle pinch event * @param {Event} event * @private */ Range.prototype._onPinch = function (event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; this.props.touch.allowDragging = false; if (event.gesture.touches.length > 1) { if (!this.props.touch.center) { this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center); } var scale = 1 / event.gesture.scale, initDate = this._pointerToDate(this.props.touch.center); // calculate new start and end var newStart = parseInt(initDate + (this.props.touch.start - initDate) * scale); var newEnd = parseInt(initDate + (this.props.touch.end - initDate) * scale); // apply new range this.setRange(newStart, newEnd); } }; /** * Helper function to calculate the center date for zooming * @param {{x: Number, y: Number}} pointer * @return {number} date * @private */ Range.prototype._pointerToDate = function (pointer) { var conversion; var direction = this.options.direction; validateDirection(direction); if (direction == 'horizontal') { var width = this.body.domProps.center.width; conversion = this.conversion(width); return pointer.x / conversion.scale + conversion.offset; } else { var height = this.body.domProps.center.height; conversion = this.conversion(height); return pointer.y / conversion.scale + conversion.offset; } }; /** * Get the pointer location relative to the location of the dom element * @param {{pageX: Number, pageY: Number}} touch * @param {Element} element HTML DOM element * @return {{x: Number, y: Number}} pointer * @private */ function getPointer (touch, element) { return { x: touch.pageX - util.getAbsoluteLeft(element), y: touch.pageY - util.getAbsoluteTop(element) }; } /** * Zoom the range the given scale in or out. Start and end date will * be adjusted, and the timeline will be redrawn. You can optionally give a * date around which to zoom. * For example, try scale = 0.9 or 1.1 * @param {Number} scale Scaling factor. Values above 1 will zoom out, * values below 1 will zoom in. * @param {Number} [center] Value representing a date around which will * be zoomed. */ Range.prototype.zoom = function(scale, center) { // if centerDate is not provided, take it half between start Date and end Date if (center == null) { center = (this.start + this.end) / 2; } // calculate new start and end var newStart = center + (this.start - center) * scale; var newEnd = center + (this.end - center) * scale; this.setRange(newStart, newEnd); }; /** * Move the range with a given delta to the left or right. Start and end * value will be adjusted. For example, try delta = 0.1 or -0.1 * @param {Number} delta Moving amount. Positive value will move right, * negative value will move left */ Range.prototype.move = function(delta) { // zoom start Date and end Date relative to the centerDate var diff = (this.end - this.start); // apply new values var newStart = this.start + diff * delta; var newEnd = this.end + diff * delta; // TODO: reckon with min and max range this.start = newStart; this.end = newEnd; }; /** * Move the range to a new center point * @param {Number} moveTo New center point of the range */ Range.prototype.moveTo = function(moveTo) { var center = (this.start + this.end) / 2; var diff = center - moveTo; // calculate new start and end var newStart = this.start - diff; var newEnd = this.end - diff; this.setRange(newStart, newEnd); }; module.exports = Range; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // Utility functions for ordering and stacking of items var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors /** * Order items by their start data * @param {Item[]} items */ exports.orderByStart = function(items) { items.sort(function (a, b) { return a.data.start - b.data.start; }); }; /** * Order items by their end date. If they have no end date, their start date * is used. * @param {Item[]} items */ exports.orderByEnd = function(items) { items.sort(function (a, b) { var aTime = ('end' in a.data) ? a.data.end : a.data.start, bTime = ('end' in b.data) ? b.data.end : b.data.start; return aTime - bTime; }); }; /** * Adjust vertical positions of the items such that they don't overlap each * other. * @param {Item[]} items * All visible items * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * Margins between items and between items and the axis. * @param {boolean} [force=false] * If true, all items will be repositioned. If false (default), only * items having a top===null will be re-stacked */ exports.stack = function(items, margin, force) { var i, iMax; if (force) { // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = null; } } // calculate new, non-overlapping positions for (i = 0, iMax = items.length; i < iMax; i++) { var item = items[i]; if (item.top === null) { // initialize top position item.top = margin.axis; do { // TODO: optimize checking for overlap. when there is a gap without items, // you only need to check for items from the next item on, not from zero var collidingItem = null; for (var j = 0, jj = items.length; j < jj; j++) { var other = items[j]; if (other.top !== null && other !== item && exports.collision(item, other, margin.item)) { collidingItem = other; break; } } if (collidingItem != null) { // There is a collision. Reposition the items above the colliding element item.top = collidingItem.top + collidingItem.height + margin.item.vertical; } } while (collidingItem); } } }; /** * Adjust vertical positions of the items without stacking them * @param {Item[]} items * All visible items * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * Margins between items and between items and the axis. */ exports.nostack = function(items, margin) { var i, iMax; // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = margin.axis; } }; /** * Test if the two provided items collide * The items must have parameters left, width, top, and height. * @param {Item} a The first item * @param {Item} b The second item * @param {{horizontal: number, vertical: number}} margin * An object containing a horizontal and vertical * minimum required margin. * @return {boolean} true if a and b collide, else false */ exports.collision = function(a, b, margin) { return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) && (a.left + a.width + margin.horizontal - EPSILON) > b.left && (a.top - margin.vertical + EPSILON) < (b.top + b.height) && (a.top + a.height + margin.vertical - EPSILON) > b.top); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var moment = __webpack_require__(41); /** * @constructor TimeStep * The class TimeStep is an iterator for dates. You provide a start date and an * end date. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function TimeStep(start, end, minimumStep) { // variables this.current = new Date(); this._start = new Date(); this._end = new Date(); this.autoScale = true; this.scale = TimeStep.SCALE.DAY; this.step = 1; // initialize the range this.setRange(start, end, minimumStep); } /// enum scale TimeStep.SCALE = { MILLISECOND: 1, SECOND: 2, MINUTE: 3, HOUR: 4, DAY: 5, WEEKDAY: 6, MONTH: 7, YEAR: 8 }; /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Date} [start] The start date and time. * @param {Date} [end] The end date and time. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds */ TimeStep.prototype.setRange = function(start, end, minimumStep) { if (!(start instanceof Date) || !(end instanceof Date)) { throw "No legal start or end date in method setRange"; } this._start = (start != undefined) ? new Date(start.valueOf()) : new Date(); this._end = (end != undefined) ? new Date(end.valueOf()) : new Date(); if (this.autoScale) { this.setMinimumStep(minimumStep); } }; /** * Set the range iterator to the start date. */ TimeStep.prototype.first = function() { this.current = new Date(this._start.valueOf()); this.roundToMinor(); }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ TimeStep.prototype.roundToMinor = function() { // round to floor // IMPORTANT: we have no breaks in this switch! (this is no bug) //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.YEAR: this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); this.current.setMonth(0); case TimeStep.SCALE.MONTH: this.current.setDate(1); case TimeStep.SCALE.DAY: // intentional fall through case TimeStep.SCALE.WEEKDAY: this.current.setHours(0); case TimeStep.SCALE.HOUR: this.current.setMinutes(0); case TimeStep.SCALE.MINUTE: this.current.setSeconds(0); case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0); //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds } if (this.step != 1) { // round down to the first minor value that is a multiple of the current step size switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break; default: break; } } }; /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ TimeStep.prototype.hasNext = function () { return (this.current.valueOf() <= this._end.valueOf()); }; /** * Do the next step */ TimeStep.prototype.next = function() { var prev = this.current.valueOf(); // Two cases, needed to prevent issues with switching daylight savings // (end of March and end of October) if (this.current.getMonth() < 6) { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break; case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break; case TimeStep.SCALE.HOUR: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) var h = this.current.getHours(); this.current.setHours(h - (h % this.step)); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } else { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } if (this.step != 1) { // round down to the correct major value switch (this.scale) { case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break; case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break; case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break; case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break; case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break; case TimeStep.SCALE.YEAR: break; // nothing to do for year default: break; } } // safety mechanism: if current time is still unchanged, move to the end if (this.current.valueOf() == prev) { this.current = new Date(this._end.valueOf()); } }; /** * Get the current datetime * @return {Date} current The current date */ TimeStep.prototype.getCurrent = function() { return this.current; }; /** * Set a custom scale. Autoscaling will be disabled. * For example setScale(SCALE.MINUTES, 5) will result * in minor steps of 5 minutes, and major steps of an hour. * * @param {TimeStep.SCALE} newScale * A scale. Choose from SCALE.MILLISECOND, * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR, * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH, * SCALE.YEAR. * @param {Number} newStep A step size, by default 1. Choose for * example 1, 2, 5, or 10. */ TimeStep.prototype.setScale = function(newScale, newStep) { this.scale = newScale; if (newStep > 0) { this.step = newStep; } this.autoScale = false; }; /** * Enable or disable autoscaling * @param {boolean} enable If true, autoascaling is set true */ TimeStep.prototype.setAutoScale = function (enable) { this.autoScale = enable; }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ TimeStep.prototype.setMinimumStep = function(minimumStep) { if (minimumStep == undefined) { return; } var stepYear = (1000 * 60 * 60 * 24 * 30 * 12); var stepMonth = (1000 * 60 * 60 * 24 * 30); var stepDay = (1000 * 60 * 60 * 24); var stepHour = (1000 * 60 * 60); var stepMinute = (1000 * 60); var stepSecond = (1000); var stepMillisecond= (1); // find the smallest step that is larger than the provided minimumStep if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;} if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;} if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;} if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;} if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;} if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;} if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;} if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;} if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;} if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;} if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;} if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;} if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;} if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;} if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;} if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;} if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;} if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;} if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;} if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;} if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;} if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;} if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;} if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;} if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;} if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;} if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;} if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;} if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;} }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeStep.prototype.snap = function(date) { var clone = new Date(date.valueOf()); if (this.scale == TimeStep.SCALE.YEAR) { var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); clone.setFullYear(Math.round(year / this.step) * this.step); clone.setMonth(0); clone.setDate(0); clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MONTH) { if (clone.getDate() > 15) { clone.setDate(1); clone.setMonth(clone.getMonth() + 1); // important: first set Date to 1, after that change the month. } else { clone.setDate(1); } clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.DAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 24) * 24); break; default: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.WEEKDAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; default: clone.setHours(Math.round(clone.getHours() / 6) * 6); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.HOUR) { switch (this.step) { case 4: clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break; default: clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break; } clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MINUTE) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); clone.setSeconds(0); break; case 5: clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break; default: clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break; } clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.SECOND) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); clone.setMilliseconds(0); break; case 5: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break; default: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break; } } else if (this.scale == TimeStep.SCALE.MILLISECOND) { var step = this.step > 5 ? this.step / 2 : 1; clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step); } return clone; }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ TimeStep.prototype.isMajor = function() { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return (this.current.getMilliseconds() == 0); case TimeStep.SCALE.SECOND: return (this.current.getSeconds() == 0); case TimeStep.SCALE.MINUTE: return (this.current.getHours() == 0) && (this.current.getMinutes() == 0); // Note: this is no bug. Major label is equal for both minute and hour scale case TimeStep.SCALE.HOUR: return (this.current.getHours() == 0); case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: return (this.current.getDate() == 1); case TimeStep.SCALE.MONTH: return (this.current.getMonth() == 0); case TimeStep.SCALE.YEAR: return false; default: return false; } }; /** * Returns formatted text for the minor axislabel, depending on the current * date and the scale. For example when scale is MINUTE, the current time is * formatted as "hh:mm". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMinor = function(date) { if (date == undefined) { date = this.current; } switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS'); case TimeStep.SCALE.SECOND: return moment(date).format('s'); case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm'); case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm'); case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D'); case TimeStep.SCALE.DAY: return moment(date).format('D'); case TimeStep.SCALE.MONTH: return moment(date).format('MMM'); case TimeStep.SCALE.YEAR: return moment(date).format('YYYY'); default: return ''; } }; /** * Returns formatted text for the major axis label, depending on the current * date and the scale. For example when scale is MINUTE, the major scale is * hours, and the hour will be formatted as "hh". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMajor = function(date) { if (date == undefined) { date = this.current; } //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss'); case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm'); case TimeStep.SCALE.MINUTE: case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM'); case TimeStep.SCALE.WEEKDAY: case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY'); case TimeStep.SCALE.MONTH: return moment(date).format('YYYY'); case TimeStep.SCALE.YEAR: return ''; default: return ''; } }; module.exports = TimeStep; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Prototype for visual components * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] * @param {Object} [options] */ function Component (body, options) { this.options = null; this.props = null; } /** * Set options for the component. The new options will be merged into the * current options. * @param {Object} options */ Component.prototype.setOptions = function(options) { if (options) { util.extend(this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ Component.prototype.redraw = function() { // should be implemented by the component return false; }; /** * Destroy the component. Cleanup DOM and event listeners */ Component.prototype.destroy = function() { // should be implemented by the component }; /** * Test whether the component is resized since the last time _isResized() was * called. * @return {Boolean} Returns true if the component is resized * @protected */ Component.prototype._isResized = function() { var resized = (this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height); this.props._previousWidth = this.props.width; this.props._previousHeight = this.props.height; return resized; }; module.exports = Component; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Component = __webpack_require__(18); var moment = __webpack_require__(41); var locales = __webpack_require__(45); /** * A current time bar * @param {{range: Range, dom: Object, domProps: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCurrentTime] * @constructor CurrentTime * @extends Component */ function CurrentTime (body, options) { this.body = body; // default options this.defaultOptions = { showCurrentTime: true, locales: locales, locale: 'en' }; this.options = util.extend({}, this.defaultOptions); this.offset = 0; this._create(); this.setOptions(options); } CurrentTime.prototype = new Component(); /** * Create the HTML DOM for the current time bar * @private */ CurrentTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'currenttime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; }; /** * Destroy the CurrentTime bar */ CurrentTime.prototype.destroy = function () { this.options.showCurrentTime = false; this.redraw(); // will remove the bar from the DOM and stop refreshing this.body = null; }; /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCurrentTime] */ CurrentTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCurrentTime', 'locale', 'locales'], this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CurrentTime.prototype.redraw = function() { if (this.options.showCurrentTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); this.start(); } var now = new Date(new Date().valueOf() + this.offset); var x = this.body.util.toScreen(now); var locale = this.options.locales[this.options.locale]; var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss'); title = title.charAt(0).toUpperCase() + title.substring(1); this.bar.style.left = x + 'px'; this.bar.title = title; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } this.stop(); } return false; }; /** * Start auto refreshing the current time bar */ CurrentTime.prototype.start = function() { var me = this; function update () { me.stop(); // determine interval to refresh var scale = me.body.range.conversion(me.body.domProps.center.width).scale; var interval = 1 / scale / 10; if (interval < 30) interval = 30; if (interval > 1000) interval = 1000; me.redraw(); // start a timer to adjust for the new time me.currentTimeTimer = setTimeout(update, interval); } update(); }; /** * Stop auto refreshing the current time bar */ CurrentTime.prototype.stop = function() { if (this.currentTimeTimer !== undefined) { clearTimeout(this.currentTimeTimer); delete this.currentTimeTimer; } }; /** * Set a current time. This can be used for example to ensure that a client's * time is synchronized with a shared server time. * @param {Date | String | Number} time A Date, unix timestamp, or * ISO date string. */ CurrentTime.prototype.setCurrentTime = function(time) { var t = util.convert(time, 'Date').valueOf(); var now = new Date().valueOf(); this.offset = t - now; this.redraw(); }; /** * Get the current time. * @return {Date} Returns the current time. */ CurrentTime.prototype.getCurrentTime = function() { return new Date(new Date().valueOf() + this.offset); }; module.exports = CurrentTime; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(42); var util = __webpack_require__(1); var Component = __webpack_require__(18); var moment = __webpack_require__(41); var locales = __webpack_require__(45); /** * A custom time bar * @param {{range: Range, dom: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCustomTime] * @constructor CustomTime * @extends Component */ function CustomTime (body, options) { this.body = body; // default options this.defaultOptions = { showCustomTime: false, locales: locales, locale: 'en' }; this.options = util.extend({}, this.defaultOptions); this.customTime = new Date(); this.eventParams = {}; // stores state parameters while dragging the bar // create the DOM this._create(); this.setOptions(options); } CustomTime.prototype = new Component(); /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCustomTime] */ CustomTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCustomTime', 'locale', 'locales'], this.options, options); } }; /** * Create the DOM for the custom time * @private */ CustomTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'customtime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; var drag = document.createElement('div'); drag.style.position = 'relative'; drag.style.top = '0px'; drag.style.left = '-10px'; drag.style.height = '100%'; drag.style.width = '20px'; bar.appendChild(drag); // attach event listeners this.hammer = Hammer(bar, { prevent_default: true }); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); }; /** * Destroy the CustomTime bar */ CustomTime.prototype.destroy = function () { this.options.showCustomTime = false; this.redraw(); // will remove the bar from the DOM this.hammer.enable(false); this.hammer = null; this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CustomTime.prototype.redraw = function () { if (this.options.showCustomTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); } var x = this.body.util.toScreen(this.customTime); var locale = this.options.locales[this.options.locale]; var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss'); title = title.charAt(0).toUpperCase() + title.substring(1); this.bar.style.left = x + 'px'; this.bar.title = title; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } } return false; }; /** * Set custom time. * @param {Date | number | string} time */ CustomTime.prototype.setCustomTime = function(time) { this.customTime = util.convert(time, 'Date'); this.redraw(); }; /** * Retrieve the current custom time. * @return {Date} customTime */ CustomTime.prototype.getCustomTime = function() { return new Date(this.customTime.valueOf()); }; /** * Start moving horizontally * @param {Event} event * @private */ CustomTime.prototype._onDragStart = function(event) { this.eventParams.dragging = true; this.eventParams.customTime = this.customTime; event.stopPropagation(); event.preventDefault(); }; /** * Perform moving operating. * @param {Event} event * @private */ CustomTime.prototype._onDrag = function (event) { if (!this.eventParams.dragging) return; var deltaX = event.gesture.deltaX, x = this.body.util.toScreen(this.eventParams.customTime) + deltaX, time = this.body.util.toTime(x); this.setCustomTime(time); // fire a timechange event this.body.emitter.emit('timechange', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; /** * Stop moving operating. * @param {event} event * @private */ CustomTime.prototype._onDragEnd = function (event) { if (!this.eventParams.dragging) return; // fire a timechanged event this.body.emitter.emit('timechanged', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; module.exports = CustomTime; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var Component = __webpack_require__(18); var DataStep = __webpack_require__(14); /** * A horizontal time axis * @param {Object} [options] See DataAxis.setOptions for the available * options. * @constructor DataAxis * @extends Component * @param body */ function DataAxis (body, options, svg, linegraphOptions) { this.id = util.randomUUID(); this.body = body; this.defaultOptions = { orientation: 'left', // supported: 'left', 'right' showMinorLabels: true, showMajorLabels: true, icons: true, majorLinesOffset: 7, minorLinesOffset: 4, labelOffsetX: 10, labelOffsetY: 2, iconWidth: 20, width: '40px', visible: true, customRange: { left: {min:undefined, max:undefined}, right: {min:undefined, max:undefined} } }; this.linegraphOptions = linegraphOptions; this.linegraphSVG = svg; this.props = {}; this.DOMelements = { // dynamic elements lines: {}, labels: {} }; this.dom = {}; this.range = {start:0, end:0}; this.options = util.extend({}, this.defaultOptions); this.conversionFactor = 1; this.setOptions(options); this.width = Number(('' + this.options.width).replace("px","")); this.minWidth = this.width; this.height = this.linegraphSVG.offsetHeight; this.stepPixels = 25; this.stepPixelsForced = 25; this.lineOffset = 0; this.master = true; this.svgElements = {}; this.groups = {}; this.amountOfGroups = 0; // create the HTML DOM this._create(); } DataAxis.prototype = new Component(); DataAxis.prototype.addGroup = function(label, graphOptions) { if (!this.groups.hasOwnProperty(label)) { this.groups[label] = graphOptions; } this.amountOfGroups += 1; }; DataAxis.prototype.updateGroup = function(label, graphOptions) { this.groups[label] = graphOptions; }; DataAxis.prototype.removeGroup = function(label) { if (this.groups.hasOwnProperty(label)) { delete this.groups[label]; this.amountOfGroups -= 1; } }; DataAxis.prototype.setOptions = function (options) { if (options) { var redraw = false; if (this.options.orientation != options.orientation && options.orientation !== undefined) { redraw = true; } var fields = [ 'orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'customRange' ]; util.selectiveExtend(fields, this.options, options); this.minWidth = Number(('' + this.options.width).replace("px","")); if (redraw == true && this.dom.frame) { this.hide(); this.show(); } } }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype._create = function() { this.dom.frame = document.createElement('div'); this.dom.frame.style.width = this.options.width; this.dom.frame.style.height = this.height; this.dom.lineContainer = document.createElement('div'); this.dom.lineContainer.style.width = '100%'; this.dom.lineContainer.style.height = this.height; // create svg element for graph drawing. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = "absolute"; this.svg.style.top = '0px'; this.svg.style.height = '100%'; this.svg.style.width = '100%'; this.svg.style.display = "block"; this.dom.frame.appendChild(this.svg); }; DataAxis.prototype._redrawGroupIcons = function () { DOMutil.prepareElements(this.svgElements); var x; var iconWidth = this.options.iconWidth; var iconHeight = 15; var iconOffset = 4; var y = iconOffset + 0.5 * iconHeight; if (this.options.orientation == 'left') { x = iconOffset; } else { x = this.width - iconWidth - iconOffset; } for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); y += iconHeight + iconOffset; } } } DOMutil.cleanupElements(this.svgElements); }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype.show = function() { if (!this.dom.frame.parentNode) { if (this.options.orientation == 'left') { this.body.dom.left.appendChild(this.dom.frame); } else { this.body.dom.right.appendChild(this.dom.frame); } } if (!this.dom.lineContainer.parentNode) { this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); } }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype.hide = function() { if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } if (this.dom.lineContainer.parentNode) { this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); } }; /** * Set a range (start and end) * @param end * @param start * @param end */ DataAxis.prototype.setRange = function (start, end) { this.range.start = start; this.range.end = end; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ DataAxis.prototype.redraw = function () { var changeCalled = false; var activeGroups = 0; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { activeGroups++; } } } if (this.amountOfGroups == 0 || activeGroups == 0) { this.hide(); } else { this.show(); this.height = Number(this.linegraphSVG.style.height.replace("px","")); // svg offsetheight did not work in firefox and explorer... this.dom.lineContainer.style.height = this.height + 'px'; this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0; var props = this.props; var frame = this.dom.frame; // update classname frame.className = 'dataaxis'; // calculate character width and height this._calculateCharSize(); var orientation = this.options.orientation; var showMinorLabels = this.options.showMinorLabels; var showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; props.minorLineHeight = 1; props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; props.majorLineHeight = 1; // take frame offline while updating (is almost twice as fast) if (orientation == 'left') { frame.style.top = '0'; frame.style.left = '0'; frame.style.bottom = ''; frame.style.width = this.width + 'px'; frame.style.height = this.height + "px"; } else { // right frame.style.top = ''; frame.style.bottom = '0'; frame.style.left = '0'; frame.style.width = this.width + 'px'; frame.style.height = this.height + "px"; } changeCalled = this._redrawLabels(); if (this.options.icons == true) { this._redrawGroupIcons(); } } return changeCalled; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ DataAxis.prototype._redrawLabels = function () { DOMutil.prepareElements(this.DOMelements.lines); DOMutil.prepareElements(this.DOMelements.labels); var orientation = this.options['orientation']; // calculate range and step (step such that we have space for 7 characters per label) var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced; var step = new DataStep(this.range.start, this.range.end, minimumStep, this.dom.frame.offsetHeight, this.options.customRange[this.options.orientation]); this.step = step; // get the distance in pixels for a step // dead space is space that is "left over" after a step var stepPixels = (this.dom.frame.offsetHeight - (step.deadSpace * (this.dom.frame.offsetHeight / step.marginRange))) / (((step.marginRange - step.deadSpace) / step.step)); this.stepPixels = stepPixels; var amountOfSteps = this.height / stepPixels; var stepDifference = 0; if (this.master == false) { stepPixels = this.stepPixelsForced; stepDifference = Math.round((this.dom.frame.offsetHeight / stepPixels) - amountOfSteps); for (var i = 0; i < 0.5 * stepDifference; i++) { step.previous(); } amountOfSteps = this.height / stepPixels; } else { amountOfSteps += 0.25; } this.valueAtZero = step.marginEnd; var marginStartPos = 0; // do not draw the first label var max = 1; this.maxLabelSize = 0; var y = 0; while (max < Math.round(amountOfSteps)) { step.next(); y = Math.round(max * stepPixels); marginStartPos = max * stepPixels; var isMajor = step.isMajor(); if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) { this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis minor', this.props.minorCharHeight); } if (isMajor && this.options['showMajorLabels'] && this.master == true || this.options['showMinorLabels'] == false && this.master == false && isMajor == true) { if (y >= 0) { this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis major', this.props.majorCharHeight); } this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth); } else { this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth); } max++; } if (this.master == false) { this.conversionFactor = y / (this.valueAtZero - step.current); } else { this.conversionFactor = this.dom.frame.offsetHeight / step.marginRange; } var offset = this.options.icons == true ? this.options.iconWidth + this.options.labelOffsetX + 15 : this.options.labelOffsetX + 15; // this will resize the yAxis to accomodate the labels. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) { this.width = this.maxLabelSize + offset; this.options.width = this.width + "px"; DOMutil.cleanupElements(this.DOMelements.lines); DOMutil.cleanupElements(this.DOMelements.labels); this.redraw(); return true; } // this will resize the yAxis if it is too big for the labels. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) { this.width = Math.max(this.minWidth,this.maxLabelSize + offset); this.options.width = this.width + "px"; DOMutil.cleanupElements(this.DOMelements.lines); DOMutil.cleanupElements(this.DOMelements.labels); this.redraw(); return true; } else { DOMutil.cleanupElements(this.DOMelements.lines); DOMutil.cleanupElements(this.DOMelements.labels); return false; } }; DataAxis.prototype.convertValue = function (value) { var invertedValue = this.valueAtZero - value; var convertedValue = invertedValue * this.conversionFactor; return convertedValue; }; /** * Create a label for the axis at position x * @private * @param y * @param text * @param orientation * @param className * @param characterHeight */ DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { // reuse redundant label var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift(); label.className = className; label.innerHTML = text; if (orientation == 'left') { label.style.left = '-' + this.options.labelOffsetX + 'px'; label.style.textAlign = "right"; } else { label.style.right = '-' + this.options.labelOffsetX + 'px'; label.style.textAlign = "left"; } label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; text += ''; var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth); if (this.maxLabelSize < text.length * largestWidth) { this.maxLabelSize = text.length * largestWidth; } }; /** * Create a minor line for the axis at position y * @param y * @param orientation * @param className * @param offset * @param width */ DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { if (this.master == true) { var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift(); line.className = className; line.innerHTML = ''; if (orientation == 'left') { line.style.left = (this.width - offset) + 'px'; } else { line.style.right = (this.width - offset) + 'px'; } line.style.width = width + 'px'; line.style.top = y + 'px'; } }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ DataAxis.prototype._calculateCharSize = function () { // determine the char width and height on the minor axis if (!('minorCharHeight' in this.props)) { var textMinor = document.createTextNode('0'); var measureCharMinor = document.createElement('DIV'); measureCharMinor.className = 'yAxis minor measure'; measureCharMinor.appendChild(textMinor); this.dom.frame.appendChild(measureCharMinor); this.props.minorCharHeight = measureCharMinor.clientHeight; this.props.minorCharWidth = measureCharMinor.clientWidth; this.dom.frame.removeChild(measureCharMinor); } if (!('majorCharHeight' in this.props)) { var textMajor = document.createTextNode('0'); var measureCharMajor = document.createElement('DIV'); measureCharMajor.className = 'yAxis major measure'; measureCharMajor.appendChild(textMajor); this.dom.frame.appendChild(measureCharMajor); this.props.majorCharHeight = measureCharMajor.clientHeight; this.props.majorCharWidth = measureCharMajor.clientWidth; this.dom.frame.removeChild(measureCharMajor); } }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ DataAxis.prototype.snap = function(date) { return this.step.snap(date); }; module.exports = DataAxis; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) { this.id = groupId; var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom'] this.options = util.selectiveBridgeObject(fields,options); this.usingDefaultStyle = group.className === undefined; this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; this.zeroPosition = 0; this.update(group); if (this.usingDefaultStyle == true) { this.groupsUsingDefaultStyles[0] += 1; } this.itemsData = []; this.visible = group.visible === undefined ? true : group.visible; } GraphGroup.prototype.setItems = function(items) { if (items != null) { this.itemsData = items; if (this.options.sort == true) { this.itemsData.sort(function (a,b) {return a.x - b.x;}) } } else { this.itemsData = []; } }; GraphGroup.prototype.setZeroPosition = function(pos) { this.zeroPosition = pos; }; GraphGroup.prototype.setOptions = function(options) { if (options !== undefined) { var fields = ['sampling','style','sort','yAxisOrientation','barChart']; util.selectiveDeepExtend(fields, this.options, options); util.mergeOptions(this.options, options,'catmullRom'); util.mergeOptions(this.options, options,'drawPoints'); util.mergeOptions(this.options, options,'shaded'); if (options.catmullRom) { if (typeof options.catmullRom == 'object') { if (options.catmullRom.parametrization) { if (options.catmullRom.parametrization == 'uniform') { this.options.catmullRom.alpha = 0; } else if (options.catmullRom.parametrization == 'chordal') { this.options.catmullRom.alpha = 1.0; } else { this.options.catmullRom.parametrization = 'centripetal'; this.options.catmullRom.alpha = 0.5; } } } } } }; GraphGroup.prototype.update = function(group) { this.group = group; this.content = group.content || 'graph'; this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10; this.visible = group.visible === undefined ? true : group.visible; this.setOptions(group.options); }; GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { var fillHeight = iconHeight * 0.5; var path, fillPath; var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer); outline.setAttributeNS(null, "x", x); outline.setAttributeNS(null, "y", y - fillHeight); outline.setAttributeNS(null, "width", iconWidth); outline.setAttributeNS(null, "height", 2*fillHeight); outline.setAttributeNS(null, "class", "outline"); if (this.options.style == 'line') { path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer); path.setAttributeNS(null, "class", this.className); path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+""); if (this.options.shaded.enabled == true) { fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer); if (this.options.shaded.orientation == 'top') { fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) + "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight)); } else { fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " + "L"+x+"," + (y + fillHeight) + " " + "L"+ (x + iconWidth) + "," + (y + fillHeight) + "L"+ (x + iconWidth) + ","+y); } fillPath.setAttributeNS(null, "class", this.className + " iconFill"); } if (this.options.drawPoints.enabled == true) { DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer); } } else { var barWidth = Math.round(0.3 * iconWidth); var bar1Height = Math.round(0.4 * iconHeight); var bar2Height = Math.round(0.75 * iconHeight); var offset = Math.round((iconWidth - (2 * barWidth))/3); DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer); DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer); } }; /** * * @param iconWidth * @param iconHeight * @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}} */ GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) { var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight); return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation}; } module.exports = GraphGroup; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var stack = __webpack_require__(16); var RangeItem = __webpack_require__(32); /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function Group (groupId, data, itemSet) { this.groupId = groupId; this.itemSet = itemSet; this.dom = {}; this.props = { label: { width: 0, height: 0 } }; this.className = null; this.items = {}; // items filtered by groupId of this group this.visibleItems = []; // items currently visible in window this.orderedItems = { // items sorted by start and by end byStart: [], byEnd: [] }; this._create(); this.setData(data); } /** * Create DOM elements for the group * @private */ Group.prototype._create = function() { var label = document.createElement('div'); label.className = 'vlabel'; this.dom.label = label; var inner = document.createElement('div'); inner.className = 'inner'; label.appendChild(inner); this.dom.inner = inner; var foreground = document.createElement('div'); foreground.className = 'group'; foreground['timeline-group'] = this; this.dom.foreground = foreground; this.dom.background = document.createElement('div'); this.dom.background.className = 'group'; this.dom.axis = document.createElement('div'); this.dom.axis.className = 'group'; // create a hidden marker to detect when the Timelines container is attached // to the DOM, or the style of a parent of the Timeline is changed from // display:none is changed to visible. this.dom.marker = document.createElement('div'); this.dom.marker.style.visibility = 'hidden'; this.dom.marker.innerHTML = '?'; this.dom.background.appendChild(this.dom.marker); }; /** * Set the group data for this group * @param {Object} data Group data, can contain properties content and className */ Group.prototype.setData = function(data) { // update contents var content = data && data.content; if (content instanceof Element) { this.dom.inner.appendChild(content); } else if (content !== undefined && content !== null) { this.dom.inner.innerHTML = content; } else { this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null } // update title this.dom.label.title = data && data.title || ''; if (!this.dom.inner.firstChild) { util.addClassName(this.dom.inner, 'hidden'); } else { util.removeClassName(this.dom.inner, 'hidden'); } // update className var className = data && data.className || null; if (className != this.className) { if (this.className) { util.removeClassName(this.dom.label, this.className); util.removeClassName(this.dom.foreground, this.className); util.removeClassName(this.dom.background, this.className); util.removeClassName(this.dom.axis, this.className); } util.addClassName(this.dom.label, className); util.addClassName(this.dom.foreground, className); util.addClassName(this.dom.background, className); util.addClassName(this.dom.axis, className); this.className = className; } }; /** * Get the width of the group label * @return {number} width */ Group.prototype.getLabelWidth = function() { return this.props.label.width; }; /** * Repaint this group * @param {{start: number, end: number}} range * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * @param {boolean} [restack=false] Force restacking of all items * @return {boolean} Returns true if the group is resized */ Group.prototype.redraw = function(range, margin, restack) { var resized = false; this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); // force recalculation of the height of the items when the marker height changed // (due to the Timeline being attached to the DOM or changed from display:none to visible) var markerHeight = this.dom.marker.clientHeight; if (markerHeight != this.lastMarkerHeight) { this.lastMarkerHeight = markerHeight; util.forEach(this.items, function (item) { item.dirty = true; if (item.displayed) item.redraw(); }); restack = true; } // reposition visible items vertically if (this.itemSet.options.stack) { // TODO: ugly way to access options... stack.stack(this.visibleItems, margin, restack); } else { // no stacking stack.nostack(this.visibleItems, margin); } // recalculate the height of the group var height; var visibleItems = this.visibleItems; if (visibleItems.length) { var min = visibleItems[0].top; var max = visibleItems[0].top + visibleItems[0].height; util.forEach(visibleItems, function (item) { min = Math.min(min, item.top); max = Math.max(max, (item.top + item.height)); }); if (min > margin.axis) { // there is an empty gap between the lowest item and the axis var offset = min - margin.axis; max -= offset; util.forEach(visibleItems, function (item) { item.top -= offset; }); } height = max + margin.item.vertical / 2; } else { height = margin.axis + margin.item.vertical; } height = Math.max(height, this.props.label.height); // calculate actual size and position var foreground = this.dom.foreground; this.top = foreground.offsetTop; this.left = foreground.offsetLeft; this.width = foreground.offsetWidth; resized = util.updateProperty(this, 'height', height) || resized; // recalculate size of label resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; // apply new height this.dom.background.style.height = height + 'px'; this.dom.foreground.style.height = height + 'px'; this.dom.label.style.height = height + 'px'; // update vertical position of items after they are re-stacked and the height of the group is calculated for (var i = 0, ii = this.visibleItems.length; i < ii; i++) { var item = this.visibleItems[i]; item.repositionY(); } return resized; }; /** * Show this group: attach to the DOM */ Group.prototype.show = function() { if (!this.dom.label.parentNode) { this.itemSet.dom.labelSet.appendChild(this.dom.label); } if (!this.dom.foreground.parentNode) { this.itemSet.dom.foreground.appendChild(this.dom.foreground); } if (!this.dom.background.parentNode) { this.itemSet.dom.background.appendChild(this.dom.background); } if (!this.dom.axis.parentNode) { this.itemSet.dom.axis.appendChild(this.dom.axis); } }; /** * Hide this group: remove from the DOM */ Group.prototype.hide = function() { var label = this.dom.label; if (label.parentNode) { label.parentNode.removeChild(label); } var foreground = this.dom.foreground; if (foreground.parentNode) { foreground.parentNode.removeChild(foreground); } var background = this.dom.background; if (background.parentNode) { background.parentNode.removeChild(background); } var axis = this.dom.axis; if (axis.parentNode) { axis.parentNode.removeChild(axis); } }; /** * Add an item to the group * @param {Item} item */ Group.prototype.add = function(item) { this.items[item.id] = item; item.setParent(this); if (this.visibleItems.indexOf(item) == -1) { var range = this.itemSet.body.range; // TODO: not nice accessing the range like this this._checkIfVisible(item, this.visibleItems, range); } }; /** * Remove an item from the group * @param {Item} item */ Group.prototype.remove = function(item) { delete this.items[item.id]; item.setParent(this.itemSet); // remove from visible items var index = this.visibleItems.indexOf(item); if (index != -1) this.visibleItems.splice(index, 1); // TODO: also remove from ordered items? }; /** * Remove an item from the corresponding DataSet * @param {Item} item */ Group.prototype.removeFromDataSet = function(item) { this.itemSet.removeItem(item.id); }; /** * Reorder the items */ Group.prototype.order = function() { var array = util.toArray(this.items); this.orderedItems.byStart = array; this.orderedItems.byEnd = this._constructByEndArray(array); stack.orderByStart(this.orderedItems.byStart); stack.orderByEnd(this.orderedItems.byEnd); }; /** * Create an array containing all items being a range (having an end date) * @param {Item[]} array * @returns {RangeItem[]} * @private */ Group.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof RangeItem) { endArray.push(array[i]); } } return endArray; }; /** * Update the visible items * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date * @param {Item[]} visibleItems The previously visible items. * @param {{start: number, end: number}} range Visible range * @return {Item[]} visibleItems The new visible items. * @private */ Group.prototype._updateVisibleItems = function(orderedItems, visibleItems, range) { var initialPosByStart, newVisibleItems = [], i; // first check if the items that were in view previously are still in view. // this handles the case for the RangeItem that is both before and after the current one. if (visibleItems.length > 0) { for (i = 0; i < visibleItems.length; i++) { this._checkIfVisible(visibleItems[i], newVisibleItems, range); } } // If there were no visible items previously, use binarySearch to find a visible PointItem or RangeItem (based on startTime) if (newVisibleItems.length == 0) { initialPosByStart = util.binarySearch(orderedItems.byStart, range, 'data','start'); } else { initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]); } // use visible search to find a visible RangeItem (only based on endTime) var initialPosByEnd = util.binarySearch(orderedItems.byEnd, range, 'data','end'); // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByStart != -1) { for (i = initialPosByStart; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } } // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByEnd != -1) { for (i = initialPosByEnd; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } } return newVisibleItems; }; /** * this function checks if an item is invisible. If it is NOT we make it visible * and add it to the global visible items. If it is, return true. * * @param {Item} item * @param {Item[]} visibleItems * @param {{start:number, end:number}} range * @returns {boolean} * @private */ Group.prototype._checkIfInvisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); item.repositionX(); if (visibleItems.indexOf(item) == -1) { visibleItems.push(item); } return false; } else { if (item.displayed) item.hide(); return true; } }; /** * this function is very similar to the _checkIfInvisible() but it does not * return booleans, hides the item if it should not be seen and always adds to * the visibleItems. * this one is for brute forcing and hiding. * * @param {Item} item * @param {Array} visibleItems * @param {{start:number, end:number}} range * @private */ Group.prototype._checkIfVisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); // reposition item horizontally item.repositionX(); visibleItems.push(item); } else { if (item.displayed) item.hide(); } }; module.exports = Group; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(42); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Component = __webpack_require__(18); var Group = __webpack_require__(23); var BoxItem = __webpack_require__(30); var PointItem = __webpack_require__(31); var RangeItem = __webpack_require__(32); var BackgroundItem = __webpack_require__(29); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * An ItemSet holds a set of items and ranges which can be displayed in a * range. The width is determined by the parent of the ItemSet, and the height * is determined by the size of the items. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See ItemSet.setOptions for the available options. * @constructor ItemSet * @extends Component */ function ItemSet(body, options) { this.body = body; this.defaultOptions = { type: null, // 'box', 'point', 'range', 'background' orientation: 'bottom', // 'top' or 'bottom' align: 'auto', // alignment of box items stack: true, groupOrder: null, selectable: true, editable: { updateTime: false, updateGroup: false, add: false, remove: false }, onAdd: function (item, callback) { callback(item); }, onUpdate: function (item, callback) { callback(item); }, onMove: function (item, callback) { callback(item); }, onRemove: function (item, callback) { callback(item); }, onMoving: function (item, callback) { callback(item); }, margin: { item: { horizontal: 10, vertical: 10 }, axis: 20 }, padding: 5 }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); // options for getting items from the DataSet with the correct type this.itemOptions = { type: {start: 'Date', end: 'Date'} }; this.conversion = { toScreen: body.util.toScreen, toTime: body.util.toTime }; this.dom = {}; this.props = {}; this.hammer = null; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.groups = {}; // Group object for every group this.groupIds = []; this.selection = []; // list with the ids of all selected nodes this.stackDirty = true; // if true, all items will be restacked on next redraw this.touchParams = {}; // stores properties while dragging // create the HTML DOM this._create(); this.setOptions(options); } ItemSet.prototype = new Component(); // available item types will be registered here ItemSet.types = { background: BackgroundItem, box: BoxItem, range: RangeItem, point: PointItem }; /** * Create the HTML DOM for the ItemSet */ ItemSet.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'itemset'; frame['timeline-itemset'] = this; this.dom.frame = frame; // create background panel var background = document.createElement('div'); background.className = 'background'; frame.appendChild(background); this.dom.background = background; // create foreground panel var foreground = document.createElement('div'); foreground.className = 'foreground'; frame.appendChild(foreground); this.dom.foreground = foreground; // create axis panel var axis = document.createElement('div'); axis.className = 'axis'; this.dom.axis = axis; // create labelset var labelSet = document.createElement('div'); labelSet.className = 'labelset'; this.dom.labelSet = labelSet; // create ungrouped Group this._updateUngrouped(); // attach event listeners // Note: we bind to the centerContainer for the case where the height // of the center container is larger than of the ItemSet, so we // can click in the empty area to create a new item or deselect an item. this.hammer = Hammer(this.body.dom.centerContainer, { prevent_default: true }); // drag items when selected this.hammer.on('touch', this._onTouch.bind(this)); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); // single select (or unselect) when tapping an item this.hammer.on('tap', this._onSelectItem.bind(this)); // multi select when holding mouse/touch, or on ctrl+click this.hammer.on('hold', this._onMultiSelectItem.bind(this)); // add item on doubletap this.hammer.on('doubletap', this._onAddItem.bind(this)); // attach to the DOM this.show(); }; /** * Set options for the ItemSet. Existing options will be extended/overwritten. * @param {Object} [options] The following options are available: * {String} type * Default type for the items. Choose from 'box' * (default), 'point', 'range', or 'background'. * The default style can be overwritten by * individual items. * {String} align * Alignment for the items, only applicable for * BoxItem. Choose 'center' (default), 'left', or * 'right'. * {String} orientation * Orientation of the item set. Choose 'top' or * 'bottom' (default). * {Function} groupOrder * A sorting function for ordering groups * {Boolean} stack * If true (deafult), items will be stacked on * top of each other. * {Number} margin.axis * Margin between the axis and the items in pixels. * Default is 20. * {Number} margin.item.horizontal * Horizontal margin between items in pixels. * Default is 10. * {Number} margin.item.vertical * Vertical Margin between items in pixels. * Default is 10. * {Number} margin.item * Margin between items in pixels in both horizontal * and vertical direction. Default is 10. * {Number} margin * Set margin for both axis and items in pixels. * {Number} padding * Padding of the contents of an item in pixels. * Must correspond with the items css. Default is 5. * {Boolean} selectable * If true (default), items can be selected. * {Boolean} editable * Set all editable options to true or false * {Boolean} editable.updateTime * Allow dragging an item to an other moment in time * {Boolean} editable.updateGroup * Allow dragging an item to an other group * {Boolean} editable.add * Allow creating new items on double tap * {Boolean} editable.remove * Allow removing items by clicking the delete button * top right of a selected item. * {Function(item: Item, callback: Function)} onAdd * Callback function triggered when an item is about to be added: * when the user double taps an empty space in the Timeline. * {Function(item: Item, callback: Function)} onUpdate * Callback function fired when an item is about to be updated. * This function typically has to show a dialog where the user * change the item. If not implemented, nothing happens. * {Function(item: Item, callback: Function)} onMove * Fired when an item has been moved. If not implemented, * the move action will be accepted. * {Function(item: Item, callback: Function)} onRemove * Fired when an item is about to be deleted. * If not implemented, the item will be always removed. */ ItemSet.prototype.setOptions = function(options) { if (options) { // copy all options that we know var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder', 'dataAttributes', 'template']; util.selectiveExtend(fields, this.options, options); if ('margin' in options) { if (typeof options.margin === 'number') { this.options.margin.axis = options.margin; this.options.margin.item.horizontal = options.margin; this.options.margin.item.vertical = options.margin; } else if (typeof options.margin === 'object') { util.selectiveExtend(['axis'], this.options.margin, options.margin); if ('item' in options.margin) { if (typeof options.margin.item === 'number') { this.options.margin.item.horizontal = options.margin.item; this.options.margin.item.vertical = options.margin.item; } else if (typeof options.margin.item === 'object') { util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); } } } } if ('editable' in options) { if (typeof options.editable === 'boolean') { this.options.editable.updateTime = options.editable; this.options.editable.updateGroup = options.editable; this.options.editable.add = options.editable; this.options.editable.remove = options.editable; } else if (typeof options.editable === 'object') { util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); } } // callback functions var addCallback = (function (name) { var fn = options[name]; if (fn) { if (!(fn instanceof Function)) { throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)'); } this.options[name] = fn; } }).bind(this); ['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback); // force the itemSet to refresh: options like orientation and margins may be changed this.markDirty(); } }; /** * Mark the ItemSet dirty so it will refresh everything with next redraw */ ItemSet.prototype.markDirty = function() { this.groupIds = []; this.stackDirty = true; }; /** * Destroy the ItemSet */ ItemSet.prototype.destroy = function() { this.hide(); this.setItems(null); this.setGroups(null); this.hammer = null; this.body = null; this.conversion = null; }; /** * Hide the component from the DOM */ ItemSet.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } // remove the axis with dots if (this.dom.axis.parentNode) { this.dom.axis.parentNode.removeChild(this.dom.axis); } // remove the labelset containing all group labels if (this.dom.labelSet.parentNode) { this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ ItemSet.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } // show axis with dots if (!this.dom.axis.parentNode) { this.body.dom.backgroundVertical.appendChild(this.dom.axis); } // show labelset containing labels if (!this.dom.labelSet.parentNode) { this.body.dom.left.appendChild(this.dom.labelSet); } }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {string[] | string} [ids] An array with zero or more id's of the items to be * selected, or a single item id. If ids is undefined * or an empty array, all items will be unselected. */ ItemSet.prototype.setSelection = function(ids) { var i, ii, id, item; if (ids == undefined) ids = []; if (!Array.isArray(ids)) ids = [ids]; // unselect currently selected items for (i = 0, ii = this.selection.length; i < ii; i++) { id = this.selection[i]; item = this.items[id]; if (item) item.unselect(); } // select items this.selection = []; for (i = 0, ii = ids.length; i < ii; i++) { id = ids[i]; item = this.items[id]; if (item) { this.selection.push(id); item.select(); } } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ ItemSet.prototype.getSelection = function() { return this.selection.concat([]); }; /** * Get the id's of the currently visible items. * @returns {Array} The ids of the visible items */ ItemSet.prototype.getVisibleItems = function() { var range = this.body.range.getRange(); var left = this.body.util.toScreen(range.start); var right = this.body.util.toScreen(range.end); var ids = []; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { var group = this.groups[groupId]; var rawVisibleItems = group.visibleItems; // filter the "raw" set with visibleItems into a set which is really // visible by pixels for (var i = 0; i < rawVisibleItems.length; i++) { var item = rawVisibleItems[i]; // TODO: also check whether visible vertically if ((item.left < right) && (item.left + item.width > left)) { ids.push(item.id); } } } } return ids; }; /** * Deselect a selected item * @param {String | Number} id * @private */ ItemSet.prototype._deselect = function(id) { var selection = this.selection; for (var i = 0, ii = selection.length; i < ii; i++) { if (selection[i] == id) { // non-strict comparison! selection.splice(i, 1); break; } } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ ItemSet.prototype.redraw = function() { var margin = this.options.margin, range = this.body.range, asSize = util.option.asSize, options = this.options, orientation = options.orientation, resized = false, frame = this.dom.frame, editable = options.editable.updateTime || options.editable.updateGroup; // recalculate absolute position (before redrawing groups) this.props.top = this.body.domProps.top.height + this.body.domProps.border.top; this.props.left = this.body.domProps.left.width + this.body.domProps.border.left; // update class name frame.className = 'itemset' + (editable ? ' editable' : ''); // reorder the groups (if needed) resized = this._orderGroups() || resized; // check whether zoomed (in that case we need to re-stack everything) // TODO: would be nicer to get this as a trigger from Range var visibleInterval = range.end - range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth); if (zoomed) this.stackDirty = true; this.lastVisibleInterval = visibleInterval; this.props.lastWidth = this.props.width; // redraw all groups var restack = this.stackDirty, firstGroup = this._firstGroup(), firstMargin = { item: margin.item, axis: margin.axis }, nonFirstMargin = { item: margin.item, axis: margin.item.vertical / 2 }, height = 0, minHeight = margin.axis + margin.item.vertical; util.forEach(this.groups, function (group) { var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin; var groupResized = group.redraw(range, groupMargin, restack); resized = groupResized || resized; height += group.height; }); height = Math.max(height, minHeight); this.stackDirty = false; // update frame height frame.style.height = asSize(height); // calculate actual size this.props.width = frame.offsetWidth; this.props.height = height; // reposition axis // reposition axis this.dom.axis.style.top = asSize((orientation == 'top') ? (this.body.domProps.top.height + this.body.domProps.border.top) : (this.body.domProps.top.height + this.body.domProps.centerContainer.height)); this.dom.axis.style.left = '0'; // check if this component is resized resized = this._isResized() || resized; return resized; }; /** * Get the first group, aligned with the axis * @return {Group | null} firstGroup * @private */ ItemSet.prototype._firstGroup = function() { var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1); var firstGroupId = this.groupIds[firstGroupIndex]; var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED]; return firstGroup || null; }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. * @protected */ ItemSet.prototype._updateUngrouped = function() { var ungrouped = this.groups[UNGROUPED]; if (this.groupsData) { // remove the group holding all ungrouped items if (ungrouped) { ungrouped.hide(); delete this.groups[UNGROUPED]; } } else { // create a group holding all (unfiltered) items if (!ungrouped) { var id = null; var data = null; ungrouped = new Group(id, data, this); this.groups[UNGROUPED] = ungrouped; for (var itemId in this.items) { if (this.items.hasOwnProperty(itemId)) { ungrouped.add(this.items[itemId]); } } ungrouped.show(); } } }; /** * Get the element for the labelset * @return {HTMLElement} labelSet */ ItemSet.prototype.getLabelSet = function() { return this.dom.labelSet; }; /** * Set items * @param {vis.DataSet | null} items */ ItemSet.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); // update the group holding all ungrouped items this._updateUngrouped(); } }; /** * Get the current items * @returns {vis.DataSet | null} */ ItemSet.prototype.getItems = function() { return this.itemsData; }; /** * Set groups * @param {vis.DataSet} groups */ ItemSet.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } // update the group holding all ungrouped items this._updateUngrouped(); // update the order of all items in each group this._order(); this.body.emitter.emit('change'); }; /** * Get the current groups * @returns {vis.DataSet | null} groups */ ItemSet.prototype.getGroups = function() { return this.groupsData; }; /** * Remove an item by its id * @param {String | Number} id */ ItemSet.prototype.removeItem = function(id) { var item = this.itemsData.get(id), dataset = this.itemsData.getDataSet(); if (item) { // confirm deletion this.options.onRemove(item, function (item) { if (item) { // remove by id here, it is possible that an item has no id defined // itself, so better not delete by the item itself dataset.remove(id); } }); } }; /** * Handle updated items * @param {Number[]} ids * @protected */ ItemSet.prototype._onUpdate = function(ids) { var me = this; ids.forEach(function (id) { var itemData = me.itemsData.get(id, me.itemOptions), item = me.items[id], type = itemData.type || me.options.type || (itemData.end ? 'range' : 'box'); var constructor = ItemSet.types[type]; if (item) { // update item if (!constructor || !(item instanceof constructor)) { // item type has changed, delete the item and recreate it me._removeItem(item); item = null; } else { me._updateItem(item, itemData); } } if (!item) { // create item if (constructor) { item = new constructor(itemData, me.conversion, me.options); item.id = id; // TODO: not so nice setting id afterwards me._addItem(item); } else if (type == 'rangeoverflow') { // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' + '.vis.timeline .item.range .content {overflow: visible;}'); } else { throw new TypeError('Unknown item type "' + type + '"'); } } }); this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); }; /** * Handle added items * @param {Number[]} ids * @protected */ ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; /** * Handle removed items * @param {Number[]} ids * @protected */ ItemSet.prototype._onRemove = function(ids) { var count = 0; var me = this; ids.forEach(function (id) { var item = me.items[id]; if (item) { count++; me._removeItem(item); } }); if (count) { // update order this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); } }; /** * Update the order of item in all groups * @private */ ItemSet.prototype._order = function() { // reorder the items in all groups // TODO: optimization: only reorder groups affected by the changed items util.forEach(this.groups, function (group) { group.order(); }); }; /** * Handle updated groups * @param {Number[]} ids * @private */ ItemSet.prototype._onUpdateGroups = function(ids) { this._onAddGroups(ids); }; /** * Handle changed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onAddGroups = function(ids) { var me = this; ids.forEach(function (id) { var groupData = me.groupsData.get(id); var group = me.groups[id]; if (!group) { // check for reserved ids if (id == UNGROUPED) { throw new Error('Illegal group id. ' + id + ' is a reserved id.'); } var groupOptions = Object.create(me.options); util.extend(groupOptions, { height: null }); group = new Group(id, groupData, me); me.groups[id] = group; // add items with this groupId to the new group for (var itemId in me.items) { if (me.items.hasOwnProperty(itemId)) { var item = me.items[itemId]; if (item.data.group == id) { group.add(item); } } } group.order(); group.show(); } else { // update group group.setData(groupData); } }); this.body.emitter.emit('change'); }; /** * Handle removed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onRemoveGroups = function(ids) { var groups = this.groups; ids.forEach(function (id) { var group = groups[id]; if (group) { group.hide(); delete groups[id]; } }); this.markDirty(); this.body.emitter.emit('change'); }; /** * Reorder the groups if needed * @return {boolean} changed * @private */ ItemSet.prototype._orderGroups = function () { if (this.groupsData) { // reorder the groups var groupIds = this.groupsData.getIds({ order: this.options.groupOrder }); var changed = !util.equalArray(groupIds, this.groupIds); if (changed) { // hide all groups, removes them from the DOM var groups = this.groups; groupIds.forEach(function (groupId) { groups[groupId].hide(); }); // show the groups again, attach them to the DOM in correct order groupIds.forEach(function (groupId) { groups[groupId].show(); }); this.groupIds = groupIds; } return changed; } else { return false; } }; /** * Add a new item * @param {Item} item * @private */ ItemSet.prototype._addItem = function(item) { this.items[item.id] = item; // add to group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); }; /** * Update an existing item * @param {Item} item * @param {Object} itemData * @private */ ItemSet.prototype._updateItem = function(item, itemData) { var oldGroupId = item.data.group; // update the items data (will redraw the item when displayed) item.setData(itemData); // update group if (oldGroupId != item.data.group) { var oldGroup = this.groups[oldGroupId]; if (oldGroup) oldGroup.remove(item); var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); } }; /** * Delete an item from the ItemSet: remove it from the DOM, from the map * with items, and from the map with visible items, and from the selection * @param {Item} item * @private */ ItemSet.prototype._removeItem = function(item) { // remove from DOM item.hide(); // remove from items delete this.items[item.id]; // remove from selection var index = this.selection.indexOf(item.id); if (index != -1) this.selection.splice(index, 1); // remove from group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.remove(item); }; /** * Create an array containing all items being a range (having an end date) * @param array * @returns {Array} * @private */ ItemSet.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof RangeItem) { endArray.push(array[i]); } } return endArray; }; /** * Register the clicked item on touch, before dragStart is initiated. * * dragStart is initiated from a mousemove event, which can have left the item * already resulting in an item == null * * @param {Event} event * @private */ ItemSet.prototype._onTouch = function (event) { // store the touched item, used in _onDragStart this.touchParams.item = ItemSet.itemFromTarget(event); }; /** * Start dragging the selected events * @param {Event} event * @private */ ItemSet.prototype._onDragStart = function (event) { if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { return; } var item = this.touchParams.item || null, me = this, props; if (item && item.selected) { var dragLeftItem = event.target.dragLeftItem; var dragRightItem = event.target.dragRightItem; if (dragLeftItem) { props = { item: dragLeftItem }; if (me.options.editable.updateTime) { props.start = item.data.start.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else if (dragRightItem) { props = { item: dragRightItem }; if (me.options.editable.updateTime) { props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else { this.touchParams.itemProps = this.getSelection().map(function (id) { var item = me.items[id]; var props = { item: item }; if (me.options.editable.updateTime) { if ('start' in item.data) props.start = item.data.start.valueOf(); if ('end' in item.data) props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } return props; }); } event.stopPropagation(); } }; /** * Drag selected items * @param {Event} event * @private */ ItemSet.prototype._onDrag = function (event) { if (this.touchParams.itemProps) { var me = this; var range = this.body.range; var snap = this.body.util.snap || null; var deltaX = event.gesture.deltaX; var scale = (this.props.width / (range.end - range.start)); var offset = deltaX / scale; // move this.touchParams.itemProps.forEach(function (props) { var newProps = {}; if ('start' in props) { var start = new Date(props.start + offset); newProps.start = snap ? snap(start) : start; } if ('end' in props) { var end = new Date(props.end + offset); newProps.end = snap ? snap(end) : end; } if ('group' in props) { // drag from one group to another var group = ItemSet.groupFromTarget(event); newProps.group = group && group.groupId; } // confirm moving the item var itemData = util.extend({}, props.item.data, newProps); me.options.onMoving(itemData, function (itemData) { if (itemData) { me._updateItemProps(props.item, itemData); } }); }); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); event.stopPropagation(); } }; /** * Update an items properties * @param {Item} item * @param {Object} props Can contain properties start, end, and group. * @private */ ItemSet.prototype._updateItemProps = function(item, props) { // TODO: copy all properties from props to item? (also new ones) if ('start' in props) item.data.start = props.start; if ('end' in props) item.data.end = props.end; if ('group' in props && item.data.group != props.group) { this._moveToGroup(item, props.group) } }; /** * Move an item to another group * @param {Item} item * @param {String | Number} groupId * @private */ ItemSet.prototype._moveToGroup = function(item, groupId) { var group = this.groups[groupId]; if (group && group.groupId != item.data.group) { var oldGroup = item.parent; oldGroup.remove(item); oldGroup.order(); group.add(item); group.order(); item.data.group = group.groupId; } }; /** * End of dragging selected items * @param {Event} event * @private */ ItemSet.prototype._onDragEnd = function (event) { if (this.touchParams.itemProps) { // prepare a change set for the changed items var changes = [], me = this, dataset = this.itemsData.getDataSet(); var itemProps = this.touchParams.itemProps ; this.touchParams.itemProps = null; itemProps.forEach(function (props) { var id = props.item.id, itemData = me.itemsData.get(id, me.itemOptions); var changed = false; if ('start' in props.item.data) { changed = (props.start != props.item.data.start.valueOf()); itemData.start = util.convert(props.item.data.start, dataset._options.type && dataset._options.type.start || 'Date'); } if ('end' in props.item.data) { changed = changed || (props.end != props.item.data.end.valueOf()); itemData.end = util.convert(props.item.data.end, dataset._options.type && dataset._options.type.end || 'Date'); } if ('group' in props.item.data) { changed = changed || (props.group != props.item.data.group); itemData.group = props.item.data.group; } // only apply changes when start or end is actually changed if (changed) { me.options.onMove(itemData, function (itemData) { if (itemData) { // apply changes itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) changes.push(itemData); } else { // restore original values me._updateItemProps(props.item, props); me.stackDirty = true; // force re-stacking of all items next redraw me.body.emitter.emit('change'); } }); } }); // apply the changes to the data (if there are changes) if (changes.length) { dataset.update(changes); } event.stopPropagation(); } }; /** * Handle selecting/deselecting an item when tapping it * @param {Event} event * @private */ ItemSet.prototype._onSelectItem = function (event) { if (!this.options.selectable) return; var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey; var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey; if (ctrlKey || shiftKey) { this._onMultiSelectItem(event); return; } var oldSelection = this.getSelection(); var item = ItemSet.itemFromTarget(event); var selection = item ? [item.id] : []; this.setSelection(selection); var newSelection = this.getSelection(); // emit a select event, // except when old selection is empty and new selection is still empty if (newSelection.length > 0 || oldSelection.length > 0) { this.body.emitter.emit('select', { items: this.getSelection() }); } event.stopPropagation(); }; /** * Handle creation and updates of an item on double tap * @param event * @private */ ItemSet.prototype._onAddItem = function (event) { if (!this.options.selectable) return; if (!this.options.editable.add) return; var me = this, snap = this.body.util.snap || null, item = ItemSet.itemFromTarget(event); if (item) { // update item // execute async handler to update the item (or cancel it) var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset this.options.onUpdate(itemData, function (itemData) { if (itemData) { me.itemsData.update(itemData); } }); } else { // add item var xAbs = util.getAbsoluteLeft(this.dom.frame); var x = event.gesture.center.pageX - xAbs; var start = this.body.util.toTime(x); var newItem = { start: snap ? snap(start) : start, content: 'new item' }; // when default type is a range, add a default end date to the new item if (this.options.type === 'range') { var end = this.body.util.toTime(x + this.props.width / 5); newItem.end = snap ? snap(end) : end; } newItem[this.itemsData._fieldId] = util.randomUUID(); var group = ItemSet.groupFromTarget(event); if (group) { newItem.group = group.groupId; } // execute async handler to customize (or cancel) adding an item this.options.onAdd(newItem, function (item) { if (item) { me.itemsData.add(item); // TODO: need to trigger a redraw? } }); } }; /** * Handle selecting/deselecting multiple items when holding an item * @param {Event} event * @private */ ItemSet.prototype._onMultiSelectItem = function (event) { if (!this.options.selectable) return; var selection, item = ItemSet.itemFromTarget(event); if (item) { // multi select items selection = this.getSelection(); // current selection var index = selection.indexOf(item.id); if (index == -1) { // item is not yet selected -> select it selection.push(item.id); } else { // item is already selected -> deselect it selection.splice(index, 1); } this.setSelection(selection); this.body.emitter.emit('select', { items: this.getSelection() }); event.stopPropagation(); } }; /** * Find an item from an event target: * searches for the attribute 'timeline-item' in the event target's element tree * @param {Event} event * @return {Item | null} item */ ItemSet.itemFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-item')) { return target['timeline-item']; } target = target.parentNode; } return null; }; /** * Find the Group from an event target: * searches for the attribute 'timeline-group' in the event target's element tree * @param {Event} event * @return {Group | null} group */ ItemSet.groupFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-group')) { return target['timeline-group']; } target = target.parentNode; } return null; }; /** * Find the ItemSet from an event target: * searches for the attribute 'timeline-itemset' in the event target's element tree * @param {Event} event * @return {ItemSet | null} item */ ItemSet.itemSetFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-itemset')) { return target['timeline-itemset']; } target = target.parentNode; } return null; }; module.exports = ItemSet; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var Component = __webpack_require__(18); /** * Legend for Graph2d */ function Legend(body, options, side, linegraphOptions) { this.body = body; this.defaultOptions = { enabled: true, icons: true, iconSize: 20, iconSpacing: 6, left: { visible: true, position: 'top-left' // top/bottom - left,center,right }, right: { visible: true, position: 'top-left' // top/bottom - left,center,right } } this.side = side; this.options = util.extend({},this.defaultOptions); this.linegraphOptions = linegraphOptions; this.svgElements = {}; this.dom = {}; this.groups = {}; this.amountOfGroups = 0; this._create(); this.setOptions(options); } Legend.prototype = new Component(); Legend.prototype.addGroup = function(label, graphOptions) { if (!this.groups.hasOwnProperty(label)) { this.groups[label] = graphOptions; } this.amountOfGroups += 1; }; Legend.prototype.updateGroup = function(label, graphOptions) { this.groups[label] = graphOptions; }; Legend.prototype.removeGroup = function(label) { if (this.groups.hasOwnProperty(label)) { delete this.groups[label]; this.amountOfGroups -= 1; } }; Legend.prototype._create = function() { this.dom.frame = document.createElement('div'); this.dom.frame.className = 'legend'; this.dom.frame.style.position = "absolute"; this.dom.frame.style.top = "10px"; this.dom.frame.style.display = "block"; this.dom.textArea = document.createElement('div'); this.dom.textArea.className = 'legendText'; this.dom.textArea.style.position = "relative"; this.dom.textArea.style.top = "0px"; this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = 'absolute'; this.svg.style.top = 0 +'px'; this.svg.style.width = this.options.iconSize + 5 + 'px'; this.dom.frame.appendChild(this.svg); this.dom.frame.appendChild(this.dom.textArea); }; /** * Hide the component from the DOM */ Legend.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ Legend.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } }; Legend.prototype.setOptions = function(options) { var fields = ['enabled','orientation','icons','left','right']; util.selectiveDeepExtend(fields, this.options, options); }; Legend.prototype.redraw = function() { var activeGroups = 0; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { activeGroups++; } } } if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) { this.hide(); } else { this.show(); if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { this.dom.frame.style.left = '4px'; this.dom.frame.style.textAlign = "left"; this.dom.textArea.style.textAlign = "left"; this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px'; this.dom.textArea.style.right = ''; this.svg.style.left = 0 +'px'; this.svg.style.right = ''; } else { this.dom.frame.style.right = '4px'; this.dom.frame.style.textAlign = "right"; this.dom.textArea.style.textAlign = "right"; this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px'; this.dom.textArea.style.left = ''; this.svg.style.right = 0 +'px'; this.svg.style.left = ''; } if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px'; this.dom.frame.style.bottom = ''; } else { this.dom.frame.style.bottom = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px'; this.dom.frame.style.top = ''; } if (this.options.icons == false) { this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; this.dom.textArea.style.right = ''; this.dom.textArea.style.left = ''; this.svg.style.width = '0px'; } else { this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px' this.drawLegendIcons(); } var content = ''; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { content += this.groups[groupId].content + '<br />'; } } } this.dom.textArea.innerHTML = content; this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px'; } }; Legend.prototype.drawLegendIcons = function() { if (this.dom.frame.parentNode) { DOMutil.prepareElements(this.svgElements); var padding = window.getComputedStyle(this.dom.frame).paddingTop; var iconOffset = Number(padding.replace('px','')); var x = iconOffset; var iconWidth = this.options.iconSize; var iconHeight = 0.75 * this.options.iconSize; var y = iconOffset + 0.5 * iconHeight + 3; this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) { this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); y += iconHeight + this.options.iconSpacing; } } } DOMutil.cleanupElements(this.svgElements); } }; module.exports = Legend; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Component = __webpack_require__(18); var DataAxis = __webpack_require__(21); var GraphGroup = __webpack_require__(22); var Legend = __webpack_require__(25); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * This is the constructor of the LineGraph. It requires a Timeline body and options. * * @param body * @param options * @constructor */ function LineGraph(body, options) { this.id = util.randomUUID(); this.body = body; this.defaultOptions = { yAxisOrientation: 'left', defaultGroup: 'default', sort: true, sampling: true, graphHeight: '400px', shaded: { enabled: false, orientation: 'bottom' // top, bottom }, style: 'line', // line, bar barChart: { width: 50, handleOverlap: 'overlap', align: 'center' // left, center, right }, catmullRom: { enabled: true, parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) alpha: 0.5 }, drawPoints: { enabled: true, size: 6, style: 'square' // square, circle }, dataAxis: { showMinorLabels: true, showMajorLabels: true, icons: false, width: '40px', visible: true, customRange: { left: {min:undefined, max:undefined}, right: {min:undefined, max:undefined} } }, legend: { enabled: false, icons: true, left: { visible: true, position: 'top-left' // top/bottom - left,right }, right: { visible: true, position: 'top-right' // top/bottom - left,right } }, groups: { visibility: {} } }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); this.dom = {}; this.props = {}; this.hammer = null; this.groups = {}; this.abortedGraphUpdate = false; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.selection = []; // list with the ids of all selected nodes this.lastStart = this.body.range.start; this.touchParams = {}; // stores properties while dragging this.svgElements = {}; this.setOptions(options); this.groupsUsingDefaultStyles = [0]; this.body.emitter.on("rangechanged", function() { me.lastStart = me.body.range.start; me.svg.style.left = util.option.asSize(-me.width); me._updateGraph.apply(me); }); // create the HTML DOM this._create(); this.body.emitter.emit("change"); } LineGraph.prototype = new Component(); /** * Create the HTML DOM for the ItemSet */ LineGraph.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'LineGraph'; this.dom.frame = frame; // create svg element for graph drawing. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = "relative"; this.svg.style.height = ('' + this.options.graphHeight).replace("px",'') + 'px'; this.svg.style.display = "block"; frame.appendChild(this.svg); // data axis this.options.dataAxis.orientation = 'left'; this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); this.options.dataAxis.orientation = 'right'; this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups); delete this.options.dataAxis.orientation; // legends this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups); this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups); this.show(); }; /** * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. * @param options */ LineGraph.prototype.setOptions = function(options) { if (options) { var fields = ['sampling','defaultGroup','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort','groups']; util.selectiveDeepExtend(fields, this.options, options); util.mergeOptions(this.options, options,'catmullRom'); util.mergeOptions(this.options, options,'drawPoints'); util.mergeOptions(this.options, options,'shaded'); util.mergeOptions(this.options, options,'legend'); if (options.catmullRom) { if (typeof options.catmullRom == 'object') { if (options.catmullRom.parametrization) { if (options.catmullRom.parametrization == 'uniform') { this.options.catmullRom.alpha = 0; } else if (options.catmullRom.parametrization == 'chordal') { this.options.catmullRom.alpha = 1.0; } else { this.options.catmullRom.parametrization = 'centripetal'; this.options.catmullRom.alpha = 0.5; } } } } if (this.yAxisLeft) { if (options.dataAxis !== undefined) { this.yAxisLeft.setOptions(this.options.dataAxis); this.yAxisRight.setOptions(this.options.dataAxis); } } if (this.legendLeft) { if (options.legend !== undefined) { this.legendLeft.setOptions(this.options.legend); this.legendRight.setOptions(this.options.legend); } } if (this.groups.hasOwnProperty(UNGROUPED)) { this.groups[UNGROUPED].setOptions(options); } } if (this.dom.frame) { this._updateGraph(); } }; /** * Hide the component from the DOM */ LineGraph.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ LineGraph.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } }; /** * Set items * @param {vis.DataSet | null} items */ LineGraph.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); } this._updateUngrouped(); this._updateGraph(); this.redraw(); }; /** * Set groups * @param {vis.DataSet} groups */ LineGraph.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } this._onUpdate(); }; /** * Update the datapoints * @param [ids] * @private */ LineGraph.prototype._onUpdate = function(ids) { this._updateUngrouped(); this._updateAllGroupData(); this._updateGraph(); this.redraw(); }; LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);}; LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);}; LineGraph.prototype._onUpdateGroups = function (groupIds) { for (var i = 0; i < groupIds.length; i++) { var group = this.groupsData.get(groupIds[i]); this._updateGroup(group, groupIds[i]); } this._updateGraph(); this.redraw(); }; LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);}; LineGraph.prototype._onRemoveGroups = function (groupIds) { for (var i = 0; i < groupIds.length; i++) { if (!this.groups.hasOwnProperty(groupIds[i])) { if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { this.yAxisRight.removeGroup(groupIds[i]); this.legendRight.removeGroup(groupIds[i]); this.legendRight.redraw(); } else { this.yAxisLeft.removeGroup(groupIds[i]); this.legendLeft.removeGroup(groupIds[i]); this.legendLeft.redraw(); } delete this.groups[groupIds[i]]; } } this._updateUngrouped(); this._updateGraph(); this.redraw(); }; /** * update a group object * * @param group * @param groupId * @private */ LineGraph.prototype._updateGroup = function (group, groupId) { if (!this.groups.hasOwnProperty(groupId)) { this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); if (this.groups[groupId].options.yAxisOrientation == 'right') { this.yAxisRight.addGroup(groupId, this.groups[groupId]); this.legendRight.addGroup(groupId, this.groups[groupId]); } else { this.yAxisLeft.addGroup(groupId, this.groups[groupId]); this.legendLeft.addGroup(groupId, this.groups[groupId]); } } else { this.groups[groupId].update(group); if (this.groups[groupId].options.yAxisOrientation == 'right') { this.yAxisRight.updateGroup(groupId, this.groups[groupId]); this.legendRight.updateGroup(groupId, this.groups[groupId]); } else { this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); this.legendLeft.updateGroup(groupId, this.groups[groupId]); } } this.legendLeft.redraw(); this.legendRight.redraw(); }; LineGraph.prototype._updateAllGroupData = function () { if (this.itemsData != null) { var groupsContent = {}; var groupId; for (groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { groupsContent[groupId] = []; } } for (var itemId in this.itemsData._data) { if (this.itemsData._data.hasOwnProperty(itemId)) { var item = this.itemsData._data[itemId]; item.x = util.convert(item.x,"Date"); groupsContent[item.group].push(item); } } for (groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { this.groups[groupId].setItems(groupsContent[groupId]); } } } }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. This anonymous group is called 'graph'. * @protected */ LineGraph.prototype._updateUngrouped = function() { if (this.itemsData && this.itemsData != null) { var ungroupedCounter = 0; for (var itemId in this.itemsData._data) { if (this.itemsData._data.hasOwnProperty(itemId)) { var item = this.itemsData._data[itemId]; if (item != undefined) { if (item.hasOwnProperty('group')) { if (item.group === undefined) { item.group = UNGROUPED; } } else { item.group = UNGROUPED; } ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; } } } if (ungroupedCounter == 0) { delete this.groups[UNGROUPED]; this.legendLeft.removeGroup(UNGROUPED); this.legendRight.removeGroup(UNGROUPED); this.yAxisLeft.removeGroup(UNGROUPED); this.yAxisRight.removeGroup(UNGROUPED); } else { var group = {id: UNGROUPED, content: this.options.defaultGroup}; this._updateGroup(group, UNGROUPED); } } else { delete this.groups[UNGROUPED]; this.legendLeft.removeGroup(UNGROUPED); this.legendRight.removeGroup(UNGROUPED); this.yAxisLeft.removeGroup(UNGROUPED); this.yAxisRight.removeGroup(UNGROUPED); } this.legendLeft.redraw(); this.legendRight.redraw(); }; /** * Redraw the component, mandatory function * @return {boolean} Returns true if the component is resized */ LineGraph.prototype.redraw = function() { var resized = false; this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px'; if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) { resized = true; } // check if this component is resized resized = this._isResized() || resized; // check whether zoomed (in that case we need to re-stack everything) var visibleInterval = this.body.range.end - this.body.range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth); this.lastVisibleInterval = visibleInterval; this.lastWidth = this.width; // calculate actual size and position this.width = this.dom.frame.offsetWidth; // the svg element is three times as big as the width, this allows for fully dragging left and right // without reloading the graph. the controls for this are bound to events in the constructor if (resized == true) { this.svg.style.width = util.option.asSize(3*this.width); this.svg.style.left = util.option.asSize(-this.width); } if (zoomed == true || this.abortedGraphUpdate == true) { this._updateGraph(); } else { // move the whole svg while dragging if (this.lastStart != 0) { var offset = this.body.range.start - this.lastStart; var range = this.body.range.end - this.body.range.start; if (this.width != 0) { var rangePerPixelInv = this.width/range; var xOffset = offset * rangePerPixelInv; this.svg.style.left = (-this.width - xOffset) + "px"; } } } this.legendLeft.redraw(); this.legendRight.redraw(); return resized; }; /** * Update and redraw the graph. * */ LineGraph.prototype._updateGraph = function () { // reset the svg elements DOMutil.prepareElements(this.svgElements); if (this.width != 0 && this.itemsData != null) { var group, i; var preprocessedGroupData = {}; var processedGroupData = {}; var groupRanges = {}; var changeCalled = false; // getting group Ids var groupIds = []; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { group = this.groups[groupId]; if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) { groupIds.push(groupId); } } } if (groupIds.length > 0) { // this is the range of the SVG canvas var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width); var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); var groupsData = {}; // fill groups data this._getRelevantData(groupIds, groupsData, minDate, maxDate); // we transform the X coordinates to detect collisions for (i = 0; i < groupIds.length; i++) { preprocessedGroupData[groupIds[i]] = this._convertXcoordinates(groupsData[groupIds[i]]); } // now all needed data has been collected we start the processing. this._getYRanges(groupIds, preprocessedGroupData, groupRanges); // update the Y axis first, we use this data to draw at the correct Y points // changeCalled is required to clean the SVG on a change emit. changeCalled = this._updateYAxis(groupIds, groupRanges); if (changeCalled == true) { DOMutil.cleanupElements(this.svgElements); this.abortedGraphUpdate = true; this.body.emitter.emit("change"); return; } this.abortedGraphUpdate = false; // With the yAxis scaled correctly, use this to get the Y values of the points. for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; processedGroupData[groupIds[i]] = this._convertYcoordinates(groupsData[groupIds[i]], group); } // draw the groups for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; if (group.options.style == 'line') { this._drawLineGraph(processedGroupData[groupIds[i]], group); } } this._drawBarGraphs(groupIds, processedGroupData); } } // cleanup unused svg elements DOMutil.cleanupElements(this.svgElements); }; LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) { // first select and preprocess the data from the datasets. // the groups have their preselection of data, we now loop over this data to see // what data we need to draw. Sorted data is much faster. // more optimization is possible by doing the sampling before and using the binary search // to find the end date to determine the increment. var group, i, j, item; if (groupIds.length > 0) { for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; groupsData[groupIds[i]] = []; var dataContainer = groupsData[groupIds[i]]; // optimization for sorted data if (group.options.sort == true) { var guess = Math.max(0, util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before')); for (j = guess; j < group.itemsData.length; j++) { item = group.itemsData[j]; if (item !== undefined) { if (item.x > maxDate) { dataContainer.push(item); break; } else { dataContainer.push(item); } } } } else { for (j = 0; j < group.itemsData.length; j++) { item = group.itemsData[j]; if (item !== undefined) { if (item.x > minDate && item.x < maxDate) { dataContainer.push(item); } } } } } } this._applySampling(groupIds, groupsData); }; LineGraph.prototype._applySampling = function (groupIds, groupsData) { var group; if (groupIds.length > 0) { for (var i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; if (group.options.sampling == true) { var dataContainer = groupsData[groupIds[i]]; if (dataContainer.length > 0) { var increment = 1; var amountOfPoints = dataContainer.length; // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop // of width changing of the yAxis. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x); var pointsPerPixel = amountOfPoints / xDistance; increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel))); var sampledData = []; for (var j = 0; j < amountOfPoints; j += increment) { sampledData.push(dataContainer[j]); } groupsData[groupIds[i]] = sampledData; } } } } }; LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) { var groupData, group, i,j; var barCombinedDataLeft = []; var barCombinedDataRight = []; var barCombinedData; if (groupIds.length > 0) { for (i = 0; i < groupIds.length; i++) { groupData = groupsData[groupIds[i]]; if (groupData.length > 0) { group = this.groups[groupIds[i]]; if (group.options.style == 'line' || group.options.barChart.handleOverlap != "stack") { var yMin = groupData[0].y; var yMax = groupData[0].y; for (j = 0; j < groupData.length; j++) { yMin = yMin > groupData[j].y ? groupData[j].y : yMin; yMax = yMax < groupData[j].y ? groupData[j].y : yMax; } groupRanges[groupIds[i]] = {min: yMin, max: yMax, yAxisOrientation: group.options.yAxisOrientation}; } else if (group.options.style == 'bar') { if (group.options.yAxisOrientation == 'left') { barCombinedData = barCombinedDataLeft; } else { barCombinedData = barCombinedDataRight; } groupRanges[groupIds[i]] = {min: 0, max: 0, yAxisOrientation: group.options.yAxisOrientation, ignore: true}; // combine data for (j = 0; j < groupData.length; j++) { barCombinedData.push({ x: groupData[j].x, y: groupData[j].y, groupId: groupIds[i] }); } } } } var intersections; if (barCombinedDataLeft.length > 0) { // sort by time and by group barCombinedDataLeft.sort(function (a, b) { if (a.x == b.x) { return a.groupId - b.groupId; } else { return a.x - b.x; } }); intersections = {}; this._getDataIntersections(intersections, barCombinedDataLeft); groupRanges["__barchartLeft"] = this._getStackedBarYRange(intersections, barCombinedDataLeft); groupRanges["__barchartLeft"].yAxisOrientation = "left"; groupIds.push("__barchartLeft"); } if (barCombinedDataRight.length > 0) { // sort by time and by group barCombinedDataRight.sort(function (a, b) { if (a.x == b.x) { return a.groupId - b.groupId; } else { return a.x - b.x; } }); intersections = {}; this._getDataIntersections(intersections, barCombinedDataRight); groupRanges["__barchartRight"] = this._getStackedBarYRange(intersections, barCombinedDataRight); groupRanges["__barchartRight"].yAxisOrientation = "right"; groupIds.push("__barchartRight"); } } }; LineGraph.prototype._getStackedBarYRange = function (intersections, combinedData) { var key; var yMin = combinedData[0].y; var yMax = combinedData[0].y; for (var i = 0; i < combinedData.length; i++) { key = combinedData[i].x; if (intersections[key] === undefined) { yMin = yMin > combinedData[i].y ? combinedData[i].y : yMin; yMax = yMax < combinedData[i].y ? combinedData[i].y : yMax; } else { intersections[key].accumulated += combinedData[i].y; } } for (var xpos in intersections) { if (intersections.hasOwnProperty(xpos)) { yMin = yMin > intersections[xpos].accumulated ? intersections[xpos].accumulated : yMin; yMax = yMax < intersections[xpos].accumulated ? intersections[xpos].accumulated : yMax; } } return {min: yMin, max: yMax}; }; /** * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. * @param {Array} groupIds * @param {Object} groupRanges * @private */ LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { var changeCalled = false; var yAxisLeftUsed = false; var yAxisRightUsed = false; var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal; // if groups are present if (groupIds.length > 0) { for (var i = 0; i < groupIds.length; i++) { if (groupRanges.hasOwnProperty(groupIds[i])) { if (groupRanges[groupIds[i]].ignore !== true) { minVal = groupRanges[groupIds[i]].min; maxVal = groupRanges[groupIds[i]].max; if (groupRanges[groupIds[i]].yAxisOrientation == 'left') { yAxisLeftUsed = true; minLeft = minLeft > minVal ? minVal : minLeft; maxLeft = maxLeft < maxVal ? maxVal : maxLeft; } else { yAxisRightUsed = true; minRight = minRight > minVal ? minVal : minRight; maxRight = maxRight < maxVal ? maxVal : maxRight; } } } } if (yAxisLeftUsed == true) { this.yAxisLeft.setRange(minLeft, maxLeft); } if (yAxisRightUsed == true) { this.yAxisRight.setRange(minRight, maxRight); } } changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled; changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled; if (yAxisRightUsed == true && yAxisLeftUsed == true) { this.yAxisLeft.drawIcons = true; this.yAxisRight.drawIcons = true; } else { this.yAxisLeft.drawIcons = false; this.yAxisRight.drawIcons = false; } this.yAxisRight.master = !yAxisLeftUsed; if (this.yAxisRight.master == false) { if (yAxisRightUsed == true) {this.yAxisLeft.lineOffset = this.yAxisRight.width;} else {this.yAxisLeft.lineOffset = 0;} changeCalled = this.yAxisLeft.redraw() || changeCalled; this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels; changeCalled = this.yAxisRight.redraw() || changeCalled; } else { changeCalled = this.yAxisRight.redraw() || changeCalled; } // clean the accumulated lists if (groupIds.indexOf("__barchartLeft") != -1) { groupIds.splice(groupIds.indexOf("__barchartLeft"),1); } if (groupIds.indexOf("__barchartRight") != -1) { groupIds.splice(groupIds.indexOf("__barchartRight"),1); } return changeCalled; }; /** * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function * * @param {boolean} axisUsed * @returns {boolean} * @private * @param axis */ LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { var changed = false; if (axisUsed == false) { if (axis.dom.frame.parentNode) { axis.hide(); changed = true; } } else { if (!axis.dom.frame.parentNode) { axis.show(); changed = true; } } return changed; }; /** * draw a bar graph * * @param groupIds * @param processedGroupData */ LineGraph.prototype._drawBarGraphs = function (groupIds, processedGroupData) { var combinedData = []; var intersections = {}; var coreDistance; var key, drawData; var group; var i,j; var barPoints = 0; // combine all barchart data for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; if (group.options.style == 'bar') { if (group.visible == true && (this.options.groups.visibility[groupIds[i]] === undefined || this.options.groups.visibility[groupIds[i]] == true)) { for (j = 0; j < processedGroupData[groupIds[i]].length; j++) { combinedData.push({ x: processedGroupData[groupIds[i]][j].x, y: processedGroupData[groupIds[i]][j].y, groupId: groupIds[i] }); barPoints += 1; } } } } if (barPoints == 0) {return;} // sort by time and by group combinedData.sort(function (a, b) { if (a.x == b.x) { return a.groupId - b.groupId; } else { return a.x - b.x; } }); // get intersections this._getDataIntersections(intersections, combinedData); // plot barchart for (i = 0; i < combinedData.length; i++) { group = this.groups[combinedData[i].groupId]; var minWidth = 0.1 * group.options.barChart.width; key = combinedData[i].x; var heightOffset = 0; if (intersections[key] === undefined) { if (i+1 < combinedData.length) {coreDistance = Math.abs(combinedData[i+1].x - key);} if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[i-1].x - key));} drawData = this._getSafeDrawData(coreDistance, group, minWidth); } else { var nextKey = i + (intersections[key].amount - intersections[key].resolved); var prevKey = i - (intersections[key].resolved + 1); if (nextKey < combinedData.length) {coreDistance = Math.abs(combinedData[nextKey].x - key);} if (prevKey > 0) {coreDistance = Math.min(coreDistance,Math.abs(combinedData[prevKey].x - key));} drawData = this._getSafeDrawData(coreDistance, group, minWidth); intersections[key].resolved += 1; if (group.options.barChart.handleOverlap == 'stack') { heightOffset = intersections[key].accumulated; intersections[key].accumulated += group.zeroPosition - combinedData[i].y; } else if (group.options.barChart.handleOverlap == 'sideBySide') { drawData.width = drawData.width / intersections[key].amount; drawData.offset += (intersections[key].resolved) * drawData.width - (0.5*drawData.width * (intersections[key].amount+1)); if (group.options.barChart.align == 'left') {drawData.offset -= 0.5*drawData.width;} else if (group.options.barChart.align == 'right') {drawData.offset += 0.5*drawData.width;} } } DOMutil.drawBar(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, drawData.width, group.zeroPosition - combinedData[i].y, group.className + ' bar', this.svgElements, this.svg); // draw points if (group.options.drawPoints.enabled == true) { DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y - heightOffset, group, this.svgElements, this.svg); } } }; /** * Fill the intersections object with counters of how many datapoints share the same x coordinates * @param intersections * @param combinedData * @private */ LineGraph.prototype._getDataIntersections = function (intersections, combinedData) { // get intersections var coreDistance; for (var i = 0; i < combinedData.length; i++) { if (i + 1 < combinedData.length) { coreDistance = Math.abs(combinedData[i + 1].x - combinedData[i].x); } if (i > 0) { coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].x - combinedData[i].x)); } if (coreDistance == 0) { if (intersections[combinedData[i].x] === undefined) { intersections[combinedData[i].x] = {amount: 0, resolved: 0, accumulated: 0}; } intersections[combinedData[i].x].amount += 1; } } }; /** * Get the width and offset for bargraphs based on the coredistance between datapoints * * @param coreDistance * @param group * @param minWidth * @returns {{width: Number, offset: Number}} * @private */ LineGraph.prototype._getSafeDrawData = function (coreDistance, group, minWidth) { var width, offset; if (coreDistance < group.options.barChart.width && coreDistance > 0) { width = coreDistance < minWidth ? minWidth : coreDistance; offset = 0; // recalculate offset with the new width; if (group.options.barChart.align == 'left') { offset -= 0.5 * coreDistance; } else if (group.options.barChart.align == 'right') { offset += 0.5 * coreDistance; } } else { // default settings width = group.options.barChart.width; offset = 0; if (group.options.barChart.align == 'left') { offset -= 0.5 * group.options.barChart.width; } else if (group.options.barChart.align == 'right') { offset += 0.5 * group.options.barChart.width; } } return {width: width, offset: offset}; }; /** * draw a line graph * * @param dataset * @param group */ LineGraph.prototype._drawLineGraph = function (dataset, group) { if (dataset != null) { if (dataset.length > 0) { var path, d; var svgHeight = Number(this.svg.style.height.replace("px","")); path = DOMutil.getSVGElement('path', this.svgElements, this.svg); path.setAttributeNS(null, "class", group.className); // construct path from dataset if (group.options.catmullRom.enabled == true) { d = this._catmullRom(dataset, group); } else { d = this._linear(dataset); } // append with points for fill and finalize the path if (group.options.shaded.enabled == true) { var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg); var dFill; if (group.options.shaded.orientation == 'top') { dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0; } else { dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight; } fillPath.setAttributeNS(null, "class", group.className + " fill"); fillPath.setAttributeNS(null, "d", dFill); } // copy properties to path for drawing. path.setAttributeNS(null, "d", "M" + d); // draw points if (group.options.drawPoints.enabled == true) { this._drawPoints(dataset, group, this.svgElements, this.svg); } } } }; /** * draw the data points * * @param {Array} dataset * @param {Object} JSONcontainer * @param {Object} svg | SVG DOM element * @param {GraphGroup} group * @param {Number} [offset] */ LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) { if (offset === undefined) {offset = 0;} for (var i = 0; i < dataset.length; i++) { DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg); } }; /** * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for * the yAxis. * * @param datapoints * @returns {Array} * @private */ LineGraph.prototype._convertXcoordinates = function (datapoints) { var extractedData = []; var xValue, yValue; var toScreen = this.body.util.toScreen; for (var i = 0; i < datapoints.length; i++) { xValue = toScreen(datapoints[i].x) + this.width; yValue = datapoints[i].y; extractedData.push({x: xValue, y: yValue}); } return extractedData; }; /** * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for * the yAxis. * * @param datapoints * @returns {Array} * @private */ LineGraph.prototype._convertYcoordinates = function (datapoints, group) { var extractedData = []; var xValue, yValue; var toScreen = this.body.util.toScreen; var axis = this.yAxisLeft; var svgHeight = Number(this.svg.style.height.replace("px","")); if (group.options.yAxisOrientation == 'right') { axis = this.yAxisRight; } for (var i = 0; i < datapoints.length; i++) { xValue = toScreen(datapoints[i].x) + this.width; yValue = Math.round(axis.convertValue(datapoints[i].y)); extractedData.push({x: xValue, y: yValue}); } group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); return extractedData; }; /** * This uses an uniform parametrization of the CatmullRom algorithm: * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al. * @param data * @returns {string} * @private */ LineGraph.prototype._catmullRomUniform = function(data) { // catmull rom var p0, p1, p2, p3, bp1, bp2; var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " "; var normalization = 1/6; var length = data.length; for (var i = 0; i < length - 1; i++) { p0 = (i == 0) ? data[0] : data[i-1]; p1 = data[i]; p2 = data[i+1]; p3 = (i + 2 < length) ? data[i+2] : p2; // Catmull-Rom to Cubic Bezier conversion matrix // 0 1 0 0 // -1/6 1 1/6 0 // 0 1/6 1 -1/6 // 0 0 1 0 // bp0 = { x: p1.x, y: p1.y }; bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)}; bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)}; // bp0 = { x: p2.x, y: p2.y }; d += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + p2.x + "," + p2.y + " "; } return d; }; /** * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. * By default, the centripetal parameterization is used because this gives the nicest results. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. * * One optimization can be used to reuse distances since this is a sliding window approach. * @param data * @returns {string} * @private */ LineGraph.prototype._catmullRom = function(data, group) { var alpha = group.options.catmullRom.alpha; if (alpha == 0 || alpha === undefined) { return this._catmullRomUniform(data); } else { var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M; var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " "; var length = data.length; for (var i = 0; i < length - 1; i++) { p0 = (i == 0) ? data[0] : data[i-1]; p1 = data[i]; p2 = data[i+1]; p3 = (i + 2 < length) ? data[i+2] : p2; d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2)); d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2)); d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2)); // Catmull-Rom to Cubic Bezier conversion matrix // // A = 2d1^2a + 3d1^a * d2^a + d3^2a // B = 2d3^2a + 3d3^a * d2^a + d2^2a // // [ 0 1 0 0 ] // [ -d2^2a/N A/N d1^2a/N 0 ] // [ 0 d3^2a/M B/M -d2^2a/M ] // [ 0 0 1 0 ] // [ 0 1 0 0 ] // [ -d2pow2a/N A/N d1pow2a/N 0 ] // [ 0 d3pow2a/M B/M -d2pow2a/M ] // [ 0 0 1 0 ] d3powA = Math.pow(d3, alpha); d3pow2A = Math.pow(d3,2*alpha); d2powA = Math.pow(d2, alpha); d2pow2A = Math.pow(d2,2*alpha); d1powA = Math.pow(d1, alpha); d1pow2A = Math.pow(d1,2*alpha); A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A; B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A; N = 3*d1powA * (d1powA + d2powA); if (N > 0) {N = 1 / N;} M = 3*d3powA * (d3powA + d2powA); if (M > 0) {M = 1 / M;} bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N), y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)}; bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M), y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)}; if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;} if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;} d += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + p2.x + "," + p2.y + " "; } return d; } }; /** * this generates the SVG path for a linear drawing between datapoints. * @param data * @returns {string} * @private */ LineGraph.prototype._linear = function(data) { // linear var d = ""; for (var i = 0; i < data.length; i++) { if (i == 0) { d += data[i].x + "," + data[i].y; } else { d += " " + data[i].x + "," + data[i].y; } } return d; }; module.exports = LineGraph; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Component = __webpack_require__(18); var TimeStep = __webpack_require__(17); var moment = __webpack_require__(41); /** * A horizontal time axis * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See TimeAxis.setOptions for the available * options. * @constructor TimeAxis * @extends Component */ function TimeAxis (body, options) { this.dom = { foreground: null, majorLines: [], majorTexts: [], minorLines: [], minorTexts: [], redundant: { majorLines: [], majorTexts: [], minorLines: [], minorTexts: [] } }; this.props = { range: { start: 0, end: 0, minimumStep: 0 }, lineTop: 0 }; this.defaultOptions = { orientation: 'bottom', // supported: 'top', 'bottom' // TODO: implement timeaxis orientations 'left' and 'right' showMinorLabels: true, showMajorLabels: true }; this.options = util.extend({}, this.defaultOptions); this.body = body; // create the HTML DOM this._create(); this.setOptions(options); } TimeAxis.prototype = new Component(); /** * Set options for the TimeAxis. * Parameters will be merged in current options. * @param {Object} options Available options: * {string} [orientation] * {boolean} [showMinorLabels] * {boolean} [showMajorLabels] */ TimeAxis.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['orientation', 'showMinorLabels', 'showMajorLabels'], this.options, options); // apply locale to moment.js // TODO: not so nice, this is applied globally to moment.js if ('locale' in options) { if (typeof moment.locale === 'function') { // moment.js 2.8.1+ moment.locale(options.locale); } else { moment.lang(options.locale); } } } }; /** * Create the HTML DOM for the TimeAxis */ TimeAxis.prototype._create = function() { this.dom.foreground = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.foreground.className = 'timeaxis foreground'; this.dom.background.className = 'timeaxis background'; }; /** * Destroy the TimeAxis */ TimeAxis.prototype.destroy = function() { // remove from DOM if (this.dom.foreground.parentNode) { this.dom.foreground.parentNode.removeChild(this.dom.foreground); } if (this.dom.background.parentNode) { this.dom.background.parentNode.removeChild(this.dom.background); } this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ TimeAxis.prototype.redraw = function () { var options = this.options, props = this.props, foreground = this.dom.foreground, background = this.dom.background; // determine the correct parent DOM element (depending on option orientation) var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom; var parentChanged = (foreground.parentNode !== parent); // calculate character width and height this._calculateCharSize(); // TODO: recalculate sizes only needed when parent is resized or options is changed var orientation = this.options.orientation, showMinorLabels = this.options.showMinorLabels, showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.height = props.minorLabelHeight + props.majorLabelHeight; props.width = foreground.offsetWidth; props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height); props.minorLineWidth = 1; // TODO: really calculate width props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight; props.majorLineWidth = 1; // TODO: really calculate width // take foreground and background offline while updating (is almost twice as fast) var foregroundNextSibling = foreground.nextSibling; var backgroundNextSibling = background.nextSibling; foreground.parentNode && foreground.parentNode.removeChild(foreground); background.parentNode && background.parentNode.removeChild(background); foreground.style.height = this.props.height + 'px'; this._repaintLabels(); // put DOM online again (at the same place) if (foregroundNextSibling) { parent.insertBefore(foreground, foregroundNextSibling); } else { parent.appendChild(foreground) } if (backgroundNextSibling) { this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling); } else { this.body.dom.backgroundVertical.appendChild(background) } return this._isResized() || parentChanged; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ TimeAxis.prototype._repaintLabels = function () { var orientation = this.options.orientation; // calculate range and step (step such that we have space for 7 characters per label) var start = util.convert(this.body.range.start, 'Number'), end = util.convert(this.body.range.end, 'Number'), minimumStep = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf() -this.body.util.toTime(0).valueOf(); var step = new TimeStep(new Date(start), new Date(end), minimumStep); this.step = step; // Move all DOM elements to a "redundant" list, where they // can be picked for re-use, and clear the lists with lines and texts. // At the end of the function _repaintLabels, left over elements will be cleaned up var dom = this.dom; dom.redundant.majorLines = dom.majorLines; dom.redundant.majorTexts = dom.majorTexts; dom.redundant.minorLines = dom.minorLines; dom.redundant.minorTexts = dom.minorTexts; dom.majorLines = []; dom.majorTexts = []; dom.minorLines = []; dom.minorTexts = []; step.first(); var xFirstMajorLabel = undefined; var max = 0; while (step.hasNext() && max < 1000) { max++; var cur = step.getCurrent(), x = this.body.util.toScreen(cur), isMajor = step.isMajor(); // TODO: lines must have a width, such that we can create css backgrounds if (this.options.showMinorLabels) { this._repaintMinorText(x, step.getLabelMinor(), orientation); } if (isMajor && this.options.showMajorLabels) { if (x > 0) { if (xFirstMajorLabel == undefined) { xFirstMajorLabel = x; } this._repaintMajorText(x, step.getLabelMajor(), orientation); } this._repaintMajorLine(x, orientation); } else { this._repaintMinorLine(x, orientation); } step.next(); } // create a major label on the left when needed if (this.options.showMajorLabels) { var leftTime = this.body.util.toTime(0), leftText = step.getLabelMajor(leftTime), widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { this._repaintMajorText(0, leftText, orientation); } } // Cleanup leftover DOM elements from the redundant list util.forEach(this.dom.redundant, function (arr) { while (arr.length) { var elem = arr.pop(); if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } }); }; /** * Create a minor label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.minorTexts.shift(); if (!label) { // create new label var content = document.createTextNode(''); label = document.createElement('div'); label.appendChild(content); label.className = 'text minor'; this.dom.foreground.appendChild(label); } this.dom.minorTexts.push(label); label.childNodes[0].nodeValue = text; label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0'; label.style.left = x + 'px'; //label.title = title; // TODO: this is a heavy operation }; /** * Create a Major label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.majorTexts.shift(); if (!label) { // create label var content = document.createTextNode(text); label = document.createElement('div'); label.className = 'text major'; label.appendChild(content); this.dom.foreground.appendChild(label); } this.dom.majorTexts.push(label); label.childNodes[0].nodeValue = text; //label.title = title; // TODO: this is a heavy operation label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px'); label.style.left = x + 'px'; }; /** * Create a minor line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.minorLines.shift(); if (!line) { // create vertical line line = document.createElement('div'); line.className = 'grid vertical minor'; this.dom.background.appendChild(line); } this.dom.minorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = props.majorLabelHeight + 'px'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.height = props.minorLineHeight + 'px'; line.style.left = (x - props.minorLineWidth / 2) + 'px'; }; /** * Create a Major line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.majorLines.shift(); if (!line) { // create vertical line line = document.createElement('DIV'); line.className = 'grid vertical major'; this.dom.background.appendChild(line); } this.dom.majorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = '0'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.left = (x - props.majorLineWidth / 2) + 'px'; line.style.height = props.majorLineHeight + 'px'; }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ TimeAxis.prototype._calculateCharSize = function () { // Note: We calculate char size with every redraw. Size may change, for // example when any of the timelines parents had display:none for example. // determine the char width and height on the minor axis if (!this.dom.measureCharMinor) { this.dom.measureCharMinor = document.createElement('DIV'); this.dom.measureCharMinor.className = 'text minor measure'; this.dom.measureCharMinor.style.position = 'absolute'; this.dom.measureCharMinor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMinor); } this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight; this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth; // determine the char width and height on the major axis if (!this.dom.measureCharMajor) { this.dom.measureCharMajor = document.createElement('DIV'); this.dom.measureCharMajor.className = 'text minor measure'; this.dom.measureCharMajor.style.position = 'absolute'; this.dom.measureCharMajor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMajor); } this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight; this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeAxis.prototype.snap = function(date) { return this.step.snap(date); }; module.exports = TimeAxis; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(42); /** * @constructor Item * @param {Object} data Object containing (optional) parameters type, * start, end, content, group, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} options Configuration options * // TODO: describe available options */ function Item (data, conversion, options) { this.id = null; this.parent = null; this.data = data; this.dom = null; this.conversion = conversion || {}; this.options = options || {}; this.selected = false; this.displayed = false; this.dirty = true; this.top = null; this.left = null; this.width = null; this.height = null; } /** * Select current item */ Item.prototype.select = function() { this.selected = true; this.dirty = true; if (this.displayed) this.redraw(); }; /** * Unselect current item */ Item.prototype.unselect = function() { this.selected = false; this.dirty = true; if (this.displayed) this.redraw(); }; /** * Set data for the item. Existing data will be updated. The id should not * be changed. When the item is displayed, it will be redrawn immediately. * @param {Object} data */ Item.prototype.setData = function(data) { this.data = data; this.dirty = true; if (this.displayed) this.redraw(); }; /** * Set a parent for the item * @param {ItemSet | Group} parent */ Item.prototype.setParent = function(parent) { if (this.displayed) { this.hide(); this.parent = parent; if (this.parent) { this.show(); } } else { this.parent = parent; } }; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ Item.prototype.isVisible = function(range) { // Should be implemented by Item implementations return false; }; /** * Show the Item in the DOM (when not already visible) * @return {Boolean} changed */ Item.prototype.show = function() { return false; }; /** * Hide the Item from the DOM (when visible) * @return {Boolean} changed */ Item.prototype.hide = function() { return false; }; /** * Repaint the item */ Item.prototype.redraw = function() { // should be implemented by the item }; /** * Reposition the Item horizontally */ Item.prototype.repositionX = function() { // should be implemented by the item }; /** * Reposition the Item vertically */ Item.prototype.repositionY = function() { // should be implemented by the item }; /** * Repaint a delete button on the top right of the item when the item is selected * @param {HTMLElement} anchor * @protected */ Item.prototype._repaintDeleteButton = function (anchor) { if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { // create and show button var me = this; var deleteButton = document.createElement('div'); deleteButton.className = 'delete'; deleteButton.title = 'Delete this item'; Hammer(deleteButton, { preventDefault: true }).on('tap', function (event) { me.parent.removeFromDataSet(me); event.stopPropagation(); }); anchor.appendChild(deleteButton); this.dom.deleteButton = deleteButton; } else if (!this.selected && this.dom.deleteButton) { // remove button if (this.dom.deleteButton.parentNode) { this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton); } this.dom.deleteButton = null; } }; /** * Set HTML contents for the item * @param {Element} element HTML element to fill with the contents * @private */ Item.prototype._updateContents = function (element) { var content; if (this.options.template) { var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset content = this.options.template(itemData); } else { content = this.data.content; } if (content instanceof Element) { element.innerHTML = ''; element.appendChild(content); } else if (content != undefined) { element.innerHTML = content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } }; /** * Set HTML contents for the item * @param {Element} element HTML element to fill with the contents * @private */ Item.prototype._updateTitle = function (element) { if (this.data.title != null) { element.title = this.data.title || ''; } else { element.removeAttribute('title'); } }; /** * Process dataAttributes timeline option and set as data- attributes on dom.content * @param {Element} element HTML element to which the attributes will be attached * @private */ Item.prototype._updateDataAttributes = function(element) { if (this.options.dataAttributes && this.options.dataAttributes.length > 0) { for (var i = 0; i < this.options.dataAttributes.length; i++) { var name = this.options.dataAttributes[i]; var value = this.data[name]; if (value != null) { element.setAttribute('data-' + name, value); } else { element.removeAttribute('data-' + name); } } } }; module.exports = Item; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(42); var Item = __webpack_require__(28); var RangeItem = __webpack_require__(32); /** * @constructor BackgroundItem * @extends Item * @param {Object} data Object containing parameters start, end * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe options */ // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation function BackgroundItem (data, conversion, options) { this.props = { content: { width: 0 } }; this.overflow = false; // if contents can overflow (css styling), this flag is set to true // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data.id); } if (data.end == undefined) { throw new Error('Property "end" missing in item ' + data.id); } } Item.call(this, data, conversion, options); } BackgroundItem.prototype = new Item (null, null, null); BackgroundItem.prototype.baseClassName = 'item background'; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ BackgroundItem.prototype.isVisible = function(range) { // determine visibility return (this.data.start < range.end) && (this.data.end > range.start); }; /** * Repaint the item */ BackgroundItem.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.box = document.createElement('div'); // className is updated in redraw() // contents box dom.content = document.createElement('div'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // attach this item as attribute dom.box['timeline-item'] = this; this.dirty = true; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var background = this.parent.dom.background; if (!background) { throw new Error('Cannot redraw time axis: parent has no background container element'); } background.appendChild(dom.box); } this.displayed = true; // Update DOM when item is marked dirty. An item is marked dirty when: // - the item is not yet rendered // - the item's data is changed // - the item is selected/deselected if (this.dirty) { this._updateContents(this.dom.content); this._updateTitle(this.dom.content); this._updateDataAttributes(this.dom.content); // update class var className = (this.data.className ? (' ' + this.data.className) : '') + (this.selected ? ' selected' : ''); dom.box.className = this.baseClassName + className; // determine from css whether this box has overflow this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; // recalculate size this.props.content.width = this.dom.content.offsetWidth; this.height = 0; // set height zero, so this item will be ignored when stacking items this.dirty = false; } }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ BackgroundItem.prototype.show = RangeItem.prototype.show; /** * Hide the item from the DOM (when visible) * @return {Boolean} changed */ BackgroundItem.prototype.hide = RangeItem.prototype.hide; /** * Reposition the item horizontally * @Override */ BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX; /** * Reposition the item vertically * @Override */ BackgroundItem.prototype.repositionY = function() { var onTop = this.options.orientation === 'top'; this.dom.content.style.top = onTop ? '' : '0'; this.dom.content.style.bottom = onTop ? '0' : ''; }; module.exports = BackgroundItem; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var Item = __webpack_require__(28); /** * @constructor BoxItem * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function BoxItem (data, conversion, options) { this.props = { dot: { width: 0, height: 0 }, line: { width: 0, height: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } BoxItem.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ BoxItem.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ BoxItem.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // create main box dom.box = document.createElement('DIV'); // contents box (inside the background box). used for making margins dom.content = document.createElement('DIV'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // line to axis dom.line = document.createElement('DIV'); dom.line.className = 'line'; // dot on axis dom.dot = document.createElement('DIV'); dom.dot.className = 'dot'; // attach this item as attribute dom.box['timeline-item'] = this; this.dirty = true; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) throw new Error('Cannot redraw time axis: parent has no foreground container element'); foreground.appendChild(dom.box); } if (!dom.line.parentNode) { var background = this.parent.dom.background; if (!background) throw new Error('Cannot redraw time axis: parent has no background container element'); background.appendChild(dom.line); } if (!dom.dot.parentNode) { var axis = this.parent.dom.axis; if (!background) throw new Error('Cannot redraw time axis: parent has no axis container element'); axis.appendChild(dom.dot); } this.displayed = true; // Update DOM when item is marked dirty. An item is marked dirty when: // - the item is not yet rendered // - the item's data is changed // - the item is selected/deselected if (this.dirty) { this._updateContents(this.dom.content); this._updateTitle(this.dom.box); this._updateDataAttributes(this.dom.box); // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); dom.box.className = 'item box' + className; dom.line.className = 'item line' + className; dom.dot.className = 'item dot' + className; // recalculate size this.props.dot.height = dom.dot.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.line.width = dom.line.offsetWidth; this.width = dom.box.offsetWidth; this.height = dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); }; /** * Show the item in the DOM (when not already displayed). The items DOM will * be created when needed. */ BoxItem.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ BoxItem.prototype.hide = function() { if (this.displayed) { var dom = this.dom; if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ BoxItem.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start); var align = this.options.align; var left; var box = this.dom.box; var line = this.dom.line; var dot = this.dom.dot; // calculate left position of the box if (align == 'right') { this.left = start - this.width; } else if (align == 'left') { this.left = start; } else { // default or 'center' this.left = start - this.width / 2; } // reposition box box.style.left = this.left + 'px'; // reposition line line.style.left = (start - this.props.line.width / 2) + 'px'; // reposition dot dot.style.left = (start - this.props.dot.width / 2) + 'px'; }; /** * Reposition the item vertically * @Override */ BoxItem.prototype.repositionY = function() { var orientation = this.options.orientation; var box = this.dom.box; var line = this.dom.line; var dot = this.dom.dot; if (orientation == 'top') { box.style.top = (this.top || 0) + 'px'; line.style.top = '0'; line.style.height = (this.parent.top + this.top + 1) + 'px'; line.style.bottom = ''; } else { // orientation 'bottom' var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; line.style.top = (itemSetHeight - lineHeight) + 'px'; line.style.bottom = '0'; } dot.style.top = (-this.props.dot.height / 2) + 'px'; }; module.exports = BoxItem; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var Item = __webpack_require__(28); /** * @constructor PointItem * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function PointItem (data, conversion, options) { this.props = { dot: { top: 0, width: 0, height: 0 }, content: { height: 0, marginLeft: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } PointItem.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ PointItem.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ PointItem.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.point = document.createElement('div'); // className is updated in redraw() // contents box, right from the dot dom.content = document.createElement('div'); dom.content.className = 'content'; dom.point.appendChild(dom.content); // dot at start dom.dot = document.createElement('div'); dom.point.appendChild(dom.dot); // attach this item as attribute dom.point['timeline-item'] = this; this.dirty = true; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.point.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.point); } this.displayed = true; // Update DOM when item is marked dirty. An item is marked dirty when: // - the item is not yet rendered // - the item's data is changed // - the item is selected/deselected if (this.dirty) { this._updateContents(this.dom.content); this._updateTitle(this.dom.point); this._updateDataAttributes(this.dom.point); // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); dom.point.className = 'item point' + className; dom.dot.className = 'item dot' + className; // recalculate size this.width = dom.point.offsetWidth; this.height = dom.point.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.dot.height = dom.dot.offsetHeight; this.props.content.height = dom.content.offsetHeight; // resize contents dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; //dom.content.style.marginRight = ... + 'px'; // TODO: margin right dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px'; dom.dot.style.left = (this.props.dot.width / 2) + 'px'; this.dirty = false; } this._repaintDeleteButton(dom.point); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ PointItem.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ PointItem.prototype.hide = function() { if (this.displayed) { if (this.dom.point.parentNode) { this.dom.point.parentNode.removeChild(this.dom.point); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ PointItem.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start); this.left = start - this.props.dot.width; // reposition point this.dom.point.style.left = this.left + 'px'; }; /** * Reposition the item vertically * @Override */ PointItem.prototype.repositionY = function() { var orientation = this.options.orientation, point = this.dom.point; if (orientation == 'top') { point.style.top = this.top + 'px'; } else { point.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; module.exports = PointItem; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(42); var Item = __webpack_require__(28); /** * @constructor RangeItem * @extends Item * @param {Object} data Object containing parameters start, end * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe options */ function RangeItem (data, conversion, options) { this.props = { content: { width: 0 } }; this.overflow = false; // if contents can overflow (css styling), this flag is set to true // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data.id); } if (data.end == undefined) { throw new Error('Property "end" missing in item ' + data.id); } } Item.call(this, data, conversion, options); } RangeItem.prototype = new Item (null, null, null); RangeItem.prototype.baseClassName = 'item range'; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ RangeItem.prototype.isVisible = function(range) { // determine visibility return (this.data.start < range.end) && (this.data.end > range.start); }; /** * Repaint the item */ RangeItem.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.box = document.createElement('div'); // className is updated in redraw() // contents box dom.content = document.createElement('div'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // attach this item as attribute dom.box['timeline-item'] = this; this.dirty = true; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.box); } this.displayed = true; // Update DOM when item is marked dirty. An item is marked dirty when: // - the item is not yet rendered // - the item's data is changed // - the item is selected/deselected if (this.dirty) { this._updateContents(this.dom.content); this._updateTitle(this.dom.box); this._updateDataAttributes(this.dom.box); // update class var className = (this.data.className ? (' ' + this.data.className) : '') + (this.selected ? ' selected' : ''); dom.box.className = this.baseClassName + className; // determine from css whether this box has overflow this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; // recalculate size this.props.content.width = this.dom.content.offsetWidth; this.height = this.dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); this._repaintDragLeft(); this._repaintDragRight(); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ RangeItem.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) * @return {Boolean} changed */ RangeItem.prototype.hide = function() { if (this.displayed) { var box = this.dom.box; if (box.parentNode) { box.parentNode.removeChild(box); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ RangeItem.prototype.repositionX = function() { var parentWidth = this.parent.width; var start = this.conversion.toScreen(this.data.start); var end = this.conversion.toScreen(this.data.end); var contentLeft; var contentWidth; // limit the width of the this, as browsers cannot draw very wide divs if (start < -parentWidth) { start = -parentWidth; } if (end > 2 * parentWidth) { end = 2 * parentWidth; } var boxWidth = Math.max(end - start, 1); if (this.overflow) { this.left = start; this.width = boxWidth + this.props.content.width; contentWidth = this.props.content.width; // Note: The calculation of width is an optimistic calculation, giving // a width which will not change when moving the Timeline // So no re-stacking needed, which is nicer for the eye; } else { this.left = start; this.width = boxWidth; contentWidth = Math.min(end - start, this.props.content.width); } this.dom.box.style.left = this.left + 'px'; this.dom.box.style.width = boxWidth + 'px'; switch (this.options.align) { case 'left': this.dom.content.style.left = '0'; break; case 'right': this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding), 0) + 'px'; break; case 'center': this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding) / 2, 0) + 'px'; break; default: // 'auto' if (this.overflow) { // when range exceeds left of the window, position the contents at the left of the visible area contentLeft = Math.max(-start, 0); } else { // when range exceeds left of the window, position the contents at the left of the visible area if (start < 0) { contentLeft = Math.min(-start, (end - start - this.props.content.width - 2 * this.options.padding)); // TODO: remove the need for options.padding. it's terrible. } else { contentLeft = 0; } } this.dom.content.style.left = contentLeft + 'px'; } }; /** * Reposition the item vertically * @Override */ RangeItem.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box; if (orientation == 'top') { box.style.top = this.top + 'px'; } else { box.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; /** * Repaint a drag area on the left side of the range when the range is selected * @protected */ RangeItem.prototype._repaintDragLeft = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) { // create and show drag area var dragLeft = document.createElement('div'); dragLeft.className = 'drag-left'; dragLeft.dragLeftItem = this; // TODO: this should be redundant? Hammer(dragLeft, { preventDefault: true }).on('drag', function () { //console.log('drag left') }); this.dom.box.appendChild(dragLeft); this.dom.dragLeft = dragLeft; } else if (!this.selected && this.dom.dragLeft) { // delete drag area if (this.dom.dragLeft.parentNode) { this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); } this.dom.dragLeft = null; } }; /** * Repaint a drag area on the right side of the range when the range is selected * @protected */ RangeItem.prototype._repaintDragRight = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) { // create and show drag area var dragRight = document.createElement('div'); dragRight.className = 'drag-right'; dragRight.dragRightItem = this; // TODO: this should be redundant? Hammer(dragRight, { preventDefault: true }).on('drag', function () { //console.log('drag right') }); this.dom.box.appendChild(dragRight); this.dom.dragRight = dragRight; } else if (!this.selected && this.dom.dragRight) { // delete drag area if (this.dom.dragRight.parentNode) { this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); } this.dom.dragRight = null; } }; module.exports = RangeItem; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(50); var Hammer = __webpack_require__(42); var mousetrap = __webpack_require__(51); var util = __webpack_require__(1); var hammerUtil = __webpack_require__(43); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var dotparser = __webpack_require__(39); var gephiParser = __webpack_require__(40); var Groups = __webpack_require__(35); var Images = __webpack_require__(36); var Node = __webpack_require__(37); var Edge = __webpack_require__(34); var Popup = __webpack_require__(38); var MixinLoader = __webpack_require__(48); var Activator = __webpack_require__(49); var locales = __webpack_require__(46); // Load custom shapes into CanvasRenderingContext2D __webpack_require__(47); /** * @constructor Network * Create a network visualization, displaying nodes and edges. * * @param {Element} container The DOM element in which the Network will * be created. Normally a div element. * @param {Object} data An object containing parameters * {Array} nodes * {Array} edges * @param {Object} options Options */ function Network (container, data, options) { if (!(this instanceof Network)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._initializeMixinLoaders(); // create variables and set default values this.containerElement = container; // render and calculation settings this.renderRefreshRate = 60; // hz (fps) this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation this.initializing = true; this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null}; // set constant values this.defaultOptions = { nodes: { mass: 1, radiusMin: 10, radiusMax: 30, radius: 10, shape: 'ellipse', image: undefined, widthMin: 16, // px widthMax: 64, // px fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', fontFill: undefined, level: -1, color: { border: '#2B7CE9', background: '#97C2FC', highlight: { border: '#2B7CE9', background: '#D2E5FF' }, hover: { border: '#2B7CE9', background: '#D2E5FF' } }, borderColor: '#2B7CE9', backgroundColor: '#97C2FC', highlightColor: '#D2E5FF', group: undefined, borderWidth: 1, borderWidthSelected: undefined }, edges: { widthMin: 1, // widthMax: 15,// width: 1, widthSelectionMultiplier: 2, hoverWidth: 1.5, style: 'line', color: { color:'#848484', highlight:'#848484', hover: '#848484' }, fontColor: '#343434', fontSize: 14, // px fontFace: 'arial', fontFill: 'white', arrowScaleFactor: 1, dash: { length: 10, gap: 5, altLength: undefined }, inheritColor: "from" // to, from, false, true (== from) }, configurePhysics:false, physics: { barnesHut: { enabled: true, theta: 1 / 0.6, // inverted to save time during calculation gravitationalConstant: -2000, centralGravity: 0.3, springLength: 95, springConstant: 0.04, damping: 0.09 }, repulsion: { centralGravity: 0.0, springLength: 200, springConstant: 0.05, nodeDistance: 100, damping: 0.09 }, hierarchicalRepulsion: { enabled: false, centralGravity: 0.0, springLength: 100, springConstant: 0.01, nodeDistance: 150, damping: 0.09 }, damping: null, centralGravity: null, springLength: null, springConstant: null }, clustering: { // Per Node in Cluster = PNiC enabled: false, // (Boolean) | global on/off switch for clustering. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains). clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px). maxFontSize: 1000, forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster). distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster). edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster. height: 1, // (px PNiC) | growth of the height per node in cluster. radius: 1}, // (px PNiC) | growth of the radius per node in cluster. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open. clusterLevelDifference: 2 }, navigation: { enabled: false }, keyboard: { enabled: false, speed: {x: 10, y: 10, zoom: 0.02} }, dataManipulation: { enabled: false, initiallyVisible: false }, hierarchicalLayout: { enabled:false, levelSeparation: 150, nodeSpacing: 100, direction: "UD", // UD, DU, LR, RL layout: "hubsize" // hubsize, directed }, freezeForStabilization: false, smoothCurves: { enabled: true, dynamic: true, type: "continuous", roundness: 0.5 }, dynamicSmoothCurves: true, maxVelocity: 30, minVelocity: 0.1, // px/s stabilize: true, // stabilize before displaying the network stabilizationIterations: 1000, // maximum number of iteration to stabilize locale: 'en', locales: locales, tooltip: { delay: 300, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } }, dragNetwork: true, dragNodes: true, zoomable: true, hover: false, hideEdgesOnDrag: false, hideNodesOnDrag: false, width : '100%', height : '100%', selectable: true }; this.constants = util.extend({}, this.defaultOptions); this.hoverObj = {nodes:{},edges:{}}; this.controlNodesActive = false; this.navigationHammers = {existing:[], new: []}; // animation properties this.animationSpeed = 1/this.renderRefreshRate; this.animationEasingFunction = "easeInOutQuint"; this.easingTime = 0; this.sourceScale = 0; this.targetScale = 0; this.sourceTranslation = 0; this.targetTranslation = 0; this.lockedOnNodeId = null; this.lockedOnNodeOffset = null; // Node variables var network = this; this.groups = new Groups(); // object with groups this.images = new Images(); // object with images this.images.setOnloadCallback(function () { network._redraw(); }); // keyboard navigation variables this.xIncrement = 0; this.yIncrement = 0; this.zoomIncrement = 0; // loading all the mixins: // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // create a frame and canvas this._create(); // load the sector system. (mandatory, fully integrated with Network) this._loadSectorSystem(); // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it) this._loadClusterSystem(); // load the selection system. (mandatory, required by Network) this._loadSelectionSystem(); // load the selection system. (mandatory, required by Network) this._loadHierarchySystem(); // apply options this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2); this._setScale(1); this.setOptions(options); // other vars this.freezeSimulation = false;// freeze the simulation this.cachedFunctions = {}; this.stabilized = false; this.stabilizationIterations = null; // containers for nodes and edges this.calculationNodes = {}; this.calculationNodeIndices = []; this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation this.nodes = {}; // object with Node objects this.edges = {}; // object with Edge objects // position and scale variables and objects this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action this.scale = 1; // defining the global scale variable in the constructor this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out // datasets or dataviews this.nodesData = null; // A DataSet or DataView this.edgesData = null; // A DataSet or DataView // create event listeners used to subscribe on the DataSets of the nodes and edges this.nodesListeners = { 'add': function (event, params) { network._addNodes(params.items); network.start(); }, 'update': function (event, params) { network._updateNodes(params.items); network.start(); }, 'remove': function (event, params) { network._removeNodes(params.items); network.start(); } }; this.edgesListeners = { 'add': function (event, params) { network._addEdges(params.items); network.start(); }, 'update': function (event, params) { network._updateEdges(params.items); network.start(); }, 'remove': function (event, params) { network._removeEdges(params.items); network.start(); } }; // properties for the animation this.moving = true; this.timer = undefined; // Scheduling function. Is definded in this.start(); // load data (the disable start variable will be the same as the enabled clustering) this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled); // hierarchical layout this.initializing = false; if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); } else { // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here. if (this.constants.stabilize == false) { this.zoomExtent(undefined, true,this.constants.clustering.enabled); } } // if clustering is disabled, the simulation will have started in the setData function if (this.constants.clustering.enabled) { this.startWithClustering(); } } // Extend Network with an Emitter mixin Emitter(Network.prototype); /** * Get the script path where the vis.js library is located * * @returns {string | null} path Path or null when not found. Path does not * end with a slash. * @private */ Network.prototype._getScriptPath = function() { var scripts = document.getElementsByTagName( 'script' ); // find script named vis.js or vis.min.js for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; var match = src && /\/?vis(.min)?\.js$/.exec(src); if (match) { // return path without the script name return src.substring(0, src.length - match[0].length); } } return null; }; /** * Find the center position of the network * @private */ Network.prototype._getRange = function() { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (minX > (node.x)) {minX = node.x;} if (maxX < (node.x)) {maxX = node.x;} if (minY > (node.y)) {minY = node.y;} if (maxY < (node.y)) {maxY = node.y;} } } if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) { minY = 0, maxY = 0, minX = 0, maxX = 0; } return {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; }; /** * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; * @returns {{x: number, y: number}} * @private */ Network.prototype._findCenter = function(range) { return {x: (0.5 * (range.maxX + range.minX)), y: (0.5 * (range.maxY + range.minY))}; }; /** * This function zooms out to fit all data on screen based on amount of nodes * * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; * @param {Boolean} [disableStart] | If true, start is not called. */ Network.prototype.zoomExtent = function(animationOptions, initialZoom, disableStart) { if (initialZoom === undefined) { initialZoom = false; } if (disableStart === undefined) { disableStart = false; } if (animationOptions === undefined) { animationOptions = false; } var range = this._getRange(); var zoomLevel; if (initialZoom == true) { var numberOfNodes = this.nodeIndices.length; if (this.constants.smoothCurves == true) { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } else { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } // correct for larger canvasses. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600); zoomLevel *= factor; } else { var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1; var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1; var xZoomLevel = this.frame.canvas.clientWidth / xDistance; var yZoomLevel = this.frame.canvas.clientHeight / yDistance; zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel; } if (zoomLevel > 1.0) { zoomLevel = 1.0; } var center = this._findCenter(range); if (disableStart == false) { var options = {position: center, scale: zoomLevel, animation: animationOptions}; this.moveTo(options); this.moving = true; this.start(); } else { center.x *= zoomLevel; center.y *= zoomLevel; center.x -= 0.5 * this.frame.canvas.clientWidth; center.y -= 0.5 * this.frame.canvas.clientHeight; this._setScale(zoomLevel); this._setTranslation(-center.x,-center.y); } }; /** * Update the this.nodeIndices with the most recent node index list * @private */ Network.prototype._updateNodeIndexList = function() { this._clearNodeIndexList(); for (var idx in this.nodes) { if (this.nodes.hasOwnProperty(idx)) { this.nodeIndices.push(idx); } } }; /** * Set nodes and edges, and optionally options as well. * * @param {Object} data Object containing parameters: * {Array | DataSet | DataView} [nodes] Array with nodes * {Array | DataSet | DataView} [edges] Array with edges * {String} [dot] String containing data in DOT format * {String} [gephi] String containing data in gephi JSON format * {Options} [options] Object with options * @param {Boolean} [disableStart] | optional: disable the calling of the start function. */ Network.prototype.setData = function(data, disableStart) { if (disableStart === undefined) { disableStart = false; } // we set initializing to true to ensure that the hierarchical layout is not performed until both nodes and edges are added. this.initializing = true; if (data && data.dot && (data.nodes || data.edges)) { throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); } // set options this.setOptions(data && data.options); // set all data if (data && data.dot) { // parse DOT file if(data && data.dot) { var dotData = dotparser.DOTToGraph(data.dot); this.setData(dotData); return; } } else if (data && data.gephi) { // parse DOT file if(data && data.gephi) { var gephiData = gephiParser.parseGephi(data.gephi); this.setData(gephiData); return; } } else { this._setNodes(data && data.nodes); this._setEdges(data && data.edges); } this._putDataInSector(); if (disableStart == false) { if (this.constants.hierarchicalLayout.enabled == true) { this._resetLevels(); this._setupHierarchicalLayout(); } else { // find a stable position or start animating to a stable position if (this.constants.stabilize) { this._stabilize(); } } this.start(); } this.initializing = false; }; /** * Set options * @param {Object} options */ Network.prototype.setOptions = function (options) { if (options) { var prop; var fields = ['nodes','edges','smoothCurves','hierarchicalLayout','clustering','navigation','keyboard','dataManipulation', 'onAdd','onEdit','onEditEdge','onConnect','onDelete','clickToUse' ]; util.selectiveNotDeepExtend(fields,this.constants, options); util.selectiveNotDeepExtend(['color'],this.constants.nodes, options.nodes); util.selectiveNotDeepExtend(['color','length'],this.constants.edges, options.edges); if (options.physics) { util.mergeOptions(this.constants.physics, options.physics,'barnesHut'); util.mergeOptions(this.constants.physics, options.physics,'repulsion'); if (options.physics.hierarchicalRepulsion) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; for (prop in options.physics.hierarchicalRepulsion) { if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) { this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop]; } } } } if (options.onAdd) {this.triggerFunctions.add = options.onAdd;} if (options.onEdit) {this.triggerFunctions.edit = options.onEdit;} if (options.onEditEdge) {this.triggerFunctions.editEdge = options.onEditEdge;} if (options.onConnect) {this.triggerFunctions.connect = options.onConnect;} if (options.onDelete) {this.triggerFunctions.del = options.onDelete;} util.mergeOptions(this.constants, options,'smoothCurves'); util.mergeOptions(this.constants, options,'hierarchicalLayout'); util.mergeOptions(this.constants, options,'clustering'); util.mergeOptions(this.constants, options,'navigation'); util.mergeOptions(this.constants, options,'keyboard'); util.mergeOptions(this.constants, options,'dataManipulation'); if (options.dataManipulation) { this.editMode = this.constants.dataManipulation.initiallyVisible; } // TODO: work out these options and document them if (options.edges) { if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) { this.constants.edges.color = {}; this.constants.edges.color.color = options.edges.color; this.constants.edges.color.highlight = options.edges.color; this.constants.edges.color.hover = options.edges.color; } else { if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;} if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;} if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;} } } if (!options.edges.fontColor) { if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;} else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;} } } } if (options.nodes) { if (options.nodes.color) { var newColorObj = util.parseColor(options.nodes.color); this.constants.nodes.color.background = newColorObj.background; this.constants.nodes.color.border = newColorObj.border; this.constants.nodes.color.highlight.background = newColorObj.highlight.background; this.constants.nodes.color.highlight.border = newColorObj.highlight.border; this.constants.nodes.color.hover.background = newColorObj.hover.background; this.constants.nodes.color.hover.border = newColorObj.hover.border; } } if (options.groups) { for (var groupname in options.groups) { if (options.groups.hasOwnProperty(groupname)) { var group = options.groups[groupname]; this.groups.add(groupname, group); } } } if (options.tooltip) { for (prop in options.tooltip) { if (options.tooltip.hasOwnProperty(prop)) { this.constants.tooltip[prop] = options.tooltip[prop]; } } if (options.tooltip.color) { this.constants.tooltip.color = util.parseColor(options.tooltip.color); } } if ('clickToUse' in options) { if (options.clickToUse) { this.activator = new Activator(this.frame); this.activator.on('change', this._createKeyBinds.bind(this)); } else { if (this.activator) { this.activator.destroy(); delete this.activator; } } } if (options.labels) { throw new Error('Option "labels" is deprecated. Use options "locale" and "locales" instead.'); } } // (Re)loading the mixins that can be enabled or disabled in the options. // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // load the navigation system. this._loadNavigationControls(); // load the data manipulation system this._loadManipulationSystem(); // configure the smooth curves this._configureSmoothCurves(); // bind keys. If disabled, this will not do anything; this._createKeyBinds(); this.setSize(this.constants.width, this.constants.height); this.moving = true; this.start(); }; /** * Create the main frame for the Network. * This function is executed once when a Network object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. * @private */ Network.prototype._create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.className = 'vis network-frame'; this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the network canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); if (!this.frame.canvas.getContext) { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } var me = this; this.drag = {}; this.pinch = {}; this.hammer = Hammer(this.frame.canvas, { prevent_default: true }); this.hammer.on('tap', me._onTap.bind(me) ); this.hammer.on('doubletap', me._onDoubleTap.bind(me) ); this.hammer.on('hold', me._onHold.bind(me) ); this.hammer.on('pinch', me._onPinch.bind(me) ); this.hammer.on('touch', me._onTouch.bind(me) ); this.hammer.on('dragstart', me._onDragStart.bind(me) ); this.hammer.on('drag', me._onDrag.bind(me) ); this.hammer.on('dragend', me._onDragEnd.bind(me) ); this.hammer.on('release', me._onRelease.bind(me) ); this.hammer.on('mousewheel',me._onMouseWheel.bind(me) ); this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) ); // add the frame to the container element this.containerElement.appendChild(this.frame); }; /** * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin * @private */ Network.prototype._createKeyBinds = function() { var me = this; this.mousetrap = mousetrap; this.mousetrap.reset(); if (this.constants.keyboard.enabled && this.isActive()) { this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown"); this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown"); this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown"); this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("right",this._moveRight.bind(me), "keydown"); this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown"); this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup"); } if (this.constants.dataManipulation.enabled == true) { this.mousetrap.bind("escape",this._createManipulatorBar.bind(me)); this.mousetrap.bind("del",this._deleteSelected.bind(me)); } }; /** * Get the pointer location from a touch location * @param {{pageX: Number, pageY: Number}} touch * @return {{x: Number, y: Number}} pointer * @private */ Network.prototype._getPointer = function (touch) { return { x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas), y: touch.pageY - util.getAbsoluteTop(this.frame.canvas) }; }; /** * On start of a touch gesture, store the pointer * @param event * @private */ Network.prototype._onTouch = function (event) { this.drag.pointer = this._getPointer(event.gesture.center); this.drag.pinched = false; this.pinch.scale = this._getScale(); this._handleTouch(this.drag.pointer); }; /** * handle drag start event * @private */ Network.prototype._onDragStart = function () { this._handleDragStart(); }; /** * This function is called by _onDragStart. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Network.prototype._handleDragStart = function() { var drag = this.drag; var node = this._getNodeAt(drag.pointer); // note: drag.pointer is set in _onTouch to get the initial touch location drag.dragging = true; drag.selection = []; drag.translation = this._getTranslation(); drag.nodeId = null; if (node != null) { drag.nodeId = node.id; // select the clicked node if not yet selected if (!node.isSelected()) { this._selectObject(node,false); } this.emit("dragStart",{nodeIds:this.getSelection().nodes}); // create an array with the selected nodes and their original location and status for (var objectId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(objectId)) { var object = this.selectionObj.nodes[objectId]; var s = { id: object.id, node: object, // store original x, y, xFixed and yFixed, make the node temporarily Fixed x: object.x, y: object.y, xFixed: object.xFixed, yFixed: object.yFixed }; object.xFixed = true; object.yFixed = true; drag.selection.push(s); } } } }; /** * handle drag event * @private */ Network.prototype._onDrag = function (event) { this._handleOnDrag(event) }; /** * This function is called by _onDrag. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Network.prototype._handleOnDrag = function(event) { if (this.drag.pinched) { return; } // remove the focus on node if it is focussed on by the focusOnNode this.releaseNode(); var pointer = this._getPointer(event.gesture.center); var me = this; var drag = this.drag; var selection = drag.selection; if (selection && selection.length && this.constants.dragNodes == true) { // calculate delta's and new location var deltaX = pointer.x - drag.pointer.x; var deltaY = pointer.y - drag.pointer.y; // update position of all selected nodes selection.forEach(function (s) { var node = s.node; if (!s.xFixed) { node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX); } if (!s.yFixed) { node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY); } }); // start _animationStep if not yet running if (!this.moving) { this.moving = true; this.start(); } } else { if (this.constants.dragNetwork == true) { // move the network var diffX = pointer.x - this.drag.pointer.x; var diffY = pointer.y - this.drag.pointer.y; this._setTranslation( this.drag.translation.x + diffX, this.drag.translation.y + diffY ); this._redraw(); // this.moving = true; // this.start(); } } }; /** * handle drag start event * @private */ Network.prototype._onDragEnd = function (event) { this._handleDragEnd(event); }; Network.prototype._handleDragEnd = function(event) { this.drag.dragging = false; var selection = this.drag.selection; if (selection && selection.length) { selection.forEach(function (s) { // restore original xFixed and yFixed s.node.xFixed = s.xFixed; s.node.yFixed = s.yFixed; }); this.moving = true; this.start(); } else { this._redraw(); } this.emit("dragEnd",{nodeIds:this.getSelection().nodes}); } /** * handle tap/click event: select/unselect a node * @private */ Network.prototype._onTap = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleTap(pointer); }; /** * handle doubletap event * @private */ Network.prototype._onDoubleTap = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleDoubleTap(pointer); }; /** * handle long tap event: multi select nodes * @private */ Network.prototype._onHold = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleOnHold(pointer); }; /** * handle the release of the screen * * @private */ Network.prototype._onRelease = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleOnRelease(pointer); }; /** * Handle pinch event * @param event * @private */ Network.prototype._onPinch = function (event) { var pointer = this._getPointer(event.gesture.center); this.drag.pinched = true; if (!('scale' in this.pinch)) { this.pinch.scale = 1; } // TODO: enabled moving while pinching? var scale = this.pinch.scale * event.gesture.scale; this._zoom(scale, pointer) }; /** * Zoom the network in or out * @param {Number} scale a number around 1, and between 0.01 and 10 * @param {{x: Number, y: Number}} pointer Position on screen * @return {Number} appliedScale scale is limited within the boundaries * @private */ Network.prototype._zoom = function(scale, pointer) { if (this.constants.zoomable == true) { var scaleOld = this._getScale(); if (scale < 0.00001) { scale = 0.00001; } if (scale > 10) { scale = 10; } var preScaleDragPointer = null; if (this.drag !== undefined) { if (this.drag.dragging == true) { preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer); } } // + this.frame.canvas.clientHeight / 2 var translation = this._getTranslation(); var scaleFrac = scale / scaleOld; var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this._setScale(scale); this._setTranslation(tx, ty); this.updateClustersDefault(); if (preScaleDragPointer != null) { var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer); this.drag.pointer.x = postScaleDragPointer.x; this.drag.pointer.y = postScaleDragPointer.y; } this._redraw(); if (scaleOld < scale) { this.emit("zoom", {direction:"+"}); } else { this.emit("zoom", {direction:"-"}); } return scale; } }; /** * Event handler for mouse wheel event, used to zoom the timeline * See http://adomas.org/javascript-mouse-wheel/ * https://github.com/EightMedia/hammer.js/issues/256 * @param {MouseEvent} event * @private */ Network.prototype._onMouseWheel = function(event) { // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // calculate the new scale var scale = this._getScale(); var zoom = delta / 10; if (delta < 0) { zoom = zoom / (1 - zoom); } scale *= (1 + zoom); // calculate the pointer location var gesture = hammerUtil.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // apply the new scale this._zoom(scale, pointer); } // Prevent default actions caused by mouse wheel. event.preventDefault(); }; /** * Mouse move handler for checking whether the title moves over a node with a title. * @param {Event} event * @private */ Network.prototype._onMouseMoveTitle = function (event) { var gesture = hammerUtil.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // check if the previously selected node is still selected if (this.popupObj) { this._checkHidePopup(pointer); } // start a timeout that will check if the mouse is positioned above // an element var me = this; var checkShow = function() { me._checkShowPopup(pointer); }; if (this.popupTimer) { clearInterval(this.popupTimer); // stop any running calculationTimer } if (!this.drag.dragging) { this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay); } /** * Adding hover highlights */ if (this.constants.hover == true) { // removing all hover highlights for (var edgeId in this.hoverObj.edges) { if (this.hoverObj.edges.hasOwnProperty(edgeId)) { this.hoverObj.edges[edgeId].hover = false; delete this.hoverObj.edges[edgeId]; } } // adding hover highlights var obj = this._getNodeAt(pointer); if (obj == null) { obj = this._getEdgeAt(pointer); } if (obj != null) { this._hoverObject(obj); } // removing all node hover highlights except for the selected one. for (var nodeId in this.hoverObj.nodes) { if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) { this._blurObject(this.hoverObj.nodes[nodeId]); delete this.hoverObj.nodes[nodeId]; } } } this.redraw(); } }; /** * Check if there is an element on the given position in the network * (a node or edge). If so, and if this element has a title, * show a popup window with its title. * * @param {{x:Number, y:Number}} pointer * @private */ Network.prototype._checkShowPopup = function (pointer) { var obj = { left: this._XconvertDOMtoCanvas(pointer.x), top: this._YconvertDOMtoCanvas(pointer.y), right: this._XconvertDOMtoCanvas(pointer.x), bottom: this._YconvertDOMtoCanvas(pointer.y) }; var id; var lastPopupNode = this.popupObj; if (this.popupObj == undefined) { // search the nodes for overlap, select the top one in case of multiple nodes var nodes = this.nodes; for (id in nodes) { if (nodes.hasOwnProperty(id)) { var node = nodes[id]; if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) { this.popupObj = node; break; } } } } if (this.popupObj === undefined) { // search the edges for overlap var edges = this.edges; for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; if (edge.connected && (edge.getTitle() !== undefined) && edge.isOverlappingWith(obj)) { this.popupObj = edge; break; } } } } if (this.popupObj) { // show popup message window if (this.popupObj != lastPopupNode) { var me = this; if (!me.popup) { me.popup = new Popup(me.frame, me.constants.tooltip); } // adjust a small offset such that the mouse cursor is located in the // bottom left location of the popup, and you can easily move over the // popup area me.popup.setPosition(pointer.x - 3, pointer.y - 3); me.popup.setText(me.popupObj.getTitle()); me.popup.show(); } } else { if (this.popup) { this.popup.hide(); } } }; /** * Check if the popup must be hided, which is the case when the mouse is no * longer hovering on the object * @param {{x:Number, y:Number}} pointer * @private */ Network.prototype._checkHidePopup = function (pointer) { if (!this.popupObj || !this._getNodeAt(pointer) ) { this.popupObj = undefined; if (this.popup) { this.popup.hide(); } } }; /** * Set a new size for the network * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Network.prototype.setSize = function(width, height) { var emitEvent = false; if (width != this.constants.width || height != this.constants.height || this.frame.style.width != width || this.frame.style.height != height) { this.frame.style.width = width; this.frame.style.height = height; this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; this.constants.width = width; this.constants.height = height; emitEvent = true; } else { // this would adapt the width of the canvas to the width from 100% if and only if // there is a change. if (this.frame.canvas.width != this.frame.canvas.clientWidth) { this.frame.canvas.width = this.frame.canvas.clientWidth; emitEvent = true; } if (this.frame.canvas.height != this.frame.canvas.clientHeight) { this.frame.canvas.height = this.frame.canvas.clientHeight; emitEvent = true; } } if (emitEvent == true) { this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height}); } }; /** * Set a data set with nodes for the network * @param {Array | DataSet | DataView} nodes The data containing the nodes. * @private */ Network.prototype._setNodes = function(nodes) { var oldNodesData = this.nodesData; if (nodes instanceof DataSet || nodes instanceof DataView) { this.nodesData = nodes; } else if (nodes instanceof Array) { this.nodesData = new DataSet(); this.nodesData.add(nodes); } else if (!nodes) { this.nodesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldNodesData) { // unsubscribe from old dataset util.forEach(this.nodesListeners, function (callback, event) { oldNodesData.off(event, callback); }); } // remove drawn nodes this.nodes = {}; if (this.nodesData) { // subscribe to new dataset var me = this; util.forEach(this.nodesListeners, function (callback, event) { me.nodesData.on(event, callback); }); // draw all new nodes var ids = this.nodesData.getIds(); this._addNodes(ids); } this._updateSelection(); }; /** * Add nodes * @param {Number[] | String[]} ids * @private */ Network.prototype._addNodes = function(ids) { var id; for (var i = 0, len = ids.length; i < len; i++) { id = ids[i]; var data = this.nodesData.get(id); var node = new Node(data, this.images, this.groups, this.constants); this.nodes[id] = node; // note: this may replace an existing node if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) { var radius = 10 * 0.1*ids.length + 10; var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} } this.moving = true; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateValueRange(this.nodes); this.updateLabels(); }; /** * Update existing nodes, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Network.prototype._updateNodes = function(ids) { var nodes = this.nodes, nodesData = this.nodesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var node = nodes[id]; var data = nodesData.get(id); if (node) { // update node node.setProperties(data, this.constants); } else { // create node node = new Node(properties, this.images, this.groups, this.constants); nodes[id] = node; } } this.moving = true; if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateNodeIndexList(); this._reconnectEdges(); this._updateValueRange(nodes); }; /** * Remove existing nodes. If nodes do not exist, the method will just ignore it. * @param {Number[] | String[]} ids * @private */ Network.prototype._removeNodes = function(ids) { var nodes = this.nodes; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; delete nodes[id]; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateSelection(); this._updateValueRange(nodes); }; /** * Load edges by reading the data table * @param {Array | DataSet | DataView} edges The data containing the edges. * @private * @private */ Network.prototype._setEdges = function(edges) { var oldEdgesData = this.edgesData; if (edges instanceof DataSet || edges instanceof DataView) { this.edgesData = edges; } else if (edges instanceof Array) { this.edgesData = new DataSet(); this.edgesData.add(edges); } else if (!edges) { this.edgesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldEdgesData) { // unsubscribe from old dataset util.forEach(this.edgesListeners, function (callback, event) { oldEdgesData.off(event, callback); }); } // remove drawn edges this.edges = {}; if (this.edgesData) { // subscribe to new dataset var me = this; util.forEach(this.edgesListeners, function (callback, event) { me.edgesData.on(event, callback); }); // draw all new nodes var ids = this.edgesData.getIds(); this._addEdges(ids); } this._reconnectEdges(); }; /** * Add edges * @param {Number[] | String[]} ids * @private */ Network.prototype._addEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var oldEdge = edges[id]; if (oldEdge) { oldEdge.disconnect(); } var data = edgesData.get(id, {"showInternalIds" : true}); edges[id] = new Edge(data, this, this.constants); } this.moving = true; this._updateValueRange(edges); this._createBezierNodes(); this._updateCalculationNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } }; /** * Update existing edges, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Network.prototype._updateEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var data = edgesData.get(id); var edge = edges[id]; if (edge) { // update edge edge.disconnect(); edge.setProperties(data, this.constants); edge.connect(); } else { // create edge edge = new Edge(data, this, this.constants); this.edges[id] = edge; } } this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this.moving = true; this._updateValueRange(edges); }; /** * Remove existing edges. Non existing ids will be ignored * @param {Number[] | String[]} ids * @private */ Network.prototype._removeEdges = function (ids) { var edges = this.edges; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var edge = edges[id]; if (edge) { if (edge.via != null) { delete this.sectors['support']['nodes'][edge.via.id]; } edge.disconnect(); delete edges[id]; } } this.moving = true; this._updateValueRange(edges); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Reconnect all edges * @private */ Network.prototype._reconnectEdges = function() { var id, nodes = this.nodes, edges = this.edges; for (id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].edges = []; nodes[id].dynamicEdges = []; } } for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.from = null; edge.to = null; edge.connect(); } } }; /** * Update the values of all object in the given array according to the current * value range of the objects in the array. * @param {Object} obj An object containing a set of Edges or Nodes * The objects must have a method getValue() and * setValueRange(min, max). * @private */ Network.prototype._updateValueRange = function(obj) { var id; // determine the range of the objects var valueMin = undefined; var valueMax = undefined; for (id in obj) { if (obj.hasOwnProperty(id)) { var value = obj[id].getValue(); if (value !== undefined) { valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin); valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax); } } } // adjust the range of all objects if (valueMin !== undefined && valueMax !== undefined) { for (id in obj) { if (obj.hasOwnProperty(id)) { obj[id].setValueRange(valueMin, valueMax); } } } }; /** * Redraw the network with the current data * chart will be resized too. */ Network.prototype.redraw = function() { this.setSize(this.constants.width, this.constants.height); this._redraw(); }; /** * Redraw the network with the current data * @private */ Network.prototype._redraw = function() { var ctx = this.frame.canvas.getContext('2d'); // clear the canvas var w = this.frame.canvas.width; var h = this.frame.canvas.height; ctx.clearRect(0, 0, w, h); // set scaling and translation ctx.save(); ctx.translate(this.translation.x, this.translation.y); ctx.scale(this.scale, this.scale); this.canvasTopLeft = { "x": this._XconvertDOMtoCanvas(0), "y": this._YconvertDOMtoCanvas(0) }; this.canvasBottomRight = { "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth), "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight) }; this._doInAllSectors("_drawAllSectorNodes",ctx); if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) { this._doInAllSectors("_drawEdges",ctx); } if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) { this._doInAllSectors("_drawNodes",ctx,false); } if (this.controlNodesActive == true) { this._doInAllSectors("_drawControlNodes",ctx); } // this._doInSupportSector("_drawNodes",ctx,true); // this._drawTree(ctx,"#F00F0F"); // restore original scaling and translation ctx.restore(); }; /** * Set the translation of the network * @param {Number} offsetX Horizontal offset * @param {Number} offsetY Vertical offset * @private */ Network.prototype._setTranslation = function(offsetX, offsetY) { if (this.translation === undefined) { this.translation = { x: 0, y: 0 }; } if (offsetX !== undefined) { this.translation.x = offsetX; } if (offsetY !== undefined) { this.translation.y = offsetY; } this.emit('viewChanged'); }; /** * Get the translation of the network * @return {Object} translation An object with parameters x and y, both a number * @private */ Network.prototype._getTranslation = function() { return { x: this.translation.x, y: this.translation.y }; }; /** * Scale the network * @param {Number} scale Scaling factor 1.0 is unscaled * @private */ Network.prototype._setScale = function(scale) { this.scale = scale; }; /** * Get the current scale of the network * @return {Number} scale Scaling factor 1.0 is unscaled * @private */ Network.prototype._getScale = function() { return this.scale; }; /** * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} x * @returns {number} * @private */ Network.prototype._XconvertDOMtoCanvas = function(x) { return (x - this.translation.x) / this.scale; }; /** * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the X coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} x * @returns {number} * @private */ Network.prototype._XconvertCanvasToDOM = function(x) { return x * this.scale + this.translation.x; }; /** * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} y * @returns {number} * @private */ Network.prototype._YconvertDOMtoCanvas = function(y) { return (y - this.translation.y) / this.scale; }; /** * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} y * @returns {number} * @private */ Network.prototype._YconvertCanvasToDOM = function(y) { return y * this.scale + this.translation.y ; }; /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Network.prototype.canvasToDOM = function (pos) { return {x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y)}; }; /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Network.prototype.DOMtoCanvas = function (pos) { return {x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y)}; }; /** * Redraw all nodes * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @param {Boolean} [alwaysShow] * @private */ Network.prototype._drawNodes = function(ctx,alwaysShow) { if (alwaysShow === undefined) { alwaysShow = false; } // first draw the unselected nodes var nodes = this.nodes; var selected = []; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight); if (nodes[id].isSelected()) { selected.push(id); } else { if (nodes[id].inArea() || alwaysShow) { nodes[id].draw(ctx); } } } } // draw the selected nodes on top for (var s = 0, sMax = selected.length; s < sMax; s++) { if (nodes[selected[s]].inArea() || alwaysShow) { nodes[selected[s]].draw(ctx); } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Network.prototype._drawEdges = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.setScale(this.scale); if (edge.connected) { edges[id].draw(ctx); } } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Network.prototype._drawControlNodes = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { edges[id]._drawControlNodes(ctx); } } }; /** * Find a stable position for all nodes * @private */ Network.prototype._stabilize = function() { if (this.constants.freezeForStabilization == true) { this._freezeDefinedNodes(); } // find stable position var count = 0; while (this.moving && count < this.constants.stabilizationIterations) { this._physicsTick(); count++; } this.zoomExtent(undefined,false,true); if (this.constants.freezeForStabilization == true) { this._restoreFrozenNodes(); } }; /** * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization * because only the supportnodes for the smoothCurves have to settle. * * @private */ Network.prototype._freezeDefinedNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].x != null && nodes[id].y != null) { nodes[id].fixedData.x = nodes[id].xFixed; nodes[id].fixedData.y = nodes[id].yFixed; nodes[id].xFixed = true; nodes[id].yFixed = true; } } } }; /** * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. * * @private */ Network.prototype._restoreFrozenNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].fixedData.x != null) { nodes[id].xFixed = nodes[id].fixedData.x; nodes[id].yFixed = nodes[id].fixedData.y; } } } }; /** * Check if any of the nodes is still moving * @param {number} vmin the minimum velocity considered as 'moving' * @return {boolean} true if moving, false if non of the nodes is moving * @private */ Network.prototype._isMoving = function(vmin) { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) { return true; } } return false; }; /** * /** * Perform one discrete step for all nodes * * @private */ Network.prototype._discreteStepNodes = function() { var interval = this.physicsDiscreteStepsize; var nodes = this.nodes; var nodeId; var nodesPresent = false; if (this.constants.maxVelocity > 0) { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity); nodesPresent = true; } } } else { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStep(interval); nodesPresent = true; } } } if (nodesPresent == true) { var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05); if (vminCorrected > 0.5*this.constants.maxVelocity) { return true; } else { return this._isMoving(vminCorrected); } } return false; }; /** * A single simulation step (or "tick") in the physics simulation * * @private */ Network.prototype._physicsTick = function() { if (!this.freezeSimulation) { if (this.moving == true) { var mainMovingStatus = false; var supportMovingStatus = false; this._doInAllActiveSectors("_initializeForceCalculation"); var mainMoving = this._doInAllActiveSectors("_discreteStepNodes"); if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { supportMovingStatus = this._doInSupportSector("_discreteStepNodes"); } // gather movement data from all sectors, if one moves, we are NOT stabilzied for (var i = 0; i < mainMoving.length; i++) {mainMovingStatus = mainMoving[0] || mainMovingStatus;} // determine if the network has stabilzied this.moving = mainMovingStatus || supportMovingStatus; this.stabilizationIterations++; } } }; /** * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick. * It reschedules itself at the beginning of the function * * @private */ Network.prototype._animationStep = function() { // reset the timer so a new scheduled animation step can be set this.timer = undefined; // handle the keyboad movement this._handleNavigation(); // this schedules a new animation step this.start(); // start the physics simulation var calculationTime = Date.now(); var maxSteps = 1; this._physicsTick(); var timeRequired = Date.now() - calculationTime; while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) { this._physicsTick(); timeRequired = Date.now() - calculationTime; maxSteps++; } // start the rendering process var renderTime = Date.now(); this._redraw(); this.renderTime = Date.now() - renderTime; }; if (typeof window !== 'undefined') { window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** * Schedule a animation step with the refreshrate interval. */ Network.prototype.start = function() { if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) { if (!this.timer) { var ua = navigator.userAgent.toLowerCase(); var requiresTimeout = false; if (ua.indexOf('msie 9.0') != -1) { // IE 9 requiresTimeout = true; } else if (ua.indexOf('safari') != -1) { // safari if (ua.indexOf('chrome') <= -1) { requiresTimeout = true; } } if (requiresTimeout == true) { this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } else{ this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } } } else { this._redraw(); if (this.stabilizationIterations > 0) { // trigger the "stabilized" event. // The event is triggered on the next tick, to prevent the case that // it is fired while initializing the Network, in which case you would not // be able to catch it var me = this; var params = { iterations: me.stabilizationIterations }; me.stabilizationIterations = 0; setTimeout(function () { me.emit("stabilized", params); }, 0); } } }; /** * Move the network according to the keyboard presses. * * @private */ Network.prototype._handleNavigation = function() { if (this.xIncrement != 0 || this.yIncrement != 0) { var translation = this._getTranslation(); this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement); } if (this.zoomIncrement != 0) { var center = { x: this.frame.canvas.clientWidth / 2, y: this.frame.canvas.clientHeight / 2 }; this._zoom(this.scale*(1 + this.zoomIncrement), center); } }; /** * Freeze the _animationStep */ Network.prototype.toggleFreeze = function() { if (this.freezeSimulation == false) { this.freezeSimulation = true; } else { this.freezeSimulation = false; this.start(); } }; /** * This function cleans the support nodes if they are not needed and adds them when they are. * * @param {boolean} [disableStart] * @private */ Network.prototype._configureSmoothCurves = function(disableStart) { if (disableStart === undefined) { disableStart = true; } if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._createBezierNodes(); // cleanup unused support nodes for (var nodeId in this.sectors['support']['nodes']) { if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) { if (this.edges[this.sectors['support']['nodes'][nodeId].parentEdgeId] === undefined) { delete this.sectors['support']['nodes'][nodeId]; } } } } else { // delete the support nodes this.sectors['support']['nodes'] = {}; for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.edges[edgeId].via = null; } } } this._updateCalculationNodes(); if (!disableStart) { this.moving = true; this.start(); } }; /** * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but * are used for the force calculation. * * @private */ Network.prototype._createBezierNodes = function() { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.via == null) { var nodeId = "edgeId:".concat(edge.id); this.sectors['support']['nodes'][nodeId] = new Node( {id:nodeId, mass:1, shape:'circle', image:"", internalMultiplier:1 },{},{},this.constants); edge.via = this.sectors['support']['nodes'][nodeId]; edge.via.parentEdgeId = edge.id; edge.positionBezierNode(); } } } } }; /** * load the functions that load the mixins into the prototype. * * @private */ Network.prototype._initializeMixinLoaders = function () { for (var mixin in MixinLoader) { if (MixinLoader.hasOwnProperty(mixin)) { Network.prototype[mixin] = MixinLoader[mixin]; } } }; /** * Load the XY positions of the nodes into the dataset. */ Network.prototype.storePosition = function() { var dataArray = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; var allowedToMoveX = !this.nodes.xFixed; var allowedToMoveY = !this.nodes.yFixed; if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) { dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY}); } } } this.nodesData.update(dataArray); }; /** * Center a node in view. * * @param {Number} nodeId * @param {Number} [options] */ Network.prototype.focusOnNode = function (nodeId, options) { if (this.nodes.hasOwnProperty(nodeId)) { if (options === undefined) { options = {}; } var nodePosition = {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y}; options.position = nodePosition; options.lockedOnNode = nodeId; this.moveTo(options) } else { console.log("This nodeId cannot be found."); } }; /** * * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels * | options.scale = Number // scale to move to * | options.position = {x:Number, y:Number} // position to move to * | options.animation = {duration:Number, easingFunction:String} || Boolean // position to move to */ Network.prototype.moveTo = function (options) { if (options === undefined) { options = {}; return; } if (options.offset === undefined) {options.offset = {x: 0, y: 0}; } if (options.offset.x === undefined) {options.offset.x = 0; } if (options.offset.y === undefined) {options.offset.y = 0; } if (options.scale === undefined) {options.scale = this._getScale(); } if (options.position === undefined) {options.position = this._getTranslation();} if (options.animation === undefined) {options.animation = {duration:0}; } if (options.animation === false ) {options.animation = {duration:0}; } if (options.animation === true ) {options.animation = {}; } if (options.animation.duration === undefined) {options.animation.duration = 1000; } // default duration if (options.animation.easingFunction === undefined) {options.animation.easingFunction = "easeInOutQuad"; } // default easing function this.animateView(options); }; /** * * @param {Object} options | options.offset = {x:Number, y:Number} // offset from the center in DOM pixels * | options.time = Number // animation time in milliseconds * | options.scale = Number // scale to animate to * | options.position = {x:Number, y:Number} // position to animate to * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad, * // easeInCubic, easeOutCubic, easeInOutCubic, * // easeInQuart, easeOutQuart, easeInOutQuart, * // easeInQuint, easeOutQuint, easeInOutQuint */ Network.prototype.animateView = function (options) { if (options === undefined) { options = {}; return; } // release if something focussed on the node this.releaseNode(); if (options.locked == true) { this.lockedOnNodeId = options.lockedOnNode; this.lockedOnNodeOffset = options.offset; } // forcefully complete the old animation if it was still running if (this.easingTime != 0) { this._transitionRedraw(1); // by setting easingtime to 1, we finish the animation. } this.sourceScale = this._getScale(); this.sourceTranslation = this._getTranslation(); this.targetScale = options.scale; // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw // but at least then we'll have the target transition this._setScale(this.targetScale); var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight}); var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node x: viewCenter.x - options.position.x, y: viewCenter.y - options.position.y }; this.targetTranslation = { x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x, y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y }; // if the time is set to 0, don't do an animation if (options.animation.duration == 0) { if (this.lockedOnNodeId != null) { this._classicRedraw = this._redraw; this._redraw = this._lockedRedraw; } else { this._setScale(this.targetScale); this._setTranslation(this.targetTranslation.x, this.targetTranslation.y); this._redraw(); } } else { this.animationSpeed = 1 / (this.renderRefreshRate * options.animation.duration * 0.001) || 1 / this.renderRefreshRate; this.animationEasingFunction = options.animation.easingFunction; this._classicRedraw = this._redraw; this._redraw = this._transitionRedraw; this._redraw(); this.moving = true; this.start(); } }; Network.prototype._lockedRedraw = function () { var nodePosition = {x: this.nodes[this.lockedOnNodeId].x, y: this.nodes[this.lockedOnNodeId].y}; var viewCenter = this.DOMtoCanvas({x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight}); var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node x: viewCenter.x - nodePosition.x, y: viewCenter.y - nodePosition.y }; var sourceTranslation = this._getTranslation(); var targetTranslation = { x: sourceTranslation.x + distanceFromCenter.x * this.scale + this.lockedOnNodeOffset.x, y: sourceTranslation.y + distanceFromCenter.y * this.scale + this.lockedOnNodeOffset.y }; this._setTranslation(targetTranslation.x,targetTranslation.y); this._classicRedraw(); } Network.prototype.releaseNode = function () { if (this.lockedOnNodeId != null) { this._redraw = this._classicRedraw; this.lockedOnNodeId = null; this.lockedOnNodeOffset = null; } } /** * * @param easingTime * @private */ Network.prototype._transitionRedraw = function (easingTime) { this.easingTime = easingTime || this.easingTime + this.animationSpeed; this.easingTime += this.animationSpeed; var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime); this._setScale(this.sourceScale + (this.targetScale - this.sourceScale) * progress); this._setTranslation( this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress, this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress ); this._classicRedraw(); this.moving = true; // cleanup if (this.easingTime >= 1.0) { this.easingTime = 0; if (this.lockedOnNodeId != null) { this._redraw = this._lockedRedraw; } else { this._redraw = this._classicRedraw; } this.emit("animationFinished"); } }; Network.prototype._classicRedraw = function () { // placeholder function to be overloaded by animations; }; /** * Returns true when the Network is active. * @returns {boolean} */ Network.prototype.isActive = function () { return !this.activator || this.activator.active; }; /** * Sets the scale * @returns {Number} */ Network.prototype.setScale = function () { return this._setScale(); }; /** * Returns the scale * @returns {Number} */ Network.prototype.getScale = function () { return this._getScale(); }; module.exports = Network; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Node = __webpack_require__(37); /** * @class Edge * * A edge connects two nodes * @param {Object} properties Object with properties. Must contain * At least properties from and to. * Available properties: from (number), * to (number), label (string, color (string), * width (number), style (string), * length (number), title (string) * @param {Network} network A Network object, used to find and edge to * nodes. * @param {Object} constants An object with default values for * example for the color */ function Edge (properties, network, networkConstants) { if (!network) { throw "No network provided"; } var fields = ['edges','physics']; var constants = util.selectiveBridgeObject(fields,networkConstants); this.options = constants.edges; this.physics = constants.physics; this.options['smoothCurves'] = networkConstants['smoothCurves']; this.network = network; // initialize variables this.id = undefined; this.fromId = undefined; this.toId = undefined; this.title = undefined; this.widthSelected = this.options.width * this.options.widthSelectionMultiplier; this.value = undefined; this.selected = false; this.hover = false; this.labelDimensions = {top:0,left:0,width:0,height:0}; this.from = null; // a node this.to = null; // a node this.via = null; // a temp node // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster // by storing the original information we can revert to the original connection when the cluser is opened. this.originalFromId = []; this.originalToId = []; this.connected = false; this.widthFixed = false; this.lengthFixed = false; this.setProperties(properties); this.controlNodesEnabled = false; this.controlNodes = {from:null, to:null, positions:{}}; this.connectedNode = null; } /** * Set or overwrite properties for the edge * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Edge.prototype.setProperties = function(properties) { if (!properties) { return; } var fields = ['style','fontSize','fontFace','fontColor','fontFill','width', 'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor' ]; util.selectiveDeepExtend(fields, this.options, properties); if (properties.from !== undefined) {this.fromId = properties.from;} if (properties.to !== undefined) {this.toId = properties.to;} if (properties.id !== undefined) {this.id = properties.id;} if (properties.label !== undefined) {this.label = properties.label;} if (properties.title !== undefined) {this.title = properties.title;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.length !== undefined) {this.physics.springLength = properties.length;} if (properties.color !== undefined) { this.options.inheritColor = false; if (util.isString(properties.color)) { this.options.color.color = properties.color; this.options.color.highlight = properties.color; } else { if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;} if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;} if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;} } } // A node is connected when it has a from and to node. this.connect(); this.widthFixed = this.widthFixed || (properties.width !== undefined); this.lengthFixed = this.lengthFixed || (properties.length !== undefined); this.widthSelected = this.options.width* this.options.widthSelectionMultiplier; // set draw method based on style switch (this.options.style) { case 'line': this.draw = this._drawLine; break; case 'arrow': this.draw = this._drawArrow; break; case 'arrow-center': this.draw = this._drawArrowCenter; break; case 'dash-line': this.draw = this._drawDashLine; break; default: this.draw = this._drawLine; break; } }; /** * Connect an edge to its nodes */ Edge.prototype.connect = function () { this.disconnect(); this.from = this.network.nodes[this.fromId] || null; this.to = this.network.nodes[this.toId] || null; this.connected = (this.from && this.to); if (this.connected) { this.from.attachEdge(this); this.to.attachEdge(this); } else { if (this.from) { this.from.detachEdge(this); } if (this.to) { this.to.detachEdge(this); } } }; /** * Disconnect an edge from its nodes */ Edge.prototype.disconnect = function () { if (this.from) { this.from.detachEdge(this); this.from = null; } if (this.to) { this.to.detachEdge(this); this.to = null; } this.connected = false; }; /** * get the title of this edge. * @return {string} title The title of the edge, or undefined when no title * has been set. */ Edge.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Retrieve the value of the edge. Can be undefined * @return {Number} value */ Edge.prototype.getValue = function() { return this.value; }; /** * Adjust the value range of the edge. The edge will adjust it's width * based on its value. * @param {Number} min * @param {Number} max */ Edge.prototype.setValueRange = function(min, max) { if (!this.widthFixed && this.value !== undefined) { var scale = (this.options.widthMax - this.options.widthMin) / (max - min); this.options.width= (this.value - min) * scale + this.options.widthMin; this.widthSelected = this.options.width* this.options.widthSelectionMultiplier; } }; /** * Redraw a edge * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Edge.prototype.draw = function(ctx) { throw "Method draw not initialized in edge"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top * @return {boolean} True if location is located on the edge */ Edge.prototype.isOverlappingWith = function(obj) { if (this.connected) { var distMax = 10; var xFrom = this.from.x; var yFrom = this.from.y; var xTo = this.to.x; var yTo = this.to.y; var xObj = obj.left; var yObj = obj.top; var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); return (dist < distMax); } else { return false } }; Edge.prototype._getColor = function() { var colorObj = this.options.color; if (this.options.inheritColor == "to") { colorObj = { highlight: this.to.options.color.highlight.border, hover: this.to.options.color.hover.border, color: this.to.options.color.border }; } else if (this.options.inheritColor == "from" || this.options.inheritColor == true) { colorObj = { highlight: this.from.options.color.highlight.border, hover: this.from.options.color.hover.border, color: this.from.options.color.border }; } if (this.selected == true) {return colorObj.highlight;} else if (this.hover == true) {return colorObj.hover;} else {return colorObj.color;} } /** * Redraw a edge as a line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawLine = function(ctx) { // set style ctx.strokeStyle = this._getColor(); ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line var via = this._line(ctx); // draw label var point; if (this.label) { if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { var x, y; var radius = this.physics.springLength / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } this._circle(ctx, x, y, radius); point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } }; /** * Get the line width of the edge. Depends on width and whether one of the * connected nodes is selected. * @return {Number} width * @private */ Edge.prototype._getLineWidth = function() { if (this.selected == true) { return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv); } else { if (this.hover == true) { return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv); } else { return Math.max(this.options.width, 0.3*this.networkScaleInv); } } }; Edge.prototype._getViaCoordinates = function () { var xVia = null; var yVia = null; var factor = this.options.smoothCurves.roundness; var type = this.options.smoothCurves.type; var dx = Math.abs(this.from.x - this.to.x); var dy = Math.abs(this.from.y - this.to.y); if (type == 'discrete' || type == 'diagonalCross') { if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dy; yVia = this.from.y - factor * dy; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dy; yVia = this.from.y - factor * dy; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dy; yVia = this.from.y + factor * dy; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dy; yVia = this.from.y + factor * dy; } } if (type == "discrete") { xVia = dx < factor * dy ? this.from.x : xVia; } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dx; yVia = this.from.y - factor * dx; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dx; yVia = this.from.y - factor * dx; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dx; yVia = this.from.y + factor * dx; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dx; yVia = this.from.y + factor * dx; } } if (type == "discrete") { yVia = dy < factor * dx ? this.from.y : yVia; } } } else if (type == "straightCross") { if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down xVia = this.from.x; if (this.from.y < this.to.y) { yVia = this.to.y - (1-factor) * dy; } else { yVia = this.to.y + (1-factor) * dy; } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right if (this.from.x < this.to.x) { xVia = this.to.x - (1-factor) * dx; } else { xVia = this.to.x + (1-factor) * dx; } yVia = this.from.y; } } else if (type == 'horizontal') { if (this.from.x < this.to.x) { xVia = this.to.x - (1-factor) * dx; } else { xVia = this.to.x + (1-factor) * dx; } yVia = this.from.y; } else if (type == 'vertical') { xVia = this.from.x; if (this.from.y < this.to.y) { yVia = this.to.y - (1-factor) * dy; } else { yVia = this.to.y + (1-factor) * dy; } } else { // continuous if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { // console.log(1) xVia = this.from.x + factor * dy; yVia = this.from.y - factor * dy; xVia = this.to.x < xVia ? this.to.x : xVia; } else if (this.from.x > this.to.x) { // console.log(2) xVia = this.from.x - factor * dy; yVia = this.from.y - factor * dy; xVia = this.to.x > xVia ? this.to.x :xVia; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { // console.log(3) xVia = this.from.x + factor * dy; yVia = this.from.y + factor * dy; xVia = this.to.x < xVia ? this.to.x : xVia; } else if (this.from.x > this.to.x) { // console.log(4, this.from.x, this.to.x) xVia = this.from.x - factor * dy; yVia = this.from.y + factor * dy; xVia = this.to.x > xVia ? this.to.x : xVia; } } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { // console.log(5) xVia = this.from.x + factor * dx; yVia = this.from.y - factor * dx; yVia = this.to.y > yVia ? this.to.y : yVia; } else if (this.from.x > this.to.x) { // console.log(6) xVia = this.from.x - factor * dx; yVia = this.from.y - factor * dx; yVia = this.to.y > yVia ? this.to.y : yVia; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { // console.log(7) xVia = this.from.x + factor * dx; yVia = this.from.y + factor * dx; yVia = this.to.y < yVia ? this.to.y : yVia; } else if (this.from.x > this.to.x) { // console.log(8) xVia = this.from.x - factor * dx; yVia = this.from.y + factor * dx; yVia = this.to.y < yVia ? this.to.y : yVia; } } } } return {x:xVia, y:yVia}; } /** * Draw a line between two nodes * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._line = function (ctx) { // draw a straight line ctx.beginPath(); ctx.moveTo(this.from.x, this.from.y); if (this.options.smoothCurves.enabled == true) { if (this.options.smoothCurves.dynamic == false) { var via = this._getViaCoordinates(); if (via.x == null) { ctx.lineTo(this.to.x, this.to.y); ctx.stroke(); return null; } else { // this.via.x = via.x; // this.via.y = via.y; ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y); ctx.stroke(); return via; } } else { ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y); ctx.stroke(); return this.via; } } else { ctx.lineTo(this.to.x, this.to.y); ctx.stroke(); return null; } }; /** * Draw a line from a node to itself, a circle * @param {CanvasRenderingContext2D} ctx * @param {Number} x * @param {Number} y * @param {Number} radius * @private */ Edge.prototype._circle = function (ctx, x, y, radius) { // draw a circle ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); }; /** * Draw label with white background and with the middle at (x, y) * @param {CanvasRenderingContext2D} ctx * @param {String} text * @param {Number} x * @param {Number} y * @private */ Edge.prototype._label = function (ctx, text, x, y) { if (text) { // TODO: cache the calculated size ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace; var lines = String(text).split('\n'); var lineCount = lines.length; var fontSize = (Number(this.options.fontSize) + 4); var yLine = y + (1 - lineCount) / 2 * fontSize; var width = ctx.measureText(lines[0]).width; for (var i = 1; i < lineCount; i++) { var lineWidth = ctx.measureText(lines[i]).width; width = lineWidth > width ? lineWidth : width; } var height = this.options.fontSize * lineCount; var left = x - width / 2; var top = y - height / 2; this.labelDimensions = {top:top,left:left,width:width,height:height}; if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") { ctx.fillStyle = this.options.fontFill; ctx.fillRect(left, top, width, height); } // draw text ctx.fillStyle = this.options.fontColor || "black"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; for (var i = 0; i < lineCount; i++) { ctx.fillText(lines[i], x, yLine); yLine += fontSize; } } }; /** * Redraw a edge as a dashed line * Draw this edge in the given canvas * @author David Jordan * @date 2012-08-08 * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawDashLine = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover;} else {ctx.strokeStyle = this.options.color.color;} ctx.lineWidth = this._getLineWidth(); var via = null; // only firefox and chrome support this method, else we use the legacy one. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) { // configure the dash pattern var pattern = [0]; if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) { pattern = [this.options.dash.length,this.options.dash.gap]; } else { pattern = [5,5]; } // set dash settings for chrome or firefox if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash(pattern); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = pattern; ctx.mozDashOffset = 0; } // draw the line via = this._line(ctx); // restore the dash settings. if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash([0]); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = [0]; ctx.mozDashOffset = 0; } } else { // unsupporting smooth lines // draw dashed line ctx.beginPath(); ctx.lineCap = 'round'; if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]); } else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.options.dash.length,this.options.dash.gap]); } else //If all else fails draw a line { ctx.moveTo(this.from.x, this.from.y); ctx.lineTo(this.to.x, this.to.y); } ctx.stroke(); } // draw label if (this.label) { var point; if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } }; /** * Get a point on a line * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnLine = function (percentage) { return { x: (1 - percentage) * this.from.x + percentage * this.to.x, y: (1 - percentage) * this.from.y + percentage * this.to.y } }; /** * Get a point on a circle * @param {Number} x * @param {Number} y * @param {Number} radius * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnCircle = function (x, y, radius, percentage) { var angle = (percentage - 3/8) * 2 * Math.PI; return { x: x + radius * Math.cos(angle), y: y - radius * Math.sin(angle) } }; /** * Redraw a edge as a line with an arrow halfway the line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrowCenter = function(ctx) { var point; // set style if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;} else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;} ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line var via = this._line(ctx); var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; // draw an arrow halfway the line if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var x, y; var radius = 0.25 * Math.max(100,this.physics.springLength); var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height * 0.5; } this._circle(ctx, x, y, radius); // draw all arrows var angle = 0.2 * Math.PI; var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; point = this._pointOnCircle(x, y, radius, 0.5); ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Redraw a edge as a line with an arrow * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrow = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;} else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;} ctx.lineWidth = this._getLineWidth(); var angle, length; //draw a line if (this.from != this.to) { angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; var via; if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) { via = this.via; } else if (this.options.smoothCurves.enabled == true) { via = this._getViaCoordinates(); } if (this.options.smoothCurves.enabled == true && via.x != null) { angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x)); dx = (this.to.x - via.x); dy = (this.to.y - via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.options.smoothCurves.enabled == true && via.x != null) { xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } ctx.beginPath(); ctx.moveTo(xFrom,yFrom); if (this.options.smoothCurves.enabled == true && via.x != null) { ctx.quadraticCurveTo(via.x,via.y,xTo, yTo); } else { ctx.lineTo(xTo, yTo); } ctx.stroke(); // draw arrow at the end of the line length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; ctx.arrow(xTo, yTo, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { var point; if (this.options.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var node = this.from; var x, y, arrow; var radius = 0.25 * Math.max(100,this.physics.springLength); if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; arrow = { x: x, y: node.y, angle: 0.9 * Math.PI }; } else { x = node.x + radius; y = node.y - node.height * 0.5; arrow = { x: node.x, y: y, angle: 0.6 * Math.PI }; } ctx.beginPath(); // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); // draw all arrows var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor; ctx.arrow(arrow.x, arrow.y, arrow.angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Calculate the distance between a point (x3,y3) and a line segment from * (x1,y1) to (x2,y2). * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @private */ Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point var returnValue = 0; if (this.from != this.to) { if (this.options.smoothCurves.enabled == true) { var xVia, yVia; if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) { xVia = this.via.x; yVia = this.via.y; } else { var via = this._getViaCoordinates(); xVia = via.x; yVia = via.y; } var minDistance = 1e9; var distance; var i,t,x,y, lastX, lastY; for (i = 0; i < 10; i++) { t = 0.1*i; x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2; y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2; if (i > 0) { distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3); minDistance = distance < minDistance ? distance : minDistance; } lastX = x; lastY = y; } returnValue = minDistance; } else { returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3); } } else { var x, y, dx, dy; var radius = 0.25 * this.physics.springLength; var node = this.from; if (node.width > node.height) { x = node.x + 0.5 * node.width; y = node.y - radius; } else { x = node.x + radius; y = node.y - 0.5 * node.height; } dx = x - x3; dy = y - y3; returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius); } if (this.labelDimensions.left < x3 && this.labelDimensions.left + this.labelDimensions.width > x3 && this.labelDimensions.top < y3 && this.labelDimensions.top + this.labelDimensions.height > y3) { return 0; } else { return returnValue; } }; Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) { var px = x2-x1, py = y2-y1, something = px*px + py*py, u = ((x3 - x1) * px + (y3 - y1) * py) / something; if (u > 1) { u = 1; } else if (u < 0) { u = 0; } var x = x1 + u * px, y = y1 + u * py, dx = x - x3, dy = y - y3; //# Note: If the actual distance does not matter, //# if you only want to compare what this function //# returns to other results of this function, you //# can just return the squared distance instead //# (i.e. remove the sqrt) to gain a little performance return Math.sqrt(dx*dx + dy*dy); } /** * This allows the zoom level of the network to influence the rendering * * @param scale */ Edge.prototype.setScale = function(scale) { this.networkScaleInv = 1.0/scale; }; Edge.prototype.select = function() { this.selected = true; }; Edge.prototype.unselect = function() { this.selected = false; }; Edge.prototype.positionBezierNode = function() { if (this.via !== null && this.from !== null && this.to !== null) { this.via.x = 0.5 * (this.from.x + this.to.x); this.via.y = 0.5 * (this.from.y + this.to.y); } }; /** * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true. * @param ctx */ Edge.prototype._drawControlNodes = function(ctx) { if (this.controlNodesEnabled == true) { if (this.controlNodes.from === null && this.controlNodes.to === null) { var nodeIdFrom = "edgeIdFrom:".concat(this.id); var nodeIdTo = "edgeIdTo:".concat(this.id); var constants = { nodes:{group:'', radius:8}, physics:{damping:0}, clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}} }; this.controlNodes.from = new Node( {id:nodeIdFrom, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); this.controlNodes.to = new Node( {id:nodeIdTo, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); } if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) { this.controlNodes.positions = this.getControlNodePositions(ctx); this.controlNodes.from.x = this.controlNodes.positions.from.x; this.controlNodes.from.y = this.controlNodes.positions.from.y; this.controlNodes.to.x = this.controlNodes.positions.to.x; this.controlNodes.to.y = this.controlNodes.positions.to.y; } this.controlNodes.from.draw(ctx); this.controlNodes.to.draw(ctx); } else { this.controlNodes = {from:null, to:null, positions:{}}; } }; /** * Enable control nodes. * @private */ Edge.prototype._enableControlNodes = function() { this.controlNodesEnabled = true; }; /** * disable control nodes * @private */ Edge.prototype._disableControlNodes = function() { this.controlNodesEnabled = false; }; /** * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null. * @param x * @param y * @returns {null} * @private */ Edge.prototype._getSelectedControlNode = function(x,y) { var positions = this.controlNodes.positions; var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2)); var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2)); if (fromDistance < 15) { this.connectedNode = this.from; this.from = this.controlNodes.from; return this.controlNodes.from; } else if (toDistance < 15) { this.connectedNode = this.to; this.to = this.controlNodes.to; return this.controlNodes.to; } else { return null; } }; /** * this resets the control nodes to their original position. * @private */ Edge.prototype._restoreControlNodes = function() { if (this.controlNodes.from.selected == true) { this.from = this.connectedNode; this.connectedNode = null; this.controlNodes.from.unselect(); } if (this.controlNodes.to.selected == true) { this.to = this.connectedNode; this.connectedNode = null; this.controlNodes.to.unselect(); } }; /** * this calculates the position of the control nodes on the edges of the parent nodes. * * @param ctx * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}} */ Edge.prototype.getControlNodePositions = function(ctx) { var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; var via; if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) { via = this.via; } else if (this.options.smoothCurves.enabled == true) { via = this._getViaCoordinates(); } if (this.options.smoothCurves.enabled == true && via.x != null) { angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x)); dx = (this.to.x - via.x); dy = (this.to.y - via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.options.smoothCurves.enabled == true && via.x != null) { xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}}; }; module.exports = Edge; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @class Groups * This class can store groups and properties specific for groups. */ function Groups() { this.clear(); this.defaultIndex = 0; } /** * default constants for group colors */ Groups.DEFAULT = [ {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint ]; /** * Clear all groups */ Groups.prototype.clear = function () { this.groups = {}; this.groups.length = function() { var i = 0; for ( var p in this ) { if (this.hasOwnProperty(p)) { i++; } } return i; } }; /** * get group properties of a groupname. If groupname is not found, a new group * is added. * @param {*} groupname Can be a number, string, Date, etc. * @return {Object} group The created group, containing all group properties */ Groups.prototype.get = function (groupname) { var group = this.groups[groupname]; if (group == undefined) { // create new group var index = this.defaultIndex % Groups.DEFAULT.length; this.defaultIndex++; group = {}; group.color = Groups.DEFAULT[index]; this.groups[groupname] = group; } return group; }; /** * Add a custom group style * @param {String} groupname * @param {Object} style An object containing borderColor, * backgroundColor, etc. * @return {Object} group The created group object */ Groups.prototype.add = function (groupname, style) { this.groups[groupname] = style; if (style.color) { style.color = util.parseColor(style.color); } return style; }; module.exports = Groups; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * @class Images * This class loads images and keeps them stored. */ function Images() { this.images = {}; this.callback = undefined; } /** * Set an onload callback function. This will be called each time an image * is loaded * @param {function} callback */ Images.prototype.setOnloadCallback = function(callback) { this.callback = callback; }; /** * * @param {string} url Url of the image * @param {string} url Url of an image to use if the url image is not found * @return {Image} img The image object */ Images.prototype.load = function(url, brokenUrl) { var img = this.images[url]; if (img == undefined) { // create the image var images = this; img = new Image(); this.images[url] = img; img.onload = function() { if (images.callback) { images.callback(this); } }; img.onerror = function () { this.src = brokenUrl; if (images.callback) { images.callback(this); } }; img.src = url; } return img; }; module.exports = Images; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @class Node * A node. A node can be connected to other nodes via one or multiple edges. * @param {object} properties An object containing properties for the node. All * properties are optional, except for the id. * {number} id Id of the node. Required * {string} label Text label for the node * {number} x Horizontal position of the node * {number} y Vertical position of the node * {string} shape Node shape, available: * "database", "circle", "ellipse", * "box", "image", "text", "dot", * "star", "triangle", "triangleDown", * "square" * {string} image An image url * {string} title An title text, can be HTML * {anytype} group A group name or number * @param {Network.Images} imagelist A list with images. Only needed * when the node has an image * @param {Network.Groups} grouplist A list with groups. Needed for * retrieving group properties * @param {Object} constants An object with default values for * example for the color * */ function Node(properties, imagelist, grouplist, networkConstants) { var constants = util.selectiveBridgeObject(['nodes'],networkConstants); this.options = constants.nodes; this.selected = false; this.hover = false; this.edges = []; // all edges connected to this node this.dynamicEdges = []; this.reroutedEdges = {}; this.fontDrawThreshold = 3; // set defaults for the properties this.id = undefined; this.x = null; this.y = null; this.allowedToMoveX = false; this.allowedToMoveY = false; this.xFixed = false; this.yFixed = false; this.horizontalAlignLeft = true; // these are for the navigation controls this.verticalAlignTop = true; // these are for the navigation controls this.baseRadiusValue = networkConstants.nodes.radius; this.radiusFixed = false; this.level = -1; this.preassignedLevel = false; this.hierarchyEnumerated = false; this.imagelist = imagelist; this.grouplist = grouplist; // physics properties this.fx = 0.0; // external force x this.fy = 0.0; // external force y this.vx = 0.0; // velocity x this.vy = 0.0; // velocity y this.damping = networkConstants.physics.damping; // written every time gravity is calculated this.fixedData = {x:null,y:null}; this.setProperties(properties, constants); // creating the variables for clustering this.resetCluster(); this.dynamicEdgesLength = 0; this.clusterSession = 0; this.clusterSizeWidthFactor = networkConstants.clustering.nodeScaling.width; this.clusterSizeHeightFactor = networkConstants.clustering.nodeScaling.height; this.clusterSizeRadiusFactor = networkConstants.clustering.nodeScaling.radius; this.maxNodeSizeIncrements = networkConstants.clustering.maxNodeSizeIncrements; this.growthIndicator = 0; // variables to tell the node about the network. this.networkScaleInv = 1; this.networkScale = 1; this.canvasTopLeft = {"x": -300, "y": -300}; this.canvasBottomRight = {"x": 300, "y": 300}; this.parentEdgeId = null; } /** * (re)setting the clustering variables and objects */ Node.prototype.resetCluster = function() { // clustering variables this.formationScale = undefined; // this is used to determine when to open the cluster this.clusterSize = 1; // this signifies the total amount of nodes in this cluster this.containedNodes = {}; this.containedEdges = {}; this.clusterSessions = []; }; /** * Attach a edge to the node * @param {Edge} edge */ Node.prototype.attachEdge = function(edge) { if (this.edges.indexOf(edge) == -1) { this.edges.push(edge); } if (this.dynamicEdges.indexOf(edge) == -1) { this.dynamicEdges.push(edge); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Detach a edge from the node * @param {Edge} edge */ Node.prototype.detachEdge = function(edge) { var index = this.edges.indexOf(edge); if (index != -1) { this.edges.splice(index, 1); } index = this.dynamicEdges.indexOf(edge); if (index != -1) { this.dynamicEdges.splice(index, 1); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Set or overwrite properties for the node * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Node.prototype.setProperties = function(properties, constants) { if (!properties) { return; } var fields = ['borderWidth','borderWidthSelected','shape','image','brokenImage','radius','fontColor', 'fontSize','fontFace','fontFill','group','mass' ]; util.selectiveDeepExtend(fields, this.options, properties); this.originalLabel = undefined; // basic properties if (properties.id !== undefined) {this.id = properties.id;} if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;} if (properties.title !== undefined) {this.title = properties.title;} if (properties.x !== undefined) {this.x = properties.x;} if (properties.y !== undefined) {this.y = properties.y;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;} // navigation controls properties if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;} if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;} if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;} if (this.id === undefined) { throw "Node must have an id"; } // copy group properties if (typeof this.options.group === 'number' || (typeof this.options.group === 'string' && this.options.group != '')) { var groupObj = this.grouplist.get(this.options.group); for (var prop in groupObj) { if (groupObj.hasOwnProperty(prop)) { this.options[prop] = groupObj[prop]; } } } // individual shape properties if (properties.radius !== undefined) {this.baseRadiusValue = this.options.radius;} if (properties.color !== undefined) {this.options.color = util.parseColor(properties.color);} if (this.options.image!== undefined && this.options.image!= "") { if (this.imagelist) { this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage); } else { throw "No imagelist provided"; } } if (properties.allowedToMoveX !== undefined) { this.xFixed = !properties.allowedToMoveX; this.allowedToMoveX = properties.allowedToMoveX; } else if (properties.x !== undefined && this.allowedToMoveX == false) { this.xFixed = true; } if (properties.allowedToMoveY !== undefined) { this.yFixed = !properties.allowedToMoveY; this.allowedToMoveY = properties.allowedToMoveY; } else if (properties.y !== undefined && this.allowedToMoveY == false) { this.yFixed = true; } this.radiusFixed = this.radiusFixed || (properties.radius !== undefined); if (this.options.shape == 'image') { this.options.radiusMin = constants.nodes.widthMin; this.options.radiusMax = constants.nodes.widthMax; } // choose draw method depending on the shape switch (this.options.shape) { case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break; case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break; case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break; case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; // TODO: add diamond shape case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break; case 'text': this.draw = this._drawText; this.resize = this._resizeText; break; case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break; case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break; case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break; case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break; case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break; default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; } // reset the size of the node, this can be changed this._reset(); }; /** * select this node */ Node.prototype.select = function() { this.selected = true; this._reset(); }; /** * unselect this node */ Node.prototype.unselect = function() { this.selected = false; this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size */ Node.prototype.clearSizeCache = function() { this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size * @private */ Node.prototype._reset = function() { this.width = undefined; this.height = undefined; }; /** * get the title of this node. * @return {string} title The title of the node, or undefined when no title * has been set. */ Node.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Calculate the distance to the border of the Node * @param {CanvasRenderingContext2D} ctx * @param {Number} angle Angle in radians * @returns {number} distance Distance to the border in pixels */ Node.prototype.distanceToBorder = function (ctx, angle) { var borderWidth = 1; if (!this.width) { this.resize(ctx); } switch (this.options.shape) { case 'circle': case 'dot': return this.options.radius+ borderWidth; case 'ellipse': var a = this.width / 2; var b = this.height / 2; var w = (Math.sin(angle) * a); var h = (Math.cos(angle) * b); return a * b / Math.sqrt(w * w + h * h); // TODO: implement distanceToBorder for database // TODO: implement distanceToBorder for triangle // TODO: implement distanceToBorder for triangleDown case 'box': case 'image': case 'text': default: if (this.width) { return Math.min( Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; // TODO: reckon with border radius too in case of box } else { return 0; } } // TODO: implement calculation of distance to border for all shapes }; /** * Set forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction */ Node.prototype._setForce = function(fx, fy) { this.fx = fx; this.fy = fy; }; /** * Add forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction * @private */ Node.prototype._addForce = function(fx, fy) { this.fx += fx; this.fy += fy; }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds */ Node.prototype.discreteStep = function(interval) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.options.mass; // acceleration this.vx += ax * interval; // velocity this.x += this.vx * interval; // position } else { this.fx = 0; this.vx = 0; } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.options.mass; // acceleration this.vy += ay * interval; // velocity this.y += this.vy * interval; // position } else { this.fy = 0; this.vy = 0; } }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds * @param {number} maxVelocity The speed limit imposed on the velocity */ Node.prototype.discreteStepLimited = function(interval, maxVelocity) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.options.mass; // acceleration this.vx += ax * interval; // velocity this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx; this.x += this.vx * interval; // position } else { this.fx = 0; this.vx = 0; } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.options.mass; // acceleration this.vy += ay * interval; // velocity this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy; this.y += this.vy * interval; // position } else { this.fy = 0; this.vy = 0; } }; /** * Check if this node has a fixed x and y position * @return {boolean} true if fixed, false if not */ Node.prototype.isFixed = function() { return (this.xFixed && this.yFixed); }; /** * Check if this node is moving * @param {number} vmin the minimum velocity considered as "moving" * @return {boolean} true if moving, false if it has no velocity */ Node.prototype.isMoving = function(vmin) { var velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2)); // this.velocity = Math.sqrt(Math.pow(this.vx,2) + Math.pow(this.vy,2)) return (velocity > vmin); }; /** * check if this node is selecte * @return {boolean} selected True if node is selected, else false */ Node.prototype.isSelected = function() { return this.selected; }; /** * Retrieve the value of the node. Can be undefined * @return {Number} value */ Node.prototype.getValue = function() { return this.value; }; /** * Calculate the distance from the nodes location to the given location (x,y) * @param {Number} x * @param {Number} y * @return {Number} value */ Node.prototype.getDistance = function(x, y) { var dx = this.x - x, dy = this.y - y; return Math.sqrt(dx * dx + dy * dy); }; /** * Adjust the value range of the node. The node will adjust it's radius * based on its value. * @param {Number} min * @param {Number} max */ Node.prototype.setValueRange = function(min, max) { if (!this.radiusFixed && this.value !== undefined) { if (max == min) { this.options.radius= (this.options.radiusMin + this.options.radiusMax) / 2; } else { var scale = (this.options.radiusMax - this.options.radiusMin) / (max - min); this.options.radius= (this.value - min) * scale + this.options.radiusMin; } } this.baseRadiusValue = this.options.radius; }; /** * Draw this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.draw = function(ctx) { throw "Draw method not initialized for node"; }; /** * Recalculate the size of this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.resize = function(ctx) { throw "Resize method not initialized for node"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top, right, bottom * @return {boolean} True if location is located on node */ Node.prototype.isOverlappingWith = function(obj) { return (this.left < obj.right && this.left + this.width > obj.left && this.top < obj.bottom && this.top + this.height > obj.top); }; Node.prototype._resizeImage = function (ctx) { // TODO: pre calculate the image size if (!this.width || !this.height) { // undefined or 0 var width, height; if (this.value) { this.options.radius= this.baseRadiusValue; var scale = this.imageObj.height / this.imageObj.width; if (scale !== undefined) { width = this.options.radius|| this.imageObj.width; height = this.options.radius* scale || this.imageObj.height; } else { width = 0; height = 0; } } else { width = this.imageObj.width; height = this.imageObj.height; } this.width = width; this.height = height; this.growthIndicator = 0; if (this.width > 0 && this.height > 0) { this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - width; } } }; Node.prototype._drawImage = function (ctx) { this._resizeImage(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var yLabel; if (this.imageObj.width != 0 ) { // draw the shade if (this.clusterSize > 1) { var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0); lineWidth *= this.networkScaleInv; lineWidth = Math.min(0.2 * this.width,lineWidth); ctx.globalAlpha = 0.5; ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth); } // draw the image ctx.globalAlpha = 1.0; ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); yLabel = this.y + this.height / 2; } else { // image still loading... just draw the label for now yLabel = this.y; } this._label(ctx, this.label, this.x, yLabel, undefined, "top"); }; Node.prototype._resizeBox = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); // this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; } }; Node.prototype._drawBox = function (ctx) { this._resizeBox(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.options.radius); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.options.color.background; ctx.roundRect(this.left, this.top, this.width, this.height, this.options.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeDatabase = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var size = textSize.width + 2 * margin; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawDatabase = function (ctx) { this._resizeDatabase(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeCircle = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; this.options.radius = diameter / 2; this.width = diameter; this.height = diameter; // scaling used for clustering // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.options.radius- 0.5*diameter; } }; Node.prototype._drawCircle = function (ctx) { this._resizeCircle(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.circle(this.x, this.y, this.options.radius+2*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx.circle(this.x, this.y, this.options.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeEllipse = function (ctx) { if (!this.width) { var textSize = this.getTextSize(ctx); this.width = textSize.width * 1.5; this.height = textSize.height * 2; if (this.width < this.height) { this.width = this.height; } var defaultSize = this.width; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - defaultSize; } }; Node.prototype._drawEllipse = function (ctx) { this._resizeEllipse(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx.ellipse(this.left, this.top, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._drawDot = function (ctx) { this._drawShape(ctx, 'circle'); }; Node.prototype._drawTriangle = function (ctx) { this._drawShape(ctx, 'triangle'); }; Node.prototype._drawTriangleDown = function (ctx) { this._drawShape(ctx, 'triangleDown'); }; Node.prototype._drawSquare = function (ctx) { this._drawShape(ctx, 'square'); }; Node.prototype._drawStar = function (ctx) { this._drawShape(ctx, 'star'); }; Node.prototype._resizeShape = function (ctx) { if (!this.width) { this.options.radius= this.baseRadiusValue; var size = 2 * this.options.radius; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawShape = function (ctx, shape) { this._resizeShape(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.options.borderWidth; var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth; var radiusMultiplier = 2; // choose draw method depending on the shape switch (shape) { case 'dot': radiusMultiplier = 2; break; case 'square': radiusMultiplier = 2; break; case 'triangle': radiusMultiplier = 3; break; case 'triangleDown': radiusMultiplier = 3; break; case 'star': radiusMultiplier = 4; break; } ctx.strokeStyle = this.selected ? this.options.color.highlight.border : this.hover ? this.options.color.hover.border : this.options.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx[shape](this.x, this.y, this.options.radius+ radiusMultiplier * ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.options.color.highlight.background : this.hover ? this.options.color.hover.background : this.options.color.background; ctx[shape](this.x, this.y, this.options.radius); ctx.fill(); ctx.stroke(); if (this.label) { this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true); } }; Node.prototype._resizeText = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.options.radius+= Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); } }; Node.prototype._drawText = function (ctx) { this._resizeText(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; this._label(ctx, this.label, this.x, this.y); }; Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) { if (text && Number(this.options.fontSize) * this.networkScale > this.fontDrawThreshold) { ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace; ctx.textAlign = align || "center"; ctx.textBaseline = baseline || "middle"; var lines = text.split('\n'); var lineCount = lines.length; var fontSize = (Number(this.options.fontSize) + 4); var yLine = y + (1 - lineCount) / 2 * fontSize; if (labelUnderNode == true) { yLine = y + (1 - lineCount) / (2 * fontSize); } // font fill from edges now for nodes! if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") { var width = ctx.measureText(lines[0]).width; for (var i = 1; i < lineCount; i++) { var lineWidth = ctx.measureText(lines[i]).width; width = lineWidth > width ? lineWidth : width; } var height = this.options.fontSize * lineCount; var left = x - width / 2; var top = y - height / 2; if (ctx.textBaseline == "top") { top += 0.5 * fontSize; } ctx.fillStyle = this.options.fontFill; ctx.fillRect(left, top, width, height); } // draw text ctx.fillStyle = this.options.fontColor || "black"; for (var i = 0; i < lineCount; i++) { ctx.fillText(lines[i], x, yLine); yLine += fontSize; } } }; Node.prototype.getTextSize = function(ctx) { if (this.label !== undefined) { ctx.font = (this.selected ? "bold " : "") + this.options.fontSize + "px " + this.options.fontFace; var lines = this.label.split('\n'), height = (Number(this.options.fontSize) + 4) * lines.length, width = 0; for (var i = 0, iMax = lines.length; i < iMax; i++) { width = Math.max(width, ctx.measureText(lines[i]).width); } return {"width": width, "height": height}; } else { return {"width": 0, "height": 0}; } }; /** * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn. * there is a safety margin of 0.3 * width; * * @returns {boolean} */ Node.prototype.inArea = function() { if (this.width !== undefined) { return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x && this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x && this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y && this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y); } else { return true; } }; /** * checks if the core of the node is in the display area, this is used for opening clusters around zoom * @returns {boolean} */ Node.prototype.inView = function() { return (this.x >= this.canvasTopLeft.x && this.x < this.canvasBottomRight.x && this.y >= this.canvasTopLeft.y && this.y < this.canvasBottomRight.y); }; /** * This allows the zoom level of the network to influence the rendering * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas * * @param scale * @param canvasTopLeft * @param canvasBottomRight */ Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) { this.networkScaleInv = 1.0/scale; this.networkScale = scale; this.canvasTopLeft = canvasTopLeft; this.canvasBottomRight = canvasBottomRight; }; /** * This allows the zoom level of the network to influence the rendering * * @param scale */ Node.prototype.setScale = function(scale) { this.networkScaleInv = 1.0/scale; this.networkScale = scale; }; /** * set the velocity at 0. Is called when this node is contained in another during clustering */ Node.prototype.clearVelocity = function() { this.vx = 0; this.vy = 0; }; /** * Basic preservation of (kinectic) energy * * @param massBeforeClustering */ Node.prototype.updateVelocity = function(massBeforeClustering) { var energyBefore = this.vx * this.vx * massBeforeClustering; //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass); this.vx = Math.sqrt(energyBefore/this.options.mass); energyBefore = this.vy * this.vy * massBeforeClustering; //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.options.mass) : Math.sqrt(energyBefore/this.options.mass); this.vy = Math.sqrt(energyBefore/this.options.mass); }; module.exports = Node; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Popup is a class to create a popup window with some text * @param {Element} container The container object. * @param {Number} [x] * @param {Number} [y] * @param {String} [text] * @param {Object} [style] An object containing borderColor, * backgroundColor, etc. */ function Popup(container, x, y, text, style) { if (container) { this.container = container; } else { this.container = document.body; } // x, y and text are optional, see if a style object was passed in their place if (style === undefined) { if (typeof x === "object") { style = x; x = undefined; } else if (typeof text === "object") { style = text; text = undefined; } else { // for backwards compatibility, in case clients other than Network are creating Popup directly style = { fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } } } } this.x = 0; this.y = 0; this.padding = 5; if (x !== undefined && y !== undefined ) { this.setPosition(x, y); } if (text !== undefined) { this.setText(text); } // create the frame this.frame = document.createElement("div"); var styleAttr = this.frame.style; styleAttr.position = "absolute"; styleAttr.visibility = "hidden"; styleAttr.border = "1px solid " + style.color.border; styleAttr.color = style.fontColor; styleAttr.fontSize = style.fontSize + "px"; styleAttr.fontFamily = style.fontFace; styleAttr.padding = this.padding + "px"; styleAttr.backgroundColor = style.color.background; styleAttr.borderRadius = "3px"; styleAttr.MozBorderRadius = "3px"; styleAttr.WebkitBorderRadius = "3px"; styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)"; styleAttr.whiteSpace = "nowrap"; this.container.appendChild(this.frame); } /** * @param {number} x Horizontal position of the popup window * @param {number} y Vertical position of the popup window */ Popup.prototype.setPosition = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); }; /** * Set the text for the popup window. This can be HTML code * @param {string} text */ Popup.prototype.setText = function(text) { this.frame.innerHTML = text; }; /** * Show the popup window * @param {boolean} show Optional. Show or hide the window */ Popup.prototype.show = function (show) { if (show === undefined) { show = true; } if (show) { var height = this.frame.clientHeight; var width = this.frame.clientWidth; var maxHeight = this.frame.parentNode.clientHeight; var maxWidth = this.frame.parentNode.clientWidth; var top = (this.y - height); if (top + height + this.padding > maxHeight) { top = maxHeight - height - this.padding; } if (top < this.padding) { top = this.padding; } var left = this.x; if (left + width + this.padding > maxWidth) { left = maxWidth - width - this.padding; } if (left < this.padding) { left = this.padding; } this.frame.style.left = left + "px"; this.frame.style.top = top + "px"; this.frame.style.visibility = "visible"; } else { this.hide(); } }; /** * Hide the popup window */ Popup.prototype.hide = function () { this.frame.style.visibility = "hidden"; }; module.exports = Popup; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /** * Parse a text source containing data in DOT language into a JSON object. * The object contains two lists: one with nodes and one with edges. * * DOT language reference: http://www.graphviz.org/doc/info/lang.html * * @param {String} data Text containing a graph in DOT-notation * @return {Object} graph An object containing two parameters: * {Object[]} nodes * {Object[]} edges */ function parseDOT (data) { dot = data; return parseGraph(); } // token types enumeration var TOKENTYPE = { NULL : 0, DELIMITER : 1, IDENTIFIER: 2, UNKNOWN : 3 }; // map with all delimiters var DELIMITERS = { '{': true, '}': true, '[': true, ']': true, ';': true, '=': true, ',': true, '->': true, '--': true }; var dot = ''; // current dot file var index = 0; // current index in dot file var c = ''; // current token character in expr var token = ''; // current token var tokenType = TOKENTYPE.NULL; // type of the token /** * Get the first character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function first() { index = 0; c = dot.charAt(0); } /** * Get the next character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function next() { index++; c = dot.charAt(index); } /** * Preview the next character from the dot file. * @return {String} cNext */ function nextPreview() { return dot.charAt(index + 1); } /** * Test whether given character is alphabetic or numeric * @param {String} c * @return {Boolean} isAlphaNumeric */ var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; function isAlphaNumeric(c) { return regexAlphaNumeric.test(c); } /** * Merge all properties of object b into object b * @param {Object} a * @param {Object} b * @return {Object} a */ function merge (a, b) { if (!a) { a = {}; } if (b) { for (var name in b) { if (b.hasOwnProperty(name)) { a[name] = b[name]; } } } return a; } /** * Set a value in an object, where the provided parameter name can be a * path with nested parameters. For example: * * var obj = {a: 2}; * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} * * @param {Object} obj * @param {String} path A parameter name or dot-separated parameter path, * like "color.highlight.border". * @param {*} value */ function setValue(obj, path, value) { var keys = path.split('.'); var o = obj; while (keys.length) { var key = keys.shift(); if (keys.length) { // this isn't the end point if (!o[key]) { o[key] = {}; } o = o[key]; } else { // this is the end point o[key] = value; } } } /** * Add a node to a graph object. If there is already a node with * the same id, their attributes will be merged. * @param {Object} graph * @param {Object} node */ function addNode(graph, node) { var i, len; var current = null; // find root graph (in case of subgraph) var graphs = [graph]; // list with all graphs from current graph to root graph var root = graph; while (root.parent) { graphs.push(root.parent); root = root.parent; } // find existing node (at root level) by its id if (root.nodes) { for (i = 0, len = root.nodes.length; i < len; i++) { if (node.id === root.nodes[i].id) { current = root.nodes[i]; break; } } } if (!current) { // this is a new node current = { id: node.id }; if (graph.node) { // clone default attributes current.attr = merge(current.attr, graph.node); } } // add node to this (sub)graph and all its parent graphs for (i = graphs.length - 1; i >= 0; i--) { var g = graphs[i]; if (!g.nodes) { g.nodes = []; } if (g.nodes.indexOf(current) == -1) { g.nodes.push(current); } } // merge attributes if (node.attr) { current.attr = merge(current.attr, node.attr); } } /** * Add an edge to a graph object * @param {Object} graph * @param {Object} edge */ function addEdge(graph, edge) { if (!graph.edges) { graph.edges = []; } graph.edges.push(edge); if (graph.edge) { var attr = merge({}, graph.edge); // clone default attributes edge.attr = merge(attr, edge.attr); // merge attributes } } /** * Create an edge to a graph object * @param {Object} graph * @param {String | Number | Object} from * @param {String | Number | Object} to * @param {String} type * @param {Object | null} attr * @return {Object} edge */ function createEdge(graph, from, to, type, attr) { var edge = { from: from, to: to, type: type }; if (graph.edge) { edge.attr = merge({}, graph.edge); // clone default attributes } edge.attr = merge(edge.attr || {}, attr); // merge attributes return edge; } /** * Get next token in the current dot file. * The token and token type are available as token and tokenType */ function getToken() { tokenType = TOKENTYPE.NULL; token = ''; // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } do { var isComment = false; // skip comment if (c == '#') { // find the previous non-space character var i = index - 1; while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') { i--; } if (dot.charAt(i) == '\n' || dot.charAt(i) == '') { // the # is at the start of a line, this is indeed a line comment while (c != '' && c != '\n') { next(); } isComment = true; } } if (c == '/' && nextPreview() == '/') { // skip line comment while (c != '' && c != '\n') { next(); } isComment = true; } if (c == '/' && nextPreview() == '*') { // skip block comment while (c != '') { if (c == '*' && nextPreview() == '/') { // end of block comment found. skip these last two characters next(); next(); break; } else { next(); } } isComment = true; } // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } } while (isComment); // check for end of dot file if (c == '') { // token is still empty tokenType = TOKENTYPE.DELIMITER; return; } // check for delimiters consisting of 2 characters var c2 = c + nextPreview(); if (DELIMITERS[c2]) { tokenType = TOKENTYPE.DELIMITER; token = c2; next(); next(); return; } // check for delimiters consisting of 1 character if (DELIMITERS[c]) { tokenType = TOKENTYPE.DELIMITER; token = c; next(); return; } // check for an identifier (number or string) // TODO: more precise parsing of numbers/strings (and the port separator ':') if (isAlphaNumeric(c) || c == '-') { token += c; next(); while (isAlphaNumeric(c)) { token += c; next(); } if (token == 'false') { token = false; // convert to boolean } else if (token == 'true') { token = true; // convert to boolean } else if (!isNaN(Number(token))) { token = Number(token); // convert to number } tokenType = TOKENTYPE.IDENTIFIER; return; } // check for a string enclosed by double quotes if (c == '"') { next(); while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) { token += c; if (c == '"') { // skip the escape character next(); } next(); } if (c != '"') { throw newSyntaxError('End of string " expected'); } next(); tokenType = TOKENTYPE.IDENTIFIER; return; } // something unknown is found, wrong characters, a syntax error tokenType = TOKENTYPE.UNKNOWN; while (c != '') { token += c; next(); } throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); } /** * Parse a graph. * @returns {Object} graph */ function parseGraph() { var graph = {}; first(); getToken(); // optional strict keyword if (token == 'strict') { graph.strict = true; getToken(); } // graph or digraph keyword if (token == 'graph' || token == 'digraph') { graph.type = token; getToken(); } // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { graph.id = token; getToken(); } // open angle bracket if (token != '{') { throw newSyntaxError('Angle bracket { expected'); } getToken(); // statements parseStatements(graph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // end of file if (token !== '') { throw newSyntaxError('End of file expected'); } getToken(); // remove temporary default properties delete graph.node; delete graph.edge; delete graph.graph; return graph; } /** * Parse a list with statements. * @param {Object} graph */ function parseStatements (graph) { while (token !== '' && token != '}') { parseStatement(graph); if (token == ';') { getToken(); } } } /** * Parse a single statement. Can be a an attribute statement, node * statement, a series of node statements and edge statements, or a * parameter. * @param {Object} graph */ function parseStatement(graph) { // parse subgraph var subgraph = parseSubgraph(graph); if (subgraph) { // edge statements parseEdge(graph, subgraph); return; } // parse an attribute statement var attr = parseAttributeStatement(graph); if (attr) { return; } // parse node if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } var id = token; // id can be a string or a number getToken(); if (token == '=') { // id statement getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } graph[id] = token; getToken(); // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " } else { parseNodeStatement(graph, id); } } /** * Parse a subgraph * @param {Object} graph parent graph object * @return {Object | null} subgraph */ function parseSubgraph (graph) { var subgraph = null; // optional subgraph keyword if (token == 'subgraph') { subgraph = {}; subgraph.type = 'subgraph'; getToken(); // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { subgraph.id = token; getToken(); } } // open angle bracket if (token == '{') { getToken(); if (!subgraph) { subgraph = {}; } subgraph.parent = graph; subgraph.node = graph.node; subgraph.edge = graph.edge; subgraph.graph = graph.graph; // statements parseStatements(subgraph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // remove temporary default properties delete subgraph.node; delete subgraph.edge; delete subgraph.graph; delete subgraph.parent; // register at the parent graph if (!graph.subgraphs) { graph.subgraphs = []; } graph.subgraphs.push(subgraph); } return subgraph; } /** * parse an attribute statement like "node [shape=circle fontSize=16]". * Available keywords are 'node', 'edge', 'graph'. * The previous list with default attributes will be replaced * @param {Object} graph * @returns {String | null} keyword Returns the name of the parsed attribute * (node, edge, graph), or null if nothing * is parsed. */ function parseAttributeStatement (graph) { // attribute statements if (token == 'node') { getToken(); // node attributes graph.node = parseAttributeList(); return 'node'; } else if (token == 'edge') { getToken(); // edge attributes graph.edge = parseAttributeList(); return 'edge'; } else if (token == 'graph') { getToken(); // graph attributes graph.graph = parseAttributeList(); return 'graph'; } return null; } /** * parse a node statement * @param {Object} graph * @param {String | Number} id */ function parseNodeStatement(graph, id) { // node statement var node = { id: id }; var attr = parseAttributeList(); if (attr) { node.attr = attr; } addNode(graph, node); // edge statements parseEdge(graph, id); } /** * Parse an edge or a series of edges * @param {Object} graph * @param {String | Number} from Id of the from node */ function parseEdge(graph, from) { while (token == '->' || token == '--') { var to; var type = token; getToken(); var subgraph = parseSubgraph(graph); if (subgraph) { to = subgraph; } else { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier or subgraph expected'); } to = token; addNode(graph, { id: to }); getToken(); } // parse edge attributes var attr = parseAttributeList(); // create edge var edge = createEdge(graph, from, to, type, attr); addEdge(graph, edge); from = to; } } /** * Parse a set with attributes, * for example [label="1.000", shape=solid] * @return {Object | null} attr */ function parseAttributeList() { var attr = null; while (token == '[') { getToken(); attr = {}; while (token !== '' && token != ']') { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute name expected'); } var name = token; getToken(); if (token != '=') { throw newSyntaxError('Equal sign = expected'); } getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute value expected'); } var value = token; setValue(attr, name, value); // name can be a path getToken(); if (token ==',') { getToken(); } } if (token != ']') { throw newSyntaxError('Bracket ] expected'); } getToken(); } return attr; } /** * Create a syntax error with extra information on current token and index. * @param {String} message * @returns {SyntaxError} err */ function newSyntaxError(message) { return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); } /** * Chop off text after a maximum length * @param {String} text * @param {Number} maxLength * @returns {String} */ function chop (text, maxLength) { return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...'); } /** * Execute a function fn for each pair of elements in two arrays * @param {Array | *} array1 * @param {Array | *} array2 * @param {function} fn */ function forEach2(array1, array2, fn) { if (array1 instanceof Array) { array1.forEach(function (elem1) { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(elem1, elem2); }); } else { fn(elem1, array2); } }); } else { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(array1, elem2); }); } else { fn(array1, array2); } } } /** * Convert a string containing a graph in DOT language into a map containing * with nodes and edges in the format of graph. * @param {String} data Text containing a graph in DOT-notation * @return {Object} graphData */ function DOTToGraph (data) { // parse the DOT file var dotData = parseDOT(data); var graphData = { nodes: [], edges: [], options: {} }; // copy the nodes if (dotData.nodes) { dotData.nodes.forEach(function (dotNode) { var graphNode = { id: dotNode.id, label: String(dotNode.label || dotNode.id) }; merge(graphNode, dotNode.attr); if (graphNode.image) { graphNode.shape = 'image'; } graphData.nodes.push(graphNode); }); } // copy the edges if (dotData.edges) { /** * Convert an edge in DOT format to an edge with VisGraph format * @param {Object} dotEdge * @returns {Object} graphEdge */ function convertEdge(dotEdge) { var graphEdge = { from: dotEdge.from, to: dotEdge.to }; merge(graphEdge, dotEdge.attr); graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line'; return graphEdge; } dotData.edges.forEach(function (dotEdge) { var from, to; if (dotEdge.from instanceof Object) { from = dotEdge.from.nodes; } else { from = { id: dotEdge.from } } if (dotEdge.to instanceof Object) { to = dotEdge.to.nodes; } else { to = { id: dotEdge.to } } if (dotEdge.from instanceof Object && dotEdge.from.edges) { dotEdge.from.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } forEach2(from, to, function (from, to) { var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); if (dotEdge.to instanceof Object && dotEdge.to.edges) { dotEdge.to.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } }); } // copy the options if (dotData.attr) { graphData.options = dotData.attr; } return graphData; } // exports exports.parseDOT = parseDOT; exports.DOTToGraph = DOTToGraph; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { function parseGephi(gephiJSON, options) { var edges = []; var nodes = []; this.options = { edges: { inheritColor: true }, nodes: { allowedToMove: false, parseColor: false } }; if (options !== undefined) { this.options.nodes['allowedToMove'] = options.allowedToMove | false; this.options.nodes['parseColor'] = options.parseColor | false; this.options.edges['inheritColor'] = options.inheritColor | true; } var gEdges = gephiJSON.edges; var gNodes = gephiJSON.nodes; for (var i = 0; i < gEdges.length; i++) { var edge = {}; var gEdge = gEdges[i]; edge['id'] = gEdge.id; edge['from'] = gEdge.source; edge['to'] = gEdge.target; edge['attributes'] = gEdge.attributes; // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; edge['color'] = gEdge.color; edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor; edges.push(edge); } for (var i = 0; i < gNodes.length; i++) { var node = {}; var gNode = gNodes[i]; node['id'] = gNode.id; node['attributes'] = gNode.attributes; node['x'] = gNode.x; node['y'] = gNode.y; node['label'] = gNode.label; if (this.options.nodes.parseColor == true) { node['color'] = gNode.color; } else { node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined; } node['radius'] = gNode.size; node['allowedToMoveX'] = this.options.nodes.allowedToMove; node['allowedToMoveY'] = this.options.nodes.allowedToMove; nodes.push(node); } return {nodes:nodes, edges:edges}; } exports.parseGephi = parseGephi; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // first check if moment.js is already loaded in the browser window, if so, // use this instance. Else, load via commonjs. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(52); /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { // Only load hammer.js when in a browser environment // (loading hammer.js in a node.js environment gives errors) if (typeof window !== 'undefined') { module.exports = window['Hammer'] || __webpack_require__(53); } else { module.exports = function () { throw Error('hammer.js is only available in a browser, not in node.js.'); } } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(42); /** * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent * @param {Element} element * @param {Event} event */ exports.fakeGesture = function(element, event) { var eventType = null; // for hammer.js 1.0.5 // var gesture = Hammer.event.collectEventData(this, eventType, event); // for hammer.js 1.0.6+ var touches = Hammer.event.getTouchList(event, eventType); var gesture = Hammer.event.collectEventData(this, eventType, touches, event); // on IE in standards mode, no touches are recognized by hammer.js, // resulting in NaN values for center.pageX and center.pageY if (isNaN(gesture.center.pageX)) { gesture.center.pageX = event.pageX; } if (isNaN(gesture.center.pageY)) { gesture.center.pageY = event.pageY; } return gesture; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(50); var Hammer = __webpack_require__(42); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var ItemSet = __webpack_require__(24); var Activator = __webpack_require__(49); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Core.setOptions for the available options. * @constructor */ function Core () {} // turn Core into an event emitter Emitter(Core.prototype); /** * Create the main DOM for the Core: a root panel containing left, right, * top, bottom, content, and background panel. * @param {Element} container The container element where the Core will * be attached. * @private */ Core.prototype._create = function (container) { this.dom = {}; this.dom.root = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.backgroundVertical = document.createElement('div'); this.dom.backgroundHorizontal = document.createElement('div'); this.dom.centerContainer = document.createElement('div'); this.dom.leftContainer = document.createElement('div'); this.dom.rightContainer = document.createElement('div'); this.dom.center = document.createElement('div'); this.dom.left = document.createElement('div'); this.dom.right = document.createElement('div'); this.dom.top = document.createElement('div'); this.dom.bottom = document.createElement('div'); this.dom.shadowTop = document.createElement('div'); this.dom.shadowBottom = document.createElement('div'); this.dom.shadowTopLeft = document.createElement('div'); this.dom.shadowBottomLeft = document.createElement('div'); this.dom.shadowTopRight = document.createElement('div'); this.dom.shadowBottomRight = document.createElement('div'); this.dom.root.className = 'vis timeline root'; this.dom.background.className = 'vispanel background'; this.dom.backgroundVertical.className = 'vispanel background vertical'; this.dom.backgroundHorizontal.className = 'vispanel background horizontal'; this.dom.centerContainer.className = 'vispanel center'; this.dom.leftContainer.className = 'vispanel left'; this.dom.rightContainer.className = 'vispanel right'; this.dom.top.className = 'vispanel top'; this.dom.bottom.className = 'vispanel bottom'; this.dom.left.className = 'content'; this.dom.center.className = 'content'; this.dom.right.className = 'content'; this.dom.shadowTop.className = 'shadow top'; this.dom.shadowBottom.className = 'shadow bottom'; this.dom.shadowTopLeft.className = 'shadow top'; this.dom.shadowBottomLeft.className = 'shadow bottom'; this.dom.shadowTopRight.className = 'shadow top'; this.dom.shadowBottomRight.className = 'shadow bottom'; this.dom.root.appendChild(this.dom.background); this.dom.root.appendChild(this.dom.backgroundVertical); this.dom.root.appendChild(this.dom.backgroundHorizontal); this.dom.root.appendChild(this.dom.centerContainer); this.dom.root.appendChild(this.dom.leftContainer); this.dom.root.appendChild(this.dom.rightContainer); this.dom.root.appendChild(this.dom.top); this.dom.root.appendChild(this.dom.bottom); this.dom.centerContainer.appendChild(this.dom.center); this.dom.leftContainer.appendChild(this.dom.left); this.dom.rightContainer.appendChild(this.dom.right); this.dom.centerContainer.appendChild(this.dom.shadowTop); this.dom.centerContainer.appendChild(this.dom.shadowBottom); this.dom.leftContainer.appendChild(this.dom.shadowTopLeft); this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft); this.dom.rightContainer.appendChild(this.dom.shadowTopRight); this.dom.rightContainer.appendChild(this.dom.shadowBottomRight); this.on('rangechange', this.redraw.bind(this)); this.on('change', this.redraw.bind(this)); this.on('touch', this._onTouch.bind(this)); this.on('pinch', this._onPinch.bind(this)); this.on('dragstart', this._onDragStart.bind(this)); this.on('drag', this._onDrag.bind(this)); // create event listeners for all interesting events, these events will be // emitted via emitter this.hammer = Hammer(this.dom.root, { preventDefault: true }); this.listeners = {}; var me = this; var events = [ 'touch', 'pinch', 'tap', 'doubletap', 'hold', 'dragstart', 'drag', 'dragend', 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox ]; events.forEach(function (event) { var listener = function () { var args = [event].concat(Array.prototype.slice.call(arguments, 0)); if (me.isActive()) { me.emit.apply(me, args); } }; me.hammer.on(event, listener); me.listeners[event] = listener; }); // size properties of each of the panels this.props = { root: {}, background: {}, centerContainer: {}, leftContainer: {}, rightContainer: {}, center: {}, left: {}, right: {}, top: {}, bottom: {}, border: {}, scrollTop: 0, scrollTopMin: 0 }; this.touch = {}; // store state information needed for touch events // attach the root panel to the provided container if (!container) throw new Error('No container provided'); container.appendChild(this.dom.root); }; /** * Set options. Options will be passed to all components loaded in the Timeline. * @param {Object} [options] * {String} orientation * Vertical orientation for the Timeline, * can be 'bottom' (default) or 'top'. * {String | Number} width * Width for the timeline, a number in pixels or * a css string like '1000px' or '75%'. '100%' by default. * {String | Number} height * Fixed height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. If undefined, * The Timeline will automatically size such that * its contents fit. * {String | Number} minHeight * Minimum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {String | Number} maxHeight * Maximum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {Number | Date | String} start * Start date for the visible window * {Number | Date | String} end * End date for the visible window */ Core.prototype.setOptions = function (options) { if (options) { // copy the known options var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation', 'clickToUse', 'dataAttributes']; util.selectiveExtend(fields, this.options, options); if ('clickToUse' in options) { if (options.clickToUse) { this.activator = new Activator(this.dom.root); } else { if (this.activator) { this.activator.destroy(); delete this.activator; } } } // enable/disable autoResize this._initAutoResize(); } // propagate options to all components this.components.forEach(function (component) { component.setOptions(options); }); // TODO: remove deprecation error one day (deprecated since version 0.8.0) if (options && options.order) { throw new Error('Option order is deprecated. There is no replacement for this feature.'); } // redraw everything this.redraw(); }; /** * Returns true when the Timeline is active. * @returns {boolean} */ Core.prototype.isActive = function () { return !this.activator || this.activator.active; }; /** * Destroy the Core, clean up all DOM elements and event listeners. */ Core.prototype.destroy = function () { // unbind datasets this.clear(); // remove all event listeners this.off(); // stop checking for changed size this._stopAutoResize(); // remove from DOM if (this.dom.root.parentNode) { this.dom.root.parentNode.removeChild(this.dom.root); } this.dom = null; // remove Activator if (this.activator) { this.activator.destroy(); delete this.activator; } // cleanup hammer touch events for (var event in this.listeners) { if (this.listeners.hasOwnProperty(event)) { delete this.listeners[event]; } } this.listeners = null; this.hammer = null; // give all components the opportunity to cleanup this.components.forEach(function (component) { component.destroy(); }); this.body = null; }; /** * Set a custom time bar * @param {Date} time */ Core.prototype.setCustomTime = function (time) { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } this.customTime.setCustomTime(time); }; /** * Retrieve the current custom time. * @return {Date} customTime */ Core.prototype.getCustomTime = function() { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } return this.customTime.getCustomTime(); }; /** * Get the id's of the currently visible items. * @returns {Array} The ids of the visible items */ Core.prototype.getVisibleItems = function() { return this.itemSet && this.itemSet.getVisibleItems() || []; }; /** * Clear the Core. By Default, items, groups and options are cleared. * Example usage: * * timeline.clear(); // clear items, groups, and options * timeline.clear({options: true}); // clear options only * * @param {Object} [what] Optionally specify what to clear. By default: * {items: true, groups: true, options: true} */ Core.prototype.clear = function(what) { // clear items if (!what || what.items) { this.setItems(null); } // clear groups if (!what || what.groups) { this.setGroups(null); } // clear options of timeline and of each of the components if (!what || what.options) { this.components.forEach(function (component) { component.setOptions(component.defaultOptions); }); this.setOptions(this.defaultOptions); // this will also do a redraw } }; /** * Set Core window such that it fits all items * @param {Object} [options] Available options: * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. */ Core.prototype.fit = function(options) { // apply the data range as range var dataRange = this.getItemRange(); // add 5% space on both sides var start = dataRange.min; var end = dataRange.max; if (start != null && end != null) { var interval = (end.valueOf() - start.valueOf()); if (interval <= 0) { // prevent an empty interval interval = 24 * 60 * 60 * 1000; // 1 day } start = new Date(start.valueOf() - interval * 0.05); end = new Date(end.valueOf() + interval * 0.05); } // skip range set if there is no start and end date if (start === null && end === null) { return; } var animate = (options && options.animate !== undefined) ? options.animate : true; this.range.setRange(start, end, animate); }; /** * Set the visible window. Both parameters are optional, you can change only * start or only end. Syntax: * * TimeLine.setWindow(start, end) * TimeLine.setWindow(range) * * Where start and end can be a Date, number, or string, and range is an * object with properties start and end. * * @param {Date | Number | String | Object} [start] Start date of visible window * @param {Date | Number | String} [end] End date of visible window * @param {Object} [options] Available options: * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. */ Core.prototype.setWindow = function(start, end, options) { var animate = (options && options.animate !== undefined) ? options.animate : true; if (arguments.length == 1) { var range = arguments[0]; this.range.setRange(range.start, range.end, animate); } else { this.range.setRange(start, end, animate); } }; /** * Move the window such that given time is centered on screen. * @param {Date | Number | String} time * @param {Object} [options] Available options: * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. */ Core.prototype.moveTo = function(time, options) { var interval = this.range.end - this.range.start; var t = util.convert(time, 'Date').valueOf(); var start = t - interval / 2; var end = t + interval / 2; var animate = (options && options.animate !== undefined) ? options.animate : true; this.range.setRange(start, end, animate); }; /** * Get the visible window * @return {{start: Date, end: Date}} Visible range */ Core.prototype.getWindow = function() { var range = this.range.getRange(); return { start: new Date(range.start), end: new Date(range.end) }; }; /** * Force a redraw of the Core. Can be useful to manually redraw when * option autoResize=false */ Core.prototype.redraw = function() { var resized = false, options = this.options, props = this.props, dom = this.dom; if (!dom) return; // when destroyed // update class names if (options.orientation == 'top') { util.addClassName(dom.root, 'top'); util.removeClassName(dom.root, 'bottom'); } else { util.removeClassName(dom.root, 'top'); util.addClassName(dom.root, 'bottom'); } // update root width and height options dom.root.style.maxHeight = util.option.asSize(options.maxHeight, ''); dom.root.style.minHeight = util.option.asSize(options.minHeight, ''); dom.root.style.width = util.option.asSize(options.width, ''); // calculate border widths props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2; props.border.right = props.border.left; props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2; props.border.bottom = props.border.top; var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight; var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; // workaround for a bug in IE: the clientWidth of an element with // a height:0px and overflow:hidden is not calculated and always has value 0 if (dom.centerContainer.clientHeight === 0) { props.border.left = props.border.top; props.border.right = props.border.left; } if (dom.root.clientHeight === 0) { borderRootWidth = borderRootHeight; } // calculate the heights. If any of the side panels is empty, we set the height to // minus the border width, such that the border will be invisible props.center.height = dom.center.offsetHeight; props.left.height = dom.left.offsetHeight; props.right.height = dom.right.offsetHeight; props.top.height = dom.top.clientHeight || -props.border.top; props.bottom.height = dom.bottom.clientHeight || -props.border.bottom; // TODO: compensate borders when any of the panels is empty. // apply auto height // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM) var contentHeight = Math.max(props.left.height, props.center.height, props.right.height); var autoHeight = props.top.height + contentHeight + props.bottom.height + borderRootHeight + props.border.top + props.border.bottom; dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); // calculate heights of the content panels props.root.height = dom.root.offsetHeight; props.background.height = props.root.height - borderRootHeight; var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; props.centerContainer.height = containerHeight; props.leftContainer.height = containerHeight; props.rightContainer.height = props.leftContainer.height; // calculate the widths of the panels props.root.width = dom.root.offsetWidth; props.background.width = props.root.width - borderRootWidth; props.left.width = dom.leftContainer.clientWidth || -props.border.left; props.leftContainer.width = props.left.width; props.right.width = dom.rightContainer.clientWidth || -props.border.right; props.rightContainer.width = props.right.width; var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; props.center.width = centerWidth; props.centerContainer.width = centerWidth; props.top.width = centerWidth; props.bottom.width = centerWidth; // resize the panels dom.background.style.height = props.background.height + 'px'; dom.backgroundVertical.style.height = props.background.height + 'px'; dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px'; dom.centerContainer.style.height = props.centerContainer.height + 'px'; dom.leftContainer.style.height = props.leftContainer.height + 'px'; dom.rightContainer.style.height = props.rightContainer.height + 'px'; dom.background.style.width = props.background.width + 'px'; dom.backgroundVertical.style.width = props.centerContainer.width + 'px'; dom.backgroundHorizontal.style.width = props.background.width + 'px'; dom.centerContainer.style.width = props.center.width + 'px'; dom.top.style.width = props.top.width + 'px'; dom.bottom.style.width = props.bottom.width + 'px'; // reposition the panels dom.background.style.left = '0'; dom.background.style.top = '0'; dom.backgroundVertical.style.left = (props.left.width + props.border.left) + 'px'; dom.backgroundVertical.style.top = '0'; dom.backgroundHorizontal.style.left = '0'; dom.backgroundHorizontal.style.top = props.top.height + 'px'; dom.centerContainer.style.left = props.left.width + 'px'; dom.centerContainer.style.top = props.top.height + 'px'; dom.leftContainer.style.left = '0'; dom.leftContainer.style.top = props.top.height + 'px'; dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px'; dom.rightContainer.style.top = props.top.height + 'px'; dom.top.style.left = props.left.width + 'px'; dom.top.style.top = '0'; dom.bottom.style.left = props.left.width + 'px'; dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px'; // update the scrollTop, feasible range for the offset can be changed // when the height of the Core or of the contents of the center changed this._updateScrollTop(); // reposition the scrollable contents var offset = this.props.scrollTop; if (options.orientation == 'bottom') { offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); } dom.center.style.left = '0'; dom.center.style.top = offset + 'px'; dom.left.style.left = '0'; dom.left.style.top = offset + 'px'; dom.right.style.left = '0'; dom.right.style.top = offset + 'px'; // show shadows when vertical scrolling is available var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : ''; dom.shadowTop.style.visibility = visibilityTop; dom.shadowBottom.style.visibility = visibilityBottom; dom.shadowTopLeft.style.visibility = visibilityTop; dom.shadowBottomLeft.style.visibility = visibilityBottom; dom.shadowTopRight.style.visibility = visibilityTop; dom.shadowBottomRight.style.visibility = visibilityBottom; // redraw all components this.components.forEach(function (component) { resized = component.redraw() || resized; }); if (resized) { // keep repainting until all sizes are settled this.redraw(); } }; // TODO: deprecated since version 1.1.0, remove some day Core.prototype.repaint = function () { throw new Error('Function repaint is deprecated. Use redraw instead.'); }; /** * Set a current time. This can be used for example to ensure that a client's * time is synchronized with a shared server time. * Only applicable when option `showCurrentTime` is true. * @param {Date | String | Number} time A Date, unix timestamp, or * ISO date string. */ Core.prototype.setCurrentTime = function(time) { if (!this.currentTime) { throw new Error('Option showCurrentTime must be true'); } this.currentTime.setCurrentTime(time); }; /** * Get the current time. * Only applicable when option `showCurrentTime` is true. * @return {Date} Returns the current time. */ Core.prototype.getCurrentTime = function() { if (!this.currentTime) { throw new Error('Option showCurrentTime must be true'); } return this.currentTime.getCurrentTime(); }; /** * Convert a position on screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Core.prototype._toTime = function(x) { var conversion = this.range.conversion(this.props.center.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a position on the global screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Core.prototype._toGlobalTime = function(x) { var conversion = this.range.conversion(this.props.root.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a datetime (Date object) into a position on the screen * @param {Date} time A date * @return {int} x The position on the screen in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Core.prototype._toScreen = function(time) { var conversion = this.range.conversion(this.props.center.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Convert a datetime (Date object) into a position on the root * This is used to get the pixel density estimate for the screen, not the center panel * @param {Date} time A date * @return {int} x The position on root in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Core.prototype._toGlobalScreen = function(time) { var conversion = this.range.conversion(this.props.root.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Initialize watching when option autoResize is true * @private */ Core.prototype._initAutoResize = function () { if (this.options.autoResize == true) { this._startAutoResize(); } else { this._stopAutoResize(); } }; /** * Watch for changes in the size of the container. On resize, the Panel will * automatically redraw itself. * @private */ Core.prototype._startAutoResize = function () { var me = this; this._stopAutoResize(); this._onResize = function() { if (me.options.autoResize != true) { // stop watching when the option autoResize is changed to false me._stopAutoResize(); return; } if (me.dom.root) { // check whether the frame is resized // Note: we compare offsetWidth here, not clientWidth. For some reason, // IE does not restore the clientWidth from 0 to the actual width after // changing the timeline's container display style from none to visible if ((me.dom.root.offsetWidth != me.props.lastWidth) || (me.dom.root.offsetHeight != me.props.lastHeight)) { me.props.lastWidth = me.dom.root.offsetWidth; me.props.lastHeight = me.dom.root.offsetHeight; me.emit('change'); } } }; // add event listener to window resize util.addEventListener(window, 'resize', this._onResize); this.watchTimer = setInterval(this._onResize, 1000); }; /** * Stop watching for a resize of the frame. * @private */ Core.prototype._stopAutoResize = function () { if (this.watchTimer) { clearInterval(this.watchTimer); this.watchTimer = undefined; } // remove event listener on window.resize util.removeEventListener(window, 'resize', this._onResize); this._onResize = null; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Core.prototype._onTouch = function (event) { this.touch.allowDragging = true; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Core.prototype._onPinch = function (event) { this.touch.allowDragging = false; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Core.prototype._onDragStart = function (event) { this.touch.initialScrollTop = this.props.scrollTop; }; /** * Move the timeline vertically * @param {Event} event * @private */ Core.prototype._onDrag = function (event) { // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.touch.allowDragging) return; var delta = event.gesture.deltaY; var oldScrollTop = this._getScrollTop(); var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); if (newScrollTop != oldScrollTop) { this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already } }; /** * Apply a scrollTop * @param {Number} scrollTop * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Core.prototype._setScrollTop = function (scrollTop) { this.props.scrollTop = scrollTop; this._updateScrollTop(); return this.props.scrollTop; }; /** * Update the current scrollTop when the height of the containers has been changed * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Core.prototype._updateScrollTop = function () { // recalculate the scrollTopMin var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero if (scrollTopMin != this.props.scrollTopMin) { // in case of bottom orientation, change the scrollTop such that the contents // do not move relative to the time axis at the bottom if (this.options.orientation == 'bottom') { this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin); } this.props.scrollTopMin = scrollTopMin; } // limit the scrollTop to the feasible scroll range if (this.props.scrollTop > 0) this.props.scrollTop = 0; if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin; return this.props.scrollTop; }; /** * Get the current scrollTop * @returns {number} scrollTop * @private */ Core.prototype._getScrollTop = function () { return this.props.scrollTop; }; module.exports = Core; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { // English exports['en'] = { current: 'current', time: 'time' }; exports['en_EN'] = exports['en']; exports['en_US'] = exports['en']; // Dutch exports['nl'] = { custom: 'aangepaste', time: 'tijd' }; exports['nl_NL'] = exports['nl']; exports['nl_BE'] = exports['nl']; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { // English exports['en'] = { edit: 'Edit', del: 'Delete selected', back: 'Back', addNode: 'Add Node', addEdge: 'Add Edge', editNode: 'Edit Node', editEdge: 'Edit Edge', addDescription: 'Click in an empty space to place a new node.', edgeDescription: 'Click on a node and drag the edge to another node to connect them.', editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.', createEdgeError: 'Cannot link edges to a cluster.', deleteClusterError: 'Clusters cannot be deleted.' }; exports['en_EN'] = exports['en']; exports['en_US'] = exports['en']; // Dutch exports['nl'] = { edit: 'Wijzigen', del: 'Selectie verwijderen', back: 'Terug', addNode: 'Node toevoegen', addEdge: 'Link toevoegen', editNode: 'Node wijzigen', editEdge: 'Link wijzigen', addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.', edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.', editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.', createEdgeError: 'Kan geen link maken naar een cluster.', deleteClusterError: 'Clusters kunnen niet worden verwijderd.' }; exports['nl_NL'] = exports['nl']; exports['nl_BE'] = exports['nl']; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Canvas shapes used by Network */ if (typeof CanvasRenderingContext2D !== 'undefined') { /** * Draw a circle shape */ CanvasRenderingContext2D.prototype.circle = function(x, y, r) { this.beginPath(); this.arc(x, y, r, 0, 2*Math.PI, false); }; /** * Draw a square shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r size, width and height of the square */ CanvasRenderingContext2D.prototype.square = function(x, y, r) { this.beginPath(); this.rect(x - r, y - r, r * 2, r * 2); }; /** * Draw a triangle shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.triangle = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y - (h - ir)); this.lineTo(x + s2, y + ir); this.lineTo(x - s2, y + ir); this.lineTo(x, y - (h - ir)); this.closePath(); }; /** * Draw a triangle shape in downward orientation * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius */ CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y + (h - ir)); this.lineTo(x + s2, y - ir); this.lineTo(x - s2, y - ir); this.lineTo(x, y + (h - ir)); this.closePath(); }; /** * Draw a star shape, a star with 5 points * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.star = function(x, y, r) { // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ this.beginPath(); for (var n = 0; n < 10; n++) { var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5; this.lineTo( x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10) ); } this.closePath(); }; /** * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas */ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) { var r2d = Math.PI/180; if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y this.beginPath(); this.moveTo(x+r,y); this.lineTo(x+w-r,y); this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false); this.lineTo(x+w,y+h-r); this.arc(x+w-r,y+h-r,r,0,r2d*90,false); this.lineTo(x+r,y+h); this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false); this.lineTo(x,y+r); this.arc(x+r,y+r,r,r2d*180,r2d*270,false); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) { var kappa = .5522848, ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle this.beginPath(); this.moveTo(x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.database = function(x, y, w, h) { var f = 1/3; var wEllipse = w; var hEllipse = h * f; var kappa = .5522848, ox = (wEllipse / 2) * kappa, // control point offset horizontal oy = (hEllipse / 2) * kappa, // control point offset vertical xe = x + wEllipse, // x-end ye = y + hEllipse, // y-end xm = x + wEllipse / 2, // x-middle ym = y + hEllipse / 2, // y-middle ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse yeb = y + h; // y-end, bottom ellipse this.beginPath(); this.moveTo(xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.lineTo(xe, ymb); this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); this.lineTo(x, ym); }; /** * Draw an arrow point (no line) */ CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) { // tail var xt = x - length * Math.cos(angle); var yt = y - length * Math.sin(angle); // inner tail // TODO: allow to customize different shapes var xi = x - length * 0.9 * Math.cos(angle); var yi = y - length * 0.9 * Math.sin(angle); // left var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); // right var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); this.beginPath(); this.moveTo(x, y); this.lineTo(xl, yl); this.lineTo(xi, yi); this.lineTo(xr, yr); this.closePath(); }; /** * Sets up the dashedLine functionality for drawing * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas * @author David Jordan * @date 2012-08-08 */ CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){ if (!dashArray) dashArray=[10,5]; if (dashLength==0) dashLength = 0.001; // Hack for Safari var dashCount = dashArray.length; this.moveTo(x, y); var dx = (x2-x), dy = (y2-y); var slope = dy/dx; var distRemaining = Math.sqrt( dx*dx + dy*dy ); var dashIndex=0, draw=true; while (distRemaining>=0.1){ var dashLength = dashArray[dashIndex++%dashCount]; if (dashLength > distRemaining) dashLength = distRemaining; var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) ); if (dx<0) xStep = -xStep; x += xStep; y += slope*xStep; this[draw ? 'lineTo' : 'moveTo'](x,y); distRemaining -= dashLength; draw = !draw; } }; // TODO: add diamond shape } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var PhysicsMixin = __webpack_require__(60); var ClusterMixin = __webpack_require__(54); var SectorsMixin = __webpack_require__(55); var SelectionMixin = __webpack_require__(56); var ManipulationMixin = __webpack_require__(57); var NavigationMixin = __webpack_require__(58); var HierarchicalLayoutMixin = __webpack_require__(59); /** * Load a mixin into the network object * * @param {Object} sourceVariable | this object has to contain functions. * @private */ exports._loadMixin = function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { this[mixinFunction] = sourceVariable[mixinFunction]; } } }; /** * removes a mixin from the network object. * * @param {Object} sourceVariable | this object has to contain functions. * @private */ exports._clearMixin = function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { this[mixinFunction] = undefined; } } }; /** * Mixin the physics system and initialize the parameters required. * * @private */ exports._loadPhysicsSystem = function () { this._loadMixin(PhysicsMixin); this._loadSelectedForceSolver(); if (this.constants.configurePhysics == true) { this._loadPhysicsConfiguration(); } }; /** * Mixin the cluster system and initialize the parameters required. * * @private */ exports._loadClusterSystem = function () { this.clusterSession = 0; this.hubThreshold = 5; this._loadMixin(ClusterMixin); }; /** * Mixin the sector system and initialize the parameters required * * @private */ exports._loadSectorSystem = function () { this.sectors = {}; this.activeSector = ["default"]; this.sectors["active"] = {}; this.sectors["active"]["default"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.sectors["frozen"] = {}; this.sectors["support"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields this._loadMixin(SectorsMixin); }; /** * Mixin the selection system and initialize the parameters required * * @private */ exports._loadSelectionSystem = function () { this.selectionObj = {nodes: {}, edges: {}}; this._loadMixin(SelectionMixin); }; /** * Mixin the navigationUI (User Interface) system and initialize the parameters required * * @private */ exports._loadManipulationSystem = function () { // reset global variables -- these are used by the selection of nodes and edges. this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.constants.dataManipulation.enabled == true) { // load the manipulator HTML elements. All styling done in css. if (this.manipulationDiv === undefined) { this.manipulationDiv = document.createElement('div'); this.manipulationDiv.className = 'network-manipulationDiv'; this.manipulationDiv.id = 'network-manipulationDiv'; if (this.editMode == true) { this.manipulationDiv.style.display = "block"; } else { this.manipulationDiv.style.display = "none"; } this.frame.appendChild(this.manipulationDiv); } if (this.editModeDiv === undefined) { this.editModeDiv = document.createElement('div'); this.editModeDiv.className = 'network-manipulation-editMode'; this.editModeDiv.id = 'network-manipulation-editMode'; if (this.editMode == true) { this.editModeDiv.style.display = "none"; } else { this.editModeDiv.style.display = "block"; } this.frame.appendChild(this.editModeDiv); } if (this.closeDiv === undefined) { this.closeDiv = document.createElement('div'); this.closeDiv.className = 'network-manipulation-closeDiv'; this.closeDiv.id = 'network-manipulation-closeDiv'; this.closeDiv.style.display = this.manipulationDiv.style.display; this.frame.appendChild(this.closeDiv); } // load the manipulation functions this._loadMixin(ManipulationMixin); // create the manipulator toolbar this._createManipulatorBar(); } else { if (this.manipulationDiv !== undefined) { // removes all the bindings and overloads this._createManipulatorBar(); // remove the manipulation divs this.frame.removeChild(this.manipulationDiv); this.frame.removeChild(this.editModeDiv); this.frame.removeChild(this.closeDiv); this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; // remove the mixin functions this._clearMixin(ManipulationMixin); } } }; /** * Mixin the navigation (User Interface) system and initialize the parameters required * * @private */ exports._loadNavigationControls = function () { this._loadMixin(NavigationMixin); // the clean function removes the button divs, this is done to remove the bindings. this._cleanNavigation(); if (this.constants.navigation.enabled == true) { this._loadNavigationElements(); } }; /** * Mixin the hierarchical layout system. * * @private */ exports._loadHierarchySystem = function () { this._loadMixin(HierarchicalLayoutMixin); }; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var mousetrap = __webpack_require__(51); var Emitter = __webpack_require__(50); var Hammer = __webpack_require__(42); var util = __webpack_require__(1); /** * Turn an element into an clickToUse element. * When not active, the element has a transparent overlay. When the overlay is * clicked, the mode is changed to active. * When active, the element is displayed with a blue border around it, and * the interactive contents of the element can be used. When clicked outside * the element, the elements mode is changed to inactive. * @param {Element} container * @constructor */ function Activator(container) { this.active = false; this.dom = { container: container }; this.dom.overlay = document.createElement('div'); this.dom.overlay.className = 'overlay'; this.dom.container.appendChild(this.dom.overlay); this.hammer = Hammer(this.dom.overlay, {prevent_default: false}); this.hammer.on('tap', this._onTapOverlay.bind(this)); // block all touch events (except tap) var me = this; var events = [ 'touch', 'pinch', 'doubletap', 'hold', 'dragstart', 'drag', 'dragend', 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox ]; events.forEach(function (event) { me.hammer.on(event, function (event) { event.stopPropagation(); }); }); // attach a tap event to the window, in order to deactivate when clicking outside the timeline this.windowHammer = Hammer(window, {prevent_default: false}); this.windowHammer.on('tap', function (event) { // deactivate when clicked outside the container if (!_hasParent(event.target, container)) { me.deactivate(); } }); // mousetrap listener only bounded when active) this.escListener = this.deactivate.bind(this); } // turn into an event emitter Emitter(Activator.prototype); // The currently active activator Activator.current = null; /** * Destroy the activator. Cleans up all created DOM and event listeners */ Activator.prototype.destroy = function () { this.deactivate(); // remove dom this.dom.overlay.parentNode.removeChild(this.dom.overlay); // cleanup hammer instances this.hammer = null; this.windowHammer = null; // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory) }; /** * Activate the element * Overlay is hidden, element is decorated with a blue shadow border */ Activator.prototype.activate = function () { // we allow only one active activator at a time if (Activator.current) { Activator.current.deactivate(); } Activator.current = this; this.active = true; this.dom.overlay.style.display = 'none'; util.addClassName(this.dom.container, 'vis-active'); this.emit('change'); this.emit('activate'); // ugly hack: bind ESC after emitting the events, as the Network rebinds all // keyboard events on a 'change' event mousetrap.bind('esc', this.escListener); }; /** * Deactivate the element * Overlay is displayed on top of the element */ Activator.prototype.deactivate = function () { this.active = false; this.dom.overlay.style.display = ''; util.removeClassName(this.dom.container, 'vis-active'); mousetrap.unbind('esc', this.escListener); this.emit('change'); this.emit('deactivate'); }; /** * Handle a tap event: activate the container * @param event * @private */ Activator.prototype._onTapOverlay = function (event) { // activate the container this.activate(); event.stopPropagation(); }; /** * Test whether the element has the requested parent element somewhere in * its chain of parent nodes. * @param {HTMLElement} element * @param {HTMLElement} parent * @returns {boolean} Returns true when the parent is found somewhere in the * chain of parent nodes. * @private */ function _hasParent(element, parent) { while (element) { if (element === parent) { return true } element = element.parentNode; } return false; } module.exports = Activator; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ 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; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {//! moment.js //! version : 2.8.3 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.8.3', // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, hasOwnProperty = Object.prototype.hasOwnProperty, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-15', '30'] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function hasOwnProp(a, b) { return hasOwnProperty.call(a, b); } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function timezoneMinutesFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = config._locale.isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be 'T' or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( 'moment.lang is deprecated. Use moment.locale instead.', function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== 'undefined') { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( 'moment.langData is deprecated. Use moment.localeData instead.', function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.zone(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.zone(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.add(this._dateTzOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output, daysAdjust; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. daysAdjust = (this - moment(this).startOf('month')) - (that - moment(that).startOf('month')); // same as above but with zones, to negate all dst daysAdjust -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4; output += daysAdjust / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this > +input; } else { return +this.clone().startOf(units) > +moment(input).startOf(units); } }, isBefore: function (input, units) { units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this < +input; } else { return +this.clone().startOf(units) < +moment(input).startOf(units); } }, isSame: function (input, units) { units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this === +input; } else { return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); } }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._dateTzOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.subtract(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._dateTzOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = moment.localeData(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } }, lang : deprecate( 'moment().lang() is deprecated. Use moment().localeData() instead.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ), localeData : function () { return this._locale; }, _dateTzOffset : function () { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return Math.round(this._d.getTimezoneOffset() / 15) * 15; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + this._milliseconds / 864e5; months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + yearsToDays(this._months / 12); switch (units) { case 'week': return days / 7 + this._milliseconds / 6048e5; case 'day': return days + this._milliseconds / 864e5; case 'hour': return days * 24 + this._milliseconds / 36e5; case 'minute': return days * 24 * 60 + this._milliseconds / 6e4; case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( 'toIsoString() is deprecated. Please use toISOString() instead ' + '(notice the capitals)', function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; } }); moment.duration.fn.toString = moment.duration.fn.toISOString; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (hasOwnProp(unitMillisecondFactors, i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); makeGlobal(true); } else { makeGlobal(); } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(65)(module))) /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20 * http://eightmedia.github.io/hammer.js * * Copyright (c) 2014 Jorik Tangelder <[email protected]>; * Licensed under the MIT license */ (function(window, undefined) { 'use strict'; /** * @main * @module hammer * * @class Hammer * @static */ /** * Hammer, use this to create instances * ```` * var hammertime = new Hammer(myElement); * ```` * * @method Hammer * @param {HTMLElement} element * @param {Object} [options={}] * @return {Hammer.Instance} */ var Hammer = function Hammer(element, options) { return new Hammer.Instance(element, options || {}); }; /** * version, as defined in package.json * the value will be set at each build * @property VERSION * @final * @type {String} */ Hammer.VERSION = '1.1.3'; /** * default settings. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled * by setting it's name (like `swipe`) to false. * You can set the defaults for all instances by changing this object before creating an instance. * @example * ```` * Hammer.defaults.drag = false; * Hammer.defaults.behavior.touchAction = 'pan-y'; * delete Hammer.defaults.behavior.userSelect; * ```` * @property defaults * @type {Object} */ Hammer.defaults = { /** * this setting object adds styles and attributes to the element to prevent the browser from doing * its native behavior. The css properties are auto prefixed for the browsers when needed. * @property defaults.behavior * @type {Object} */ behavior: { /** * Disables text selection to improve the dragging gesture. When the value is `none` it also sets * `onselectstart=false` for IE on the element. Mainly for desktop browsers. * @property defaults.behavior.userSelect * @type {String} * @default 'none' */ userSelect: 'none', /** * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming). * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event. * @property defaults.behavior.touchAction * @type {String} * @default: 'pan-y' */ touchAction: 'pan-y', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @property defaults.behavior.touchCallout * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @property defaults.behavior.contentZooming * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. * Mainly for desktop browsers. * @property defaults.behavior.userDrag * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in Safari on iPhone. This property obeys the alpha value, if specified. * * If you don't specify an alpha value, Safari on iPhone applies a default alpha value * to the color. To disable tap highlighting, set the alpha value to 0 (invisible). * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped. * @property defaults.behavior.tapHighlightColor * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; /** * hammer document where the base events are added at * @property DOCUMENT * @type {HTMLElement} * @default window.document */ Hammer.DOCUMENT = document; /** * detect support for pointer events * @property HAS_POINTEREVENTS * @type {Boolean} */ Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled; /** * detect support for touch events * @property HAS_TOUCHEVENTS * @type {Boolean} */ Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window); /** * detect mobile browsers * @property IS_MOBILE * @type {Boolean} */ Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent); /** * detect if we want to support mouseevents at all * @property NO_MOUSEEVENTS * @type {Boolean} */ Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS; /** * interval in which Hammer recalculates current velocity/direction/angle in ms * @property CALCULATE_INTERVAL * @type {Number} * @default 25 */ Hammer.CALCULATE_INTERVAL = 25; /** * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup` * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`) * @property EVENT_TYPES * @private * @writeOnce * @type {Object} */ var EVENT_TYPES = {}; /** * direction strings, for safe comparisons * @property DIRECTION_DOWN|LEFT|UP|RIGHT * @final * @type {String} * @default 'down' 'left' 'up' 'right' */ var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down'; var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left'; var DIRECTION_UP = Hammer.DIRECTION_UP = 'up'; var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right'; /** * pointertype strings, for safe comparisons * @property POINTER_MOUSE|TOUCH|PEN * @final * @type {String} * @default 'mouse' 'touch' 'pen' */ var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse'; var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch'; var POINTER_PEN = Hammer.POINTER_PEN = 'pen'; /** * eventtypes * @property EVENT_START|MOVE|END|RELEASE|TOUCH * @final * @type {String} * @default 'start' 'change' 'move' 'end' 'release' 'touch' */ var EVENT_START = Hammer.EVENT_START = 'start'; var EVENT_MOVE = Hammer.EVENT_MOVE = 'move'; var EVENT_END = Hammer.EVENT_END = 'end'; var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release'; var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch'; /** * if the window events are set... * @property READY * @writeOnce * @type {Boolean} * @default false */ Hammer.READY = false; /** * plugins namespace * @property plugins * @type {Object} */ Hammer.plugins = Hammer.plugins || {}; /** * gestures namespace * see `/gestures` for the definitions * @property gestures * @type {Object} */ Hammer.gestures = Hammer.gestures || {}; /** * setup events to detect gestures on the document * this function is called when creating an new instance * @private */ function setup() { if(Hammer.READY) { return; } // find what eventtypes we add listeners to Event.determineEventTypes(); // Register all gestures inside Hammer.gestures Utils.each(Hammer.gestures, function(gesture) { Detection.register(gesture); }); // Add touch events on the document Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect); Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect); // Hammer is ready...! Hammer.READY = true; } /** * @module hammer * * @class Utils * @static */ var Utils = Hammer.utils = { /** * extend method, could also be used for cloning when `dest` is an empty object. * changes the dest object * @method extend * @param {Object} dest * @param {Object} src * @param {Boolean} [merge=false] do a merge * @return {Object} dest */ extend: function extend(dest, src, merge) { for(var key in src) { if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) { continue; } dest[key] = src[key]; } return dest; }, /** * simple addEventListener wrapper * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ on: function on(element, type, handler) { element.addEventListener(type, handler, false); }, /** * simple removeEventListener wrapper * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ off: function off(element, type, handler) { element.removeEventListener(type, handler, false); }, /** * forEach over arrays and objects * @method each * @param {Object|Array} obj * @param {Function} iterator * @param {any} iterator.item * @param {Number} iterator.index * @param {Object|Array} iterator.obj the source object * @param {Object} context value to use as `this` in the iterator */ each: function each(obj, iterator, context) { var i, len; // native forEach on arrays if('forEach' in obj) { obj.forEach(iterator, context); // arrays } else if(obj.length !== undefined) { for(i = 0, len = obj.length; i < len; i++) { if(iterator.call(context, obj[i], i, obj) === false) { return; } } // objects } else { for(i in obj) { if(obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) { return; } } } }, /** * find if a string contains the string using indexOf * @method inStr * @param {String} src * @param {String} find * @return {Boolean} found */ inStr: function inStr(src, find) { return src.indexOf(find) > -1; }, /** * find if a array contains the object using indexOf or a simple polyfill * @method inArray * @param {String} src * @param {String} find * @return {Boolean|Number} false when not found, or the index */ inArray: function inArray(src, find) { if(src.indexOf) { var index = src.indexOf(find); return (index === -1) ? false : index; } else { for(var i = 0, len = src.length; i < len; i++) { if(src[i] === find) { return i; } } return false; } }, /** * convert an array-like object (`arguments`, `touchlist`) to an array * @method toArray * @param {Object} obj * @return {Array} */ toArray: function toArray(obj) { return Array.prototype.slice.call(obj, 0); }, /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ hasParent: function hasParent(node, parent) { while(node) { if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @method getCenter * @param {Array} touches * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties */ getCenter: function getCenter(touches) { var pageX = [], pageY = [], clientX = [], clientY = [], min = Math.min, max = Math.max; // no need to loop when only one touch if(touches.length === 1) { return { pageX: touches[0].pageX, pageY: touches[0].pageY, clientX: touches[0].clientX, clientY: touches[0].clientY }; } Utils.each(touches, function(touch) { pageX.push(touch.pageX); pageY.push(touch.pageY); clientX.push(touch.clientX); clientY.push(touch.clientY); }); return { pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2, pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2, clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2, clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2 }; }, /** * calculate the velocity between two points. unit is in px per ms. * @method getVelocity * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY * @return {Object} velocity `x` and `y` */ getVelocity: function getVelocity(deltaTime, deltaX, deltaY) { return { x: Math.abs(deltaX / deltaTime) || 0, y: Math.abs(deltaY / deltaTime) || 0 }; }, /** * calculate the angle between two coordinates * @method getAngle * @param {Touch} touch1 * @param {Touch} touch2 * @return {Number} angle */ getAngle: function getAngle(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.atan2(y, x) * 180 / Math.PI; }, /** * do a small comparision to get the direction between two touches. * @method getDirection * @param {Touch} touch1 * @param {Touch} touch2 * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN` */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.clientX - touch2.clientX), y = Math.abs(touch1.clientY - touch2.clientY); if(x >= y) { return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN; }, /** * calculate the distance between two touches * @method getDistance * @param {Touch}touch1 * @param {Touch} touch2 * @return {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @method getScale * @param {Array} start array of touches * @param {Array} end array of touches * @return {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 * @method getRotation * @param {Array} start array of touches * @param {Array} end array of touches * @return {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; }, /** * find out if the direction is vertical * * @method isVertical * @param {String} direction matches `DIRECTION_UP|DOWN` * @return {Boolean} is_vertical */ isVertical: function isVertical(direction) { return direction == DIRECTION_UP || direction == DIRECTION_DOWN; }, /** * set css properties with their prefixes * @param {HTMLElement} element * @param {String} prop * @param {String} value * @param {Boolean} [toggle=true] * @return {Boolean} */ setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) { var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms']; prop = Utils.toCamelCase(prop); for(var i = 0; i < prefixes.length; i++) { var p = prop; // prefixes if(prefixes[i]) { p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1); } // test the style if(p in element.style) { element.style[p] = (toggle == null || toggle) && value || ''; break; } } }, /** * toggle browser default behavior by setting css properties. * `userSelect='none'` also sets `element.onselectstart` to false * `userDrag='none'` also sets `element.ondragstart` to false * * @method toggleBehavior * @param {HtmlElement} element * @param {Object} props * @param {Boolean} [toggle=true] */ toggleBehavior: function toggleBehavior(element, props, toggle) { if(!props || !element || !element.style) { return; } // set the css properties Utils.each(props, function(value, prop) { Utils.setPrefixedCss(element, prop, value, toggle); }); var falseFn = toggle && function() { return false; }; // also the disable onselectstart if(props.userSelect == 'none') { element.onselectstart = falseFn; } // and disable ondragstart if(props.userDrag == 'none') { element.ondragstart = falseFn; } }, /** * convert a string with underscores to camelCase * so prevent_default becomes preventDefault * @param {String} str * @return {String} camelCaseStr */ toCamelCase: function toCamelCase(str) { return str.replace(/[_-]([a-z])/g, function(s) { return s[1].toUpperCase(); }); } }; /** * @module hammer */ /** * @class Event * @static */ var Event = Hammer.event = { /** * when touch events have been fired, this is true * this is used to stop mouse events * @property prevent_mouseevents * @private * @type {Boolean} */ preventMouseEvents: false, /** * if EVENT_START has been fired * @property started * @private * @type {Boolean} */ started: false, /** * when the mouse is hold down, this is true * @property should_detect * @private * @type {Boolean} */ shouldDetect: false, /** * simple event binder with a hook and support for multiple types * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ on: function on(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.on(element, type, handler); hook && hook(type); }); }, /** * simple event unbinder with a hook and support for multiple types * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ off: function off(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.off(element, type, handler); hook && hook(type); }); }, /** * the core touch event handler. * this finds out if we should to detect gestures * @method onTouch * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Function} handler * @return onTouchHandler {Function} the core event handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; var onTouchHandler = function onTouchHandler(ev) { var srcType = ev.type.toLowerCase(), isPointer = Hammer.HAS_POINTEREVENTS, isMouse = Utils.inStr(srcType, 'mouse'), triggerType; // if we are in a mouseevent, but there has been a touchevent triggered in this session // we want to do nothing. simply break out of the event. if(isMouse && self.preventMouseEvents) { return; // mousebutton must be down } else if(isMouse && eventType == EVENT_START && ev.button === 0) { self.preventMouseEvents = false; self.shouldDetect = true; } else if(isPointer && eventType == EVENT_START) { self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev)); // just a valid start event, but no mouse } else if(!isMouse && eventType == EVENT_START) { self.preventMouseEvents = true; self.shouldDetect = true; } // update the pointer event before entering the detection if(isPointer && eventType != EVENT_END) { PointerEvent.updatePointer(eventType, ev); } // we are in a touch/down state, so allowed detection of gestures if(self.shouldDetect) { triggerType = self.doDetect.call(self, ev, eventType, element, handler); } // ...and we are done with the detection // so reset everything to start each detection totally fresh if(triggerType == EVENT_END) { self.preventMouseEvents = false; self.shouldDetect = false; PointerEvent.reset(); // update the pointerevent object after the detection } if(isPointer && eventType == EVENT_END) { PointerEvent.updatePointer(eventType, ev); } }; this.on(element, EVENT_TYPES[eventType], onTouchHandler); return onTouchHandler; }, /** * the core detection method * this finds out what hammer-touch-events to trigger * @method doDetect * @param {Object} ev * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {HTMLElement} element * @param {Function} handler * @return {String} triggerType matches `EVENT_START|MOVE|END` */ doDetect: function doDetect(ev, eventType, element, handler) { var touchList = this.getTouchList(ev, eventType); var touchListLength = touchList.length; var triggerType = eventType; var triggerChange = touchList.trigger; // used by fakeMultitouch plugin var changedLength = touchListLength; // at each touchstart-like event we want also want to trigger a TOUCH event... if(eventType == EVENT_START) { triggerChange = EVENT_TOUCH; // ...the same for a touchend-like event } else if(eventType == EVENT_END) { triggerChange = EVENT_RELEASE; // keep track of how many touches have been removed changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1); } // after there are still touches on the screen, // we just want to trigger a MOVE event. so change the START or END to a MOVE // but only after detection has been started, the first time we actualy want a START if(changedLength > 0 && this.started) { triggerType = EVENT_MOVE; } // detection has been started, we keep track of this, see above this.started = true; // generate some event data, some basic information var evData = this.collectEventData(element, triggerType, touchList, ev); // trigger the triggerType event before the change (TOUCH, RELEASE) events // but the END event should be at last if(eventType != EVENT_END) { handler.call(Detection, evData); } // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed if(triggerChange) { evData.changedLength = changedLength; evData.eventType = triggerChange; handler.call(Detection, evData); evData.eventType = triggerType; delete evData.changedLength; } // trigger the END event if(triggerType == EVENT_END) { handler.call(Detection, evData); // ...and we are done with the detection // so reset everything to start each detection totally fresh this.started = false; } return triggerType; }, /** * we have different events for each device/browser * determine what we need and set them in the EVENT_TYPES constant * the `onTouch` method is bind to these properties. * @method determineEventTypes * @return {Object} events */ determineEventTypes: function determineEventTypes() { var types; if(Hammer.HAS_POINTEREVENTS) { if(window.PointerEvent) { types = [ 'pointerdown', 'pointermove', 'pointerup pointercancel lostpointercapture' ]; } else { types = [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp MSPointerCancel MSLostPointerCapture' ]; } } else if(Hammer.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel' ]; } else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup' ]; } EVENT_TYPES[EVENT_START] = types[0]; EVENT_TYPES[EVENT_MOVE] = types[1]; EVENT_TYPES[EVENT_END] = types[2]; return EVENT_TYPES; }, /** * create touchList depending on the event * @method getTouchList * @param {Object} ev * @param {String} eventType * @return {Array} touches */ getTouchList: function getTouchList(ev, eventType) { // get the fake pointerEvent touchlist if(Hammer.HAS_POINTEREVENTS) { return PointerEvent.getTouchList(); } // get the touchlist if(ev.touches) { if(eventType == EVENT_MOVE) { return ev.touches; } var identifiers = []; var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches)); var touchList = []; Utils.each(concat, function(touch) { if(Utils.inArray(identifiers, touch.identifier) === false) { touchList.push(touch); } identifiers.push(touch.identifier); }); return touchList; } // make fake touchList from mouse position ev.identifier = 1; return [ev]; }, /** * collect basic event data * @method collectEventData * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Array} touches * @param {Object} ev * @return {Object} ev */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } else if(PointerEvent.matchType(POINTER_PEN, ev)) { pointerType = POINTER_PEN; } return { center: Utils.getCenter(touches), timeStamp: Date.now(), 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() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && 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 Detection.stopDetect(); } }; } }; /** * @module hammer * * @class PointerEvent * @static */ var PointerEvent = Hammer.PointerEvent = { /** * holds all pointers, by `identifier` * @property pointers * @type {Object} */ pointers: {}, /** * get the pointers as an array * @method getTouchList * @return {Array} touchlist */ getTouchList: function getTouchList() { var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Utils.each(this.pointers, function(pointer) { touchlist.push(pointer); }); return touchlist; }, /** * update the position of a pointer * @method updatePointer * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Object} pointerEvent */ updatePointer: function updatePointer(eventType, pointerEvent) { if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) { delete this.pointers[pointerEvent.pointerId]; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } }, /** * check if ev matches pointertype * @method matchType * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN` * @param {PointerEvent} ev */ matchType: function matchType(pointerType, ev) { if(!ev.pointerType) { return false; } var pt = ev.pointerType, types = {}; types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE)); types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH)); types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN)); return types[pointerType]; }, /** * reset the stored pointers * @method reset */ reset: function resetList() { this.pointers = {}; } }; /** * @module hammer * * @class Detection * @static */ var Detection = Hammer.detection = { // contains all registred Hammer.gestures in the correct order gestures: [], // data of the current Hammer.gesture detection session current: null, // the previous Hammer.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 Hammer.gesture detection * @method startDetect * @param {Hammer.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a Hammer.gesture detection on an element if(this.current) { return; } this.stopped = false; // holds current session this.current = { inst: inst, // reference to HammerInstance we're working for startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent: false, // last eventData lastCalcEvent: false, // last eventData for calculations. futureCalcEvent: false, // last eventData for calculations. lastCalcData: {}, // last lastCalcData name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * Hammer.gesture detection * @method detect * @param {Object} eventData * @return {any} */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // hammer instance and instance options var inst = this.current.inst, instOptions = inst.options; // call Hammer.gesture handlers Utils.each(this.gestures, function triggerGesture(gesture) { // only when the instance options have enabled this gesture if(!this.stopped && inst.enabled && instOptions[gesture.name]) { gesture.handler.call(gesture, eventData, inst); } }, this); // store as previous event event if(this.current) { this.current.lastEvent = eventData; } if(eventData.eventType == EVENT_END) { this.stopDetect(); } return eventData; }, /** * clear the Hammer.gesture vars * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected * to stop other Hammer.gestures from being fired * @method stopDetect */ 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 = Utils.extend({}, this.current); // reset the current this.current = null; this.stopped = true; }, /** * calculate velocity, angle and direction * @method getVelocityData * @param {Object} ev * @param {Object} center * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY */ getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) { var cur = this.current, recalc = false, calcEv = cur.lastCalcEvent, calcData = cur.lastCalcData; if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) { center = calcEv.center; deltaTime = ev.timeStamp - calcEv.timeStamp; deltaX = ev.center.clientX - calcEv.center.clientX; deltaY = ev.center.clientY - calcEv.center.clientY; recalc = true; } if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { cur.futureCalcEvent = ev; } if(!cur.lastCalcEvent || recalc) { calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY); calcData.angle = Utils.getAngle(center, ev.center); calcData.direction = Utils.getDirection(center, ev.center); cur.lastCalcEvent = cur.futureCalcEvent || ev; cur.futureCalcEvent = ev; } ev.velocityX = calcData.velocity.x; ev.velocityY = calcData.velocity.y; ev.interimAngle = calcData.angle; ev.interimDirection = calcData.direction; }, /** * extend eventData for Hammer.gestures * @method extendEventData * @param {Object} ev * @return {Object} ev */ extendEventData: function extendEventData(ev) { var cur = this.current, startEv = cur.startEvent, lastEv = cur.lastEvent || startEv; // update the start touchlist to calculate the scale/rotation if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { startEv.touches = []; Utils.each(ev.touches, function(touch) { startEv.touches.push({ clientX: touch.clientX, clientY: touch.clientY }); }); } var deltaTime = ev.timeStamp - startEv.timeStamp, deltaX = ev.center.clientX - startEv.center.clientX, deltaY = ev.center.clientY - startEv.center.clientY; this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY); Utils.extend(ev, { startEvent: startEv, deltaTime: deltaTime, deltaX: deltaX, deltaY: deltaY, distance: Utils.getDistance(startEv.center, ev.center), angle: Utils.getAngle(startEv.center, ev.center), direction: Utils.getDirection(startEv.center, ev.center), scale: Utils.getScale(startEv.touches, ev.touches), rotation: Utils.getRotation(startEv.touches, ev.touches) }); return ev; }, /** * register new gesture * @method register * @param {Object} gesture object, see `gestures/` for documentation * @return {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 Hammer default options with the Hammer.gesture options Utils.extend(Hammer.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add Hammer.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; } }; /** * @module hammer */ /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * * @class Instance * @constructor * @param {HTMLElement} element * @param {Object} [options={}] options are merged with `Hammer.defaults` * @return {Hammer.Instance} */ Hammer.Instance = function(element, options) { var self = this; // setup HammerJS window events and register all gestures // this also sets up the default options setup(); /** * @property element * @type {HTMLElement} */ this.element = element; /** * @property enabled * @type {Boolean} * @protected */ this.enabled = true; /** * options, merged with the defaults * options with an _ are converted to camelCase * @property options * @type {Object} */ Utils.each(options, function(value, name) { delete options[name]; options[Utils.toCamelCase(name)] = value; }); this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.behavior) { Utils.toggleBehavior(this.element, this.options.behavior, true); } /** * event start handler on the element to start the detection * @property eventStartHandler * @type {Object} */ this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) { if(self.enabled && ev.eventType == EVENT_START) { Detection.startDetect(self, ev); } else if(ev.eventType == EVENT_TOUCH) { Detection.detect(ev); } }); /** * keep a list of user event handlers which needs to be removed when calling 'dispose' * @property eventHandlers * @type {Array} */ this.eventHandlers = []; }; Hammer.Instance.prototype = { /** * bind events to the instance * @method on * @chainable * @param {String} gestures multiple gestures by splitting with a space * @param {Function} handler * @param {Object} handler.ev event object */ on: function onEvent(gestures, handler) { var self = this; Event.on(self.element, gestures, handler, function(type) { self.eventHandlers.push({ gesture: type, handler: handler }); }); return self; }, /** * unbind events to the instance * @method off * @chainable * @param {String} gestures * @param {Function} handler */ off: function offEvent(gestures, handler) { var self = this; Event.off(self.element, gestures, handler, function(type) { var index = Utils.inArray({ gesture: type, handler: handler }); if(index !== false) { self.eventHandlers.splice(index, 1); } }); return self; }, /** * trigger gesture event * @method trigger * @chainable * @param {String} gesture * @param {Object} [eventData] */ trigger: function triggerEvent(gesture, eventData) { // optional if(!eventData) { eventData = {}; } // create DOM event var event = Hammer.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(Utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @method enable * @chainable * @param {Boolean} state */ enable: function enable(state) { this.enabled = state; return this; }, /** * dispose this hammer instance * @method dispose * @return {Null} */ dispose: function dispose() { var i, eh; // undo all changes made by stop_browser_behavior Utils.toggleBehavior(this.element, this.options.behavior, false); // unbind all custom event handlers for(i = -1; (eh = this.eventHandlers[++i]);) { Utils.off(this.element, eh.gesture, eh.handler); } this.eventHandlers = []; // unbind the start event listener Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; } }; /** * @module gestures */ /** * Move with x fingers (default 1) around on the page. * Preventing the default browser behavior is a good way to improve feel and working. * ```` * hammertime.on("drag", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Drag * @static */ /** * @event drag * @param {Object} ev */ /** * @event dragstart * @param {Object} ev */ /** * @event dragend * @param {Object} ev */ /** * @event drapleft * @param {Object} ev */ /** * @event dragright * @param {Object} ev */ /** * @event dragup * @param {Object} ev */ /** * @event dragdown * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function dragGesture(ev, inst) { var cur = Detection.current; // max touches if(inst.options.dragMaxTouches > 0 && ev.touches.length > inst.options.dragMaxTouches) { return; } switch(ev.eventType) { case EVENT_START: triggered = false; break; case 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.dragMinDistance && cur.name != name) { return; } var startCenter = cur.startEvent.center; // we are dragging! if(cur.name != name) { cur.name = name; if(inst.options.dragDistanceCorrection && ev.distance > 0) { // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.dragMinDistance / ev.distance); startCenter.pageX += ev.deltaX * factor; startCenter.pageY += ev.deltaY * factor; startCenter.clientX += ev.deltaX * factor; startCenter.clientY += ev.deltaY * factor; // recalculate event data using new start point ev = Detection.extendEventData(ev); } } // lock drag to axis? if(cur.lastEvent.dragLockToAxis || ( inst.options.dragLockToAxis && inst.options.dragLockMinDistance <= ev.distance )) { ev.dragLockToAxis = true; } // keep direction on the axis that the drag gesture started on var lastDirection = cur.lastEvent.direction; if(ev.dragLockToAxis && lastDirection !== ev.direction) { if(Utils.isVertical(lastDirection)) { ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } // trigger events inst.trigger(name, ev); inst.trigger(name + ev.direction, ev); var isVertical = Utils.isVertical(ev.direction); // block the browser events if((inst.options.dragBlockVertical && isVertical) || (inst.options.dragBlockHorizontal && !isVertical)) { ev.preventDefault(); } break; case EVENT_RELEASE: if(triggered && ev.changedLength <= inst.options.dragMaxTouches) { inst.trigger(name + 'end', ev); triggered = false; } break; case EVENT_END: triggered = false; break; } } Hammer.gestures.Drag = { name: name, index: 50, handler: dragGesture, defaults: { /** * minimal movement that have to be made before the drag event gets triggered * @property dragMinDistance * @type {Number} * @default 10 */ dragMinDistance: 10, /** * Set dragDistanceCorrection 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. * @property dragDistanceCorrection * @type {Boolean} * @default true */ dragDistanceCorrection: true, /** * set 0 for unlimited, but this can conflict with transform * @property dragMaxTouches * @type {Number} * @default 1 */ dragMaxTouches: 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 * @property dragBlockHorizontal * @type {Boolean} * @default false */ dragBlockHorizontal: false, /** * same as `dragBlockHorizontal`, but for vertical movement * @property dragBlockVertical * @type {Boolean} * @default false */ dragBlockVertical: false, /** * dragLockToAxis keeps the drag gesture on the axis that it started on, * It disallows vertical directions if the initial direction was horizontal, and vice versa. * @property dragLockToAxis * @type {Boolean} * @default false */ dragLockToAxis: false, /** * drag lock only kicks in when distance > dragLockMinDistance * This way, locking occurs only when the distance has become large enough to reliably determine the direction * @property dragLockMinDistance * @type {Number} * @default 25 */ dragLockMinDistance: 25 } }; })('drag'); /** * @module gestures */ /** * trigger a simple gesture event, so you can do anything in your handler. * only usable if you know what your doing... * * @class Gesture * @static */ /** * @event gesture * @param {Object} ev */ Hammer.gestures.Gesture = { name: 'gesture', index: 1337, handler: function releaseGesture(ev, inst) { inst.trigger(this.name, ev); } }; /** * @module gestures */ /** * Touch stays at the same place for x time * * @class Hold * @static */ /** * @event hold * @param {Object} ev */ /** * @param {String} name */ (function(name) { var timer; function holdGesture(ev, inst) { var options = inst.options, current = Detection.current; switch(ev.eventType) { case EVENT_START: clearTimeout(timer); // set the gesture so we can check in the timeout if it still is current.name = name; // set timer and if after the timeout it still is hold, // we trigger the hold event timer = setTimeout(function() { if(current && current.name == name) { inst.trigger(name, ev); } }, options.holdTimeout); break; case EVENT_MOVE: if(ev.distance > options.holdThreshold) { clearTimeout(timer); } break; case EVENT_RELEASE: clearTimeout(timer); break; } } Hammer.gestures.Hold = { name: name, index: 10, defaults: { /** * @property holdTimeout * @type {Number} * @default 500 */ holdTimeout: 500, /** * movement allowed while holding * @property holdThreshold * @type {Number} * @default 2 */ holdThreshold: 2 }, handler: holdGesture }; })('hold'); /** * @module gestures */ /** * when a touch is being released from the page * * @class Release * @static */ /** * @event release * @param {Object} ev */ Hammer.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { inst.trigger(this.name, ev); } } }; /** * @module gestures */ /** * triggers swipe events when the end velocity is above the threshold * for best usage, set `preventDefault` (on the drag gesture) to `true` * ```` * hammertime.on("dragleft swipeleft", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Swipe * @static */ /** * @event swipe * @param {Object} ev */ /** * @event swipeleft * @param {Object} ev */ /** * @event swiperight * @param {Object} ev */ /** * @event swipeup * @param {Object} ev */ /** * @event swipedown * @param {Object} ev */ Hammer.gestures.Swipe = { name: 'swipe', index: 40, defaults: { /** * @property swipeMinTouches * @type {Number} * @default 1 */ swipeMinTouches: 1, /** * @property swipeMaxTouches * @type {Number} * @default 1 */ swipeMaxTouches: 1, /** * horizontal swipe velocity * @property swipeVelocityX * @type {Number} * @default 0.6 */ swipeVelocityX: 0.6, /** * vertical swipe velocity * @property swipeVelocityY * @type {Number} * @default 0.6 */ swipeVelocityY: 0.6 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { var touches = ev.touches.length, options = inst.options; // max touches if(touches < options.swipeMinTouches || touches > options.swipeMaxTouches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > options.swipeVelocityX || ev.velocityY > options.swipeVelocityY) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * @module gestures */ /** * Single tap and a double tap on a place * * @class Tap * @static */ /** * @event tap * @param {Object} ev */ /** * @event doubletap * @param {Object} ev */ /** * @param {String} name */ (function(name) { var hasMoved = false; function tapGesture(ev, inst) { var options = inst.options, current = Detection.current, prev = Detection.previous, sincePrev, didDoubleTap; switch(ev.eventType) { case EVENT_START: hasMoved = false; break; case EVENT_MOVE: hasMoved = hasMoved || (ev.distance > options.tapMaxDistance); break; case EVENT_END: if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) { // previous gesture, for the double tap since these are two different gesture detections sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp; didDoubleTap = false; // check if double tap if(prev && prev.name == name && (sincePrev && sincePrev < options.doubleTapInterval) && ev.distance < options.doubleTapDistance) { inst.trigger('doubletap', ev); didDoubleTap = true; } // do a single tap if(!didDoubleTap || options.tapAlways) { current.name = name; inst.trigger(current.name, ev); } } break; } } Hammer.gestures.Tap = { name: name, index: 100, handler: tapGesture, defaults: { /** * max time of a tap, this is for the slow tappers * @property tapMaxTime * @type {Number} * @default 250 */ tapMaxTime: 250, /** * max distance of movement of a tap, this is for the slow tappers * @property tapMaxDistance * @type {Number} * @default 10 */ tapMaxDistance: 10, /** * always trigger the `tap` event, even while double-tapping * @property tapAlways * @type {Boolean} * @default true */ tapAlways: true, /** * max distance between two taps * @property doubleTapDistance * @type {Number} * @default 20 */ doubleTapDistance: 20, /** * max time between two taps * @property doubleTapInterval * @type {Number} * @default 300 */ doubleTapInterval: 300 } }; })('tap'); /** * @module gestures */ /** * when a touch is being touched at the page * * @class Touch * @static */ /** * @event touch * @param {Object} ev */ Hammer.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 * @property preventDefault * @type {Boolean} * @default false */ preventDefault: false, /** * disable mouse events, so only touch (or pen!) input triggers events * @property preventMouse * @type {Boolean} * @default false */ preventMouse: false }, handler: function touchGesture(ev, inst) { if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.preventDefault) { ev.preventDefault(); } if(ev.eventType == EVENT_TOUCH) { inst.trigger('touch', ev); } } }; /** * @module gestures */ /** * User want to scale or rotate with 2 fingers * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the * `preventDefault` option. * * @class Transform * @static */ /** * @event transform * @param {Object} ev */ /** * @event transformstart * @param {Object} ev */ /** * @event transformend * @param {Object} ev */ /** * @event pinchin * @param {Object} ev */ /** * @event pinchout * @param {Object} ev */ /** * @event rotate * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function transformGesture(ev, inst) { switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // at least multitouch if(ev.touches.length < 2) { return; } var scaleThreshold = Math.abs(1 - ev.scale); var rotationThreshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scaleThreshold < inst.options.transformMinScale && rotationThreshold < inst.options.transformMinRotation) { return; } // we are transforming! Detection.current.name = name; // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } inst.trigger(name, ev); // basic transform event // trigger rotate event if(rotationThreshold > inst.options.transformMinRotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scaleThreshold > inst.options.transformMinScale) { inst.trigger('pinch', ev); inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev); } break; case EVENT_RELEASE: if(triggered && ev.changedLength < 2) { inst.trigger(name + 'end', ev); triggered = false; } break; } } Hammer.gestures.Transform = { name: name, index: 45, defaults: { /** * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 * @property transformMinScale * @type {Number} * @default 0.01 */ transformMinScale: 0.01, /** * rotation in degrees * @property transformMinRotation * @type {Number} * @default 1 */ transformMinRotation: 1 }, handler: transformGesture }; })('transform'); /** * @module hammer */ // AMD export if(true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return Hammer; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // commonjs export } else if(typeof module !== 'undefined' && module.exports) { module.exports = Hammer; // browser export } else { window.Hammer = Hammer; } })(window); /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * Creation of the ClusterMixin var. * * This contains all the functions the Network object can use to employ clustering */ /** * This is only called in the constructor of the network object * */ exports.startWithClustering = function() { // cluster if the data set is big this.clusterToFit(this.constants.clustering.initialMaxNodes, true); // updates the lables after clustering this.updateLabels(); // this is called here because if clusterin is disabled, the start and stabilize are called in // the setData function. if (this.stabilize) { this._stabilize(); } this.start(); }; /** * This function clusters until the initialMaxNodes has been reached * * @param {Number} maxNumberOfNodes * @param {Boolean} reposition */ exports.clusterToFit = function(maxNumberOfNodes, reposition) { var numberOfNodes = this.nodeIndices.length; var maxLevels = 50; var level = 0; // we first cluster the hubs, then we pull in the outliers, repeat while (numberOfNodes > maxNumberOfNodes && level < maxLevels) { if (level % 3 == 0) { this.forceAggregateHubs(true); this.normalizeClusterLevels(); } else { this.increaseClusterLevel(); // this also includes a cluster normalization } numberOfNodes = this.nodeIndices.length; level += 1; } // after the clustering we reposition the nodes to reduce the initial chaos if (level > 0 && reposition == true) { this.repositionNodes(); } this._updateCalculationNodes(); }; /** * This function can be called to open up a specific cluster. It is only called by * It will unpack the cluster back one level. * * @param node | Node object: cluster to open. */ exports.openCluster = function(node) { var isMovingBeforeClustering = this.moving; if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) && !(this._sector() == "default" && this.nodeIndices.length == 1)) { // this loads a new sector, loads the nodes and edges and nodeIndices of it. this._addSector(node); var level = 0; // we decluster until we reach a decent number of nodes while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) { this.decreaseClusterLevel(); level += 1; } } else { this._expandClusterNode(node,false,true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this._updateCalculationNodes(); this.updateLabels(); } // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } }; /** * This calls the updateClustes with default arguments */ exports.updateClustersDefault = function() { if (this.constants.clustering.enabled == true) { this.updateClusters(0,false,false); } }; /** * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will * be clustered with their connected node. This can be repeated as many times as needed. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets. */ exports.increaseClusterLevel = function() { this.updateClusters(-1,false,true); }; /** * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will * be unpacked if they are a cluster. This can be repeated as many times as needed. * This can be called externally (by a key-bind for instance) to look into clusters without zooming. */ exports.decreaseClusterLevel = function() { this.updateClusters(1,false,true); }; /** * This is the main clustering function. It clusters and declusters on zoom or forced * This function clusters on zoom, it can be called with a predefined zoom direction * If out, check if we can form clusters, if in, check if we can open clusters. * This function is only called from _zoom() * * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters * @param {Boolean} force | enabled or disable forcing * @param {Boolean} doNotStart | if true do not call start * */ exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; // on zoom out collapse the sector if the scale is at the level the sector was made if (this.previousScale > this.scale && zoomDirection == 0) { this._collapseSector(); } // check if we zoom in or out if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out // forming clusters when forced pulls outliers in. When not forced, the edge length of the // outer nodes determines if it is being clustered this._formClusters(force); } else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in if (force == true) { // _openClusters checks for each node if the formationScale of the cluster is smaller than // the current scale and if so, declusters. When forced, all clusters are reduced by one step this._openClusters(recursive,force); } else { // if a cluster takes up a set percentage of the active window this._openClustersBySize(); } } this._updateNodeIndexList(); // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) { this._aggregateHubs(force); this._updateNodeIndexList(); } // we now reduce chains. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out this.handleChains(); this._updateNodeIndexList(); } this.previousScale = this.scale; // rest of the update the index list, dynamic edges and labels this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place this.clusterSession += 1; // if clusters have been made, we normalize the cluster level this.normalizeClusterLevels(); } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } this._updateCalculationNodes(); }; /** * This function handles the chains. It is called on every updateClusters(). */ exports.handleChains = function() { // after clustering we check how many chains there are var chainPercentage = this._getChainFraction(); if (chainPercentage > this.constants.clustering.chainThreshold) { this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage) } }; /** * this functions starts clustering by hubs * The minimum hub threshold is set globally * * @private */ exports._aggregateHubs = function(force) { this._getHubSize(); this._formClustersByHub(force,false); }; /** * This function is fired by keypress. It forces hubs to form. * */ exports.forceAggregateHubs = function(doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; this._aggregateHubs(true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } }; /** * If a cluster takes up more than a set percentage of the screen, open the cluster * * @private */ exports._openClustersBySize = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.inView() == true) { if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { this.openCluster(node); } } } } }; /** * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it * has to be opened based on the current zoom level. * * @private */ exports._openClusters = function(recursive,force) { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; this._expandClusterNode(node,recursive,force); this._updateCalculationNodes(); } }; /** * This function checks if a node has to be opened. This is done by checking the zoom level. * If the node contains child nodes, this function is recursively called on the child nodes as well. * This recursive behaviour is optional and can be set by the recursive argument. * * @param {Node} parentNode | to check for cluster and expand * @param {Boolean} recursive | enabled or disable recursive calling * @param {Boolean} force | enabled or disable forcing * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released * @private */ exports._expandClusterNode = function(parentNode, recursive, force, openAll) { // first check if node is a cluster if (parentNode.clusterSize > 1) { // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20 if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) { openAll = true; } recursive = openAll ? true : recursive; // if the last child has been added on a smaller scale than current scale decluster if (parentNode.formationScale < this.scale || force == true) { // we will check if any of the contained child nodes should be removed from the cluster for (var containedNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) { var childNode = parentNode.containedNodes[containedNodeId]; // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that // the largest cluster is the one that comes from outside if (force == true) { if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1] || openAll) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } else { if (this._nodeInActiveArea(parentNode)) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } } } } } }; /** * ONLY CALLED FROM _expandClusterNode * * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove * the child node from the parent contained_node object and put it back into the global nodes object. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object. * * @param {Node} parentNode | the parent node * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node * @param {Boolean} recursive | This will also check if the child needs to be expanded. * With force and recursive both true, the entire cluster is unpacked * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released * @private */ exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) { var childNode = parentNode.containedNodes[containedNodeId]; // if child node has been added on smaller scale than current, kick out if (childNode.formationScale < this.scale || force == true) { // unselect all selected items this._unselectAll(); // put the child node back in the global nodes object this.nodes[containedNodeId] = childNode; // release the contained edges from this childNode back into the global edges this._releaseContainedEdges(parentNode,childNode); // reconnect rerouted edges to the childNode this._connectEdgeBackToChild(parentNode,childNode); // validate all edges in dynamicEdges this._validateEdges(parentNode); // undo the changes from the clustering operation on the parent node parentNode.options.mass -= childNode.options.mass; parentNode.clusterSize -= childNode.clusterSize; parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length; // place the child node near the parent, not at the exact same location to avoid chaos in the system childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random()); childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random()); // remove node from the list delete parentNode.containedNodes[containedNodeId]; // check if there are other childs with this clusterSession in the parent. var othersPresent = false; for (var childNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(childNodeId)) { if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) { othersPresent = true; break; } } } // if there are no others, remove the cluster session from the list if (othersPresent == false) { parentNode.clusterSessions.pop(); } this._repositionBezierNodes(childNode); // this._repositionBezierNodes(parentNode); // remove the clusterSession from the child node childNode.clusterSession = 0; // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // restart the simulation to reorganise all nodes this.moving = true; } // check if a further expansion step is possible if recursivity is enabled if (recursive == true) { this._expandClusterNode(childNode,recursive,force,openAll); } }; /** * position the bezier nodes at the center of the edges * * @param node * @private */ exports._repositionBezierNodes = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { node.dynamicEdges[i].positionBezierNode(); } }; /** * This function checks if any nodes at the end of their trees have edges below a threshold length * This function is called only from updateClusters() * forceLevelCollapse ignores the length of the edge and collapses one level * This means that a node with only one edge will be clustered with its connected node * * @private * @param {Boolean} force */ exports._formClusters = function(force) { if (force == false) { this._formClustersByZoom(); } else { this._forceClustersByZoom(); } }; /** * This function handles the clustering by zooming out, this is based on a minimum edge distance * * @private */ exports._formClustersByZoom = function() { var dx,dy,length, minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; // check if any edges are shorter than minLength and start the clustering // the clustering favours the node with the larger mass for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { // first check which node is larger var parentNode = edge.from; var childNode = edge.to; if (edge.to.options.mass > edge.from.options.mass) { parentNode = edge.to; childNode = edge.from; } if (childNode.dynamicEdgesLength == 1) { this._addToCluster(parentNode,childNode,false); } else if (parentNode.dynamicEdgesLength == 1) { this._addToCluster(childNode,parentNode,false); } } } } } } }; /** * This function forces the network to cluster all nodes with only one connecting edge to their * connected node. * * @private */ exports._forceClustersByZoom = function() { for (var nodeId in this.nodes) { // another node could have absorbed this child. if (this.nodes.hasOwnProperty(nodeId)) { var childNode = this.nodes[nodeId]; // the edges can be swallowed by another decrease if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) { var edge = childNode.dynamicEdges[0]; var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId]; // group to the largest node if (childNode.id != parentNode.id) { if (parentNode.options.mass > childNode.options.mass) { this._addToCluster(parentNode,childNode,true); } else { this._addToCluster(childNode,parentNode,true); } } } } } }; /** * To keep the nodes of roughly equal size we normalize the cluster levels. * This function clusters a node to its smallest connected neighbour. * * @param node * @private */ exports._clusterToSmallestNeighbour = function(node) { var smallestNeighbour = -1; var smallestNeighbourNode = null; for (var i = 0; i < node.dynamicEdges.length; i++) { if (node.dynamicEdges[i] !== undefined) { var neighbour = null; if (node.dynamicEdges[i].fromId != node.id) { neighbour = node.dynamicEdges[i].from; } else if (node.dynamicEdges[i].toId != node.id) { neighbour = node.dynamicEdges[i].to; } if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) { smallestNeighbour = neighbour.clusterSessions.length; smallestNeighbourNode = neighbour; } } } if (neighbour != null && this.nodes[neighbour.id] !== undefined) { this._addToCluster(neighbour, node, true); } }; /** * This function forms clusters from hubs, it loops over all nodes * * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @private */ exports._formClustersByHub = function(force, onlyEqual) { // we loop over all nodes in the list for (var nodeId in this.nodes) { // we check if it is still available since it can be used by the clustering in this loop if (this.nodes.hasOwnProperty(nodeId)) { this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual); } } }; /** * This function forms a cluster from a specific preselected hub node * * @param {Node} hubNode | the node we will cluster as a hub * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @param {Number} [absorptionSizeOffset] | * @private */ exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) { if (absorptionSizeOffset === undefined) { absorptionSizeOffset = 0; } // we decide if the node is a hub if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) || (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) { // initialize variables var dx,dy,length; var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; var allowCluster = false; // we create a list of edges because the dynamicEdges change over the course of this loop var edgesIdarray = []; var amountOfInitialEdges = hubNode.dynamicEdges.length; for (var j = 0; j < amountOfInitialEdges; j++) { edgesIdarray.push(hubNode.dynamicEdges[j].id); } // if the hub clustering is not forces, we check if one of the edges connected // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold if (force == false) { allowCluster = false; for (j = 0; j < amountOfInitialEdges; j++) { var edge = this.edges[edgesIdarray[j]]; if (edge !== undefined) { if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { allowCluster = true; break; } } } } } } // start the clustering if allowed if ((!force && allowCluster) || force) { // we loop over all edges INITIALLY connected to this hub for (j = 0; j < amountOfInitialEdges; j++) { edge = this.edges[edgesIdarray[j]]; // the edge can be clustered by this function in a previous loop if (edge !== undefined) { var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId]; // we do not want hubs to merge with other hubs nor do we want to cluster itself. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) && (childNode.id != hubNode.id)) { this._addToCluster(hubNode,childNode,force); } } } } } }; /** * This function adds the child node to the parent node, creating a cluster if it is not already. * * @param {Node} parentNode | this is the node that will house the child node * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse * @private */ exports._addToCluster = function(parentNode, childNode, force) { // join child node in the parent node parentNode.containedNodes[childNode.id] = childNode; // manage all the edges connected to the child and parent nodes for (var i = 0; i < childNode.dynamicEdges.length; i++) { var edge = childNode.dynamicEdges[i]; if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode this._addToContainedEdges(parentNode,childNode,edge); } else { this._connectEdgeToCluster(parentNode,childNode,edge); } } // a contained node has no dynamic edges. childNode.dynamicEdges = []; // remove circular edges from clusters this._containCircularEdgesFromNode(parentNode,childNode); // remove the childNode from the global nodes object delete this.nodes[childNode.id]; // update the properties of the child and parent var massBefore = parentNode.options.mass; childNode.clusterSession = this.clusterSession; parentNode.options.mass += childNode.options.mass; parentNode.clusterSize += childNode.clusterSize; parentNode.options.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); // keep track of the clustersessions so we can open the cluster up as it has been formed. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) { parentNode.clusterSessions.push(this.clusterSession); } // forced clusters only open from screen size and double tap if (force == true) { // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3); parentNode.formationScale = 0; } else { parentNode.formationScale = this.scale; // The latest child has been added on this scale } // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // set the pop-out scale for the childnode parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale; // nullify the movement velocity of the child, this is to avoid hectic behaviour childNode.clearVelocity(); // the mass has altered, preservation of energy dictates the velocity to be updated parentNode.updateVelocity(massBefore); // restart the simulation to reorganise all nodes this.moving = true; }; /** * This function will apply the changes made to the remainingEdges during the formation of the clusters. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree. * It has to be called if a level is collapsed. It is called by _formClusters(). * @private */ exports._updateDynamicEdges = function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; node.dynamicEdgesLength = node.dynamicEdges.length; // this corrects for multiple edges pointing at the same other node var correction = 0; if (node.dynamicEdgesLength > 1) { for (var j = 0; j < node.dynamicEdgesLength - 1; j++) { var edgeToId = node.dynamicEdges[j].toId; var edgeFromId = node.dynamicEdges[j].fromId; for (var k = j+1; k < node.dynamicEdgesLength; k++) { if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) || (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) { correction += 1; } } } } node.dynamicEdgesLength -= correction; } }; /** * This adds an edge from the childNode to the contained edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ exports._addToContainedEdges = function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) { parentNode.containedEdges[childNode.id] = [] } // add this edge to the list parentNode.containedEdges[childNode.id].push(edge); // remove the edge from the global edges object delete this.edges[edge.id]; // remove the edge from the parent object for (var i = 0; i < parentNode.dynamicEdges.length; i++) { if (parentNode.dynamicEdges[i].id == edge.id) { parentNode.dynamicEdges.splice(i,1); break; } } }; /** * This function connects an edge that was connected to a child node to the parent node. * It keeps track of which nodes it has been connected to with the originalId array. * * @param {Node} parentNode | Node object * @param {Node} childNode | Node object * @param {Edge} edge | Edge object * @private */ exports._connectEdgeToCluster = function(parentNode, childNode, edge) { // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } else { if (edge.toId == childNode.id) { // edge connected to other node on the "to" side edge.originalToId.push(childNode.id); edge.to = parentNode; edge.toId = parentNode.id; } else { // edge connected to other node with the "from" side edge.originalFromId.push(childNode.id); edge.from = parentNode; edge.fromId = parentNode.id; } this._addToReroutedEdges(parentNode,childNode,edge); } }; /** * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain * these edges inside of the cluster. * * @param parentNode * @param childNode * @private */ exports._containCircularEdgesFromNode = function(parentNode, childNode) { // manage all the edges connected to the child and parent nodes for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } } }; /** * This adds an edge from the childNode to the rerouted edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ exports._addToReroutedEdges = function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode // we store the edge in the rerouted edges so we can restore it when the cluster pops open if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) { parentNode.reroutedEdges[childNode.id] = []; } parentNode.reroutedEdges[childNode.id].push(edge); // this edge becomes part of the dynamicEdges of the cluster node parentNode.dynamicEdges.push(edge); }; /** * This function connects an edge that was connected to a cluster node back to the child node. * * @param parentNode | Node object * @param childNode | Node object * @private */ exports._connectEdgeBackToChild = function(parentNode, childNode) { if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) { for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) { var edge = parentNode.reroutedEdges[childNode.id][i]; if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) { edge.originalFromId.pop(); edge.fromId = childNode.id; edge.from = childNode; } else { edge.originalToId.pop(); edge.toId = childNode.id; edge.to = childNode; } // append this edge to the list of edges connecting to the childnode childNode.dynamicEdges.push(edge); // remove the edge from the parent object for (var j = 0; j < parentNode.dynamicEdges.length; j++) { if (parentNode.dynamicEdges[j].id == edge.id) { parentNode.dynamicEdges.splice(j,1); break; } } } // remove the entry from the rerouted edges delete parentNode.reroutedEdges[childNode.id]; } }; /** * When loops are clustered, an edge can be both in the rerouted array and the contained array. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the * parentNode * * @param parentNode | Node object * @private */ exports._validateEdges = function(parentNode) { for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; if (parentNode.id != edge.toId && parentNode.id != edge.fromId) { parentNode.dynamicEdges.splice(i,1); } } }; /** * This function released the contained edges back into the global domain and puts them back into the * dynamic edges of both parent and child. * * @param {Node} parentNode | * @param {Node} childNode | * @private */ exports._releaseContainedEdges = function(parentNode, childNode) { for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) { var edge = parentNode.containedEdges[childNode.id][i]; // put the edge back in the global edges object this.edges[edge.id] = edge; // put the edge back in the dynamic edges of the child and parent childNode.dynamicEdges.push(edge); parentNode.dynamicEdges.push(edge); } // remove the entry from the contained edges delete parentNode.containedEdges[childNode.id]; }; // ------------------- UTILITY FUNCTIONS ---------------------------- // /** * This updates the node labels for all nodes (for debugging purposes) */ exports.updateLabels = function() { var nodeId; // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.clusterSize > 1) { node.label = "[".concat(String(node.clusterSize),"]"); } } } // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.clusterSize == 1) { if (node.originalLabel !== undefined) { node.label = node.originalLabel; } else { node.label = String(node.id); } } } } // /* Debug Override */ // for (nodeId in this.nodes) { // if (this.nodes.hasOwnProperty(nodeId)) { // node = this.nodes[nodeId]; // node.label = String(node.level); // } // } }; /** * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes * if the rest of the nodes are already a few cluster levels in. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not * clustered enough to the clusterToSmallestNeighbours function. */ exports.normalizeClusterLevels = function() { var maxLevel = 0; var minLevel = 1e9; var clusterLevel = 0; var nodeId; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { clusterLevel = this.nodes[nodeId].clusterSessions.length; if (maxLevel < clusterLevel) {maxLevel = clusterLevel;} if (minLevel > clusterLevel) {minLevel = clusterLevel;} } } if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) { var amountOfNodes = this.nodeIndices.length; var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].clusterSessions.length < targetLevel) { this._clusterToSmallestNeighbour(this.nodes[nodeId]); } } } this._updateNodeIndexList(); this._updateDynamicEdges(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } } }; /** * This function determines if the cluster we want to decluster is in the active area * this means around the zoom center * * @param {Node} node * @returns {boolean} * @private */ exports._nodeInActiveArea = function(node) { return ( Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale && Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale ) }; /** * This is an adaptation of the original repositioning function. This is called if the system is clustered initially * It puts large clusters away from the center and randomizes the order. * */ exports.repositionNodes = function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if ((node.xFixed == false || node.yFixed == false)) { var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.options.mass); var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} this._repositionBezierNodes(node); } } }; /** * We determine how many connections denote an important hub. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) * * @private */ exports._getHubSize = function() { var average = 0; var averageSquared = 0; var hubCounter = 0; var largestHub = 0; for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if (node.dynamicEdgesLength > largestHub) { largestHub = node.dynamicEdgesLength; } average += node.dynamicEdgesLength; averageSquared += Math.pow(node.dynamicEdgesLength,2); hubCounter += 1; } average = average / hubCounter; averageSquared = averageSquared / hubCounter; var variance = averageSquared - Math.pow(average,2); var standardDeviation = Math.sqrt(variance); this.hubThreshold = Math.floor(average + 2*standardDeviation); // always have at least one to cluster if (this.hubThreshold > largestHub) { this.hubThreshold = largestHub; } // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation); // console.log("hubThreshold:",this.hubThreshold); }; /** * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce * @private */ exports._reduceAmountOfChains = function(fraction) { this.hubThreshold = 2; var reduceAmount = Math.floor(this.nodeIndices.length * fraction); for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { if (reduceAmount > 0) { this._formClusterFromHub(this.nodes[nodeId],true,true,1); reduceAmount -= 1; } } } } }; /** * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @private */ exports._getChainFraction = function() { var chains = 0; var total = 0; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { chains += 1; } total += 1; } } return chains/total; }; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * Creation of the SectorMixin var. * * This contains all the functions the Network object can use to employ the sector system. * The sector system is always used by Network, though the benefits only apply to the use of clustering. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges. */ /** * This function is only called by the setData function of the Network object. * This loads the global references into the active sector. This initializes the sector. * * @private */ exports._putDataInSector = function() { this.sectors["active"][this._sector()].nodes = this.nodes; this.sectors["active"][this._sector()].edges = this.edges; this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices; }; /** * /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied (active) sector. If a type is defined, do the specific type * * @param {String} sectorId * @param {String} [sectorType] | "active" or "frozen" * @private */ exports._switchToSector = function(sectorId, sectorType) { if (sectorType === undefined || sectorType == "active") { this._switchToActiveSector(sectorId); } else { this._switchToFrozenSector(sectorId); } }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @param sectorId * @private */ exports._switchToActiveSector = function(sectorId) { this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"]; this.nodes = this.sectors["active"][sectorId]["nodes"]; this.edges = this.sectors["active"][sectorId]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @private */ exports._switchToSupportSector = function() { this.nodeIndices = this.sectors["support"]["nodeIndices"]; this.nodes = this.sectors["support"]["nodes"]; this.edges = this.sectors["support"]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied frozen sector. * * @param sectorId * @private */ exports._switchToFrozenSector = function(sectorId) { this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"]; this.nodes = this.sectors["frozen"][sectorId]["nodes"]; this.edges = this.sectors["frozen"][sectorId]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the currently active sector. * * @private */ exports._loadLatestSector = function() { this._switchToSector(this._sector()); }; /** * This function returns the currently active sector Id * * @returns {String} * @private */ exports._sector = function() { return this.activeSector[this.activeSector.length-1]; }; /** * This function returns the previously active sector Id * * @returns {String} * @private */ exports._previousSector = function() { if (this.activeSector.length > 1) { return this.activeSector[this.activeSector.length-2]; } else { throw new TypeError('there are not enough sectors in the this.activeSector array.'); } }; /** * We add the active sector at the end of the this.activeSector array * This ensures it is the currently active sector returned by _sector() and it reaches the top * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack. * * @param newId * @private */ exports._setActiveSector = function(newId) { this.activeSector.push(newId); }; /** * We remove the currently active sector id from the active sector stack. This happens when * we reactivate the previously active sector * * @private */ exports._forgetLastSector = function() { this.activeSector.pop(); }; /** * This function creates a new active sector with the supplied newId. This newId * is the expanding node id. * * @param {String} newId | Id of the new active sector * @private */ exports._createNewSector = function(newId) { // create the new sector this.sectors["active"][newId] = {"nodes":{}, "edges":{}, "nodeIndices":[], "formationScale": this.scale, "drawingNode": undefined}; // create the new sector render node. This gives visual feedback that you are in a new sector. this.sectors["active"][newId]['drawingNode'] = new Node( {id:newId, color: { background: "#eaefef", border: "495c5e" } },{},{},this.constants); this.sectors["active"][newId]['drawingNode'].clusterSize = 2; }; /** * This function removes the currently active sector. This is called when we create a new * active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ exports._deleteActiveSector = function(sectorId) { delete this.sectors["active"][sectorId]; }; /** * This function removes the currently active sector. This is called when we reactivate * the previously active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ exports._deleteFrozenSector = function(sectorId) { delete this.sectors["frozen"][sectorId]; }; /** * Freezing an active sector means moving it from the "active" object to the "frozen" object. * We copy the references, then delete the active entree. * * @param sectorId * @private */ exports._freezeSector = function(sectorId) { // we move the set references from the active to the frozen stack. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId]; // we have moved the sector data into the frozen set, we now remove it from the active set this._deleteActiveSector(sectorId); }; /** * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen" * object to the "active" object. * * @param sectorId * @private */ exports._activateSector = function(sectorId) { // we move the set references from the frozen to the active stack. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId]; // we have moved the sector data into the active set, we now remove it from the frozen stack this._deleteFrozenSector(sectorId); }; /** * This function merges the data from the currently active sector with a frozen sector. This is used * in the process of reverting back to the previously active sector. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it * upon the creation of a new active sector. * * @param sectorId * @private */ exports._mergeThisWithFrozen = function(sectorId) { // copy all nodes for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId]; } } // copy all edges (if not fully clustered, else there are no edges) for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId]; } } // merge the nodeIndices for (var i = 0; i < this.nodeIndices.length; i++) { this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]); } }; /** * This clusters the sector to one cluster. It was a single cluster before this process started so * we revert to that state. The clusterToFit function with a maximum size of 1 node does this. * * @private */ exports._collapseThisToSingleCluster = function() { this.clusterToFit(1,false); }; /** * We create a new active sector from the node that we want to open. * * @param node * @private */ exports._addSector = function(node) { // this is the currently active sector var sector = this._sector(); // // this should allow me to select nodes from a frozen set. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) { // console.log("the node is part of the active sector"); // } // else { // console.log("I dont know what the fuck happened!!"); // } // when we switch to a new sector, we remove the node that will be expanded from the current nodes list. delete this.nodes[node.id]; var unqiueIdentifier = util.randomUUID(); // we fully freeze the currently active sector this._freezeSector(sector); // we create a new active sector. This sector has the Id of the node to ensure uniqueness this._createNewSector(unqiueIdentifier); // we add the active sector to the sectors array to be able to revert these steps later on this._setActiveSector(unqiueIdentifier); // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier this._switchToSector(this._sector()); // finally we add the node we removed from our previous active sector to the new active sector this.nodes[node.id] = node; }; /** * We close the sector that is currently open and revert back to the one before. * If the active sector is the "default" sector, nothing happens. * * @private */ exports._collapseSector = function() { // the currently active sector var sector = this._sector(); // we cannot collapse the default sector if (sector != "default") { if ((this.nodeIndices.length == 1) || (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { var previousSector = this._previousSector(); // we collapse the sector back to a single cluster this._collapseThisToSingleCluster(); // we move the remaining nodes, edges and nodeIndices to the previous sector. // This previous sector is the one we will reactivate this._mergeThisWithFrozen(previousSector); // the previously active (frozen) sector now has all the data from the currently active sector. // we can now delete the active sector. this._deleteActiveSector(sector); // we activate the previously active (and currently frozen) sector. this._activateSector(previousSector); // we load the references from the newly active sector into the global references this._switchToSector(previousSector); // we forget the previously active sector because we reverted to the one before this._forgetLastSector(); // finally, we update the node index list. this._updateNodeIndexList(); // we refresh the list with calulation nodes and calculation node indices. this._updateCalculationNodes(); } } }; /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllActiveSectors = function(runFunction,argument) { var returnValues = []; if (argument === undefined) { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); returnValues.push( this[runFunction]() ); } } } else { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { returnValues.push( this[runFunction](args[0],args[1]) ); } else { returnValues.push( this[runFunction](argument) ); } } } } // we revert the global references back to our active sector this._loadLatestSector(); return returnValues; }; /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInSupportSector = function(runFunction,argument) { var returnValues = false; if (argument === undefined) { this._switchToSupportSector(); returnValues = this[runFunction](); } else { this._switchToSupportSector(); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { returnValues = this[runFunction](args[0],args[1]); } else { returnValues = this[runFunction](argument); } } // we revert the global references back to our active sector this._loadLatestSector(); return returnValues; }; /** * This runs a function in all frozen sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllFrozenSectors = function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } this._loadLatestSector(); }; /** * This runs a function in all sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllSectors = function(runFunction,argument) { var args = Array.prototype.splice.call(arguments, 1); if (argument === undefined) { this._doInAllActiveSectors(runFunction); this._doInAllFrozenSectors(runFunction); } else { if (args.length > 1) { this._doInAllActiveSectors(runFunction,args[0],args[1]); this._doInAllFrozenSectors(runFunction,args[0],args[1]); } else { this._doInAllActiveSectors(runFunction,argument); this._doInAllFrozenSectors(runFunction,argument); } } }; /** * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it. * * @private */ exports._clearNodeIndexList = function() { var sector = this._sector(); this.sectors["active"][sector]["nodeIndices"] = []; this.nodeIndices = this.sectors["active"][sector]["nodeIndices"]; }; /** * Draw the encompassing sector node * * @param ctx * @param sectorType * @private */ exports._drawSectorNodes = function(ctx,sectorType) { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var sector in this.sectors[sectorType]) { if (this.sectors[sectorType].hasOwnProperty(sector)) { if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) { this._switchToSector(sector,sectorType); minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.resize(ctx); if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;} if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;} if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;} if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;} } } node = this.sectors[sectorType][sector]["drawingNode"]; node.x = 0.5 * (maxX + minX); node.y = 0.5 * (maxY + minY); node.width = 2 * (node.x - minX); node.height = 2 * (node.y - minY); node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2)); node.setScale(this.scale); node._drawCircle(ctx); } } } }; exports._drawAllSectorNodes = function(ctx) { this._drawSectorNodes(ctx,"frozen"); this._drawSectorNodes(ctx,"active"); this._loadLatestSector(); }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var Node = __webpack_require__(37); /** * This function can be called from the _doInAllSectors function * * @param object * @param overlappingNodes * @private */ exports._getNodesOverlappingWith = function(object, overlappingNodes) { var nodes = this.nodes; for (var nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { if (nodes[nodeId].isOverlappingWith(object)) { overlappingNodes.push(nodeId); } } } }; /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getAllNodesOverlappingWith = function (object) { var overlappingNodes = []; this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes); return overlappingNodes; }; /** * Return a position object in canvasspace from a single point in screenspace * * @param pointer * @returns {{left: number, top: number, right: number, bottom: number}} * @private */ exports._pointerToPositionObject = function(pointer) { var x = this._XconvertDOMtoCanvas(pointer.x); var y = this._YconvertDOMtoCanvas(pointer.y); return { left: x, top: y, right: x, bottom: y }; }; /** * Get the top node at the a specific point (like a click) * * @param {{x: Number, y: Number}} pointer * @return {Node | null} node * @private */ exports._getNodeAt = function (pointer) { // we first check if this is an navigation controls element var positionObject = this._pointerToPositionObject(pointer); var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); // if there are overlapping nodes, select the last one, this is the // one which is drawn on top of the others if (overlappingNodes.length > 0) { return this.nodes[overlappingNodes[overlappingNodes.length - 1]]; } else { return null; } }; /** * retrieve all edges overlapping with given object, selector is around center * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getEdgesOverlappingWith = function (object, overlappingEdges) { var edges = this.edges; for (var edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { if (edges[edgeId].isOverlappingWith(object)) { overlappingEdges.push(edgeId); } } } }; /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getAllEdgesOverlappingWith = function (object) { var overlappingEdges = []; this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges); return overlappingEdges; }; /** * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences. * * @param pointer * @returns {null} * @private */ exports._getEdgeAt = function(pointer) { var positionObject = this._pointerToPositionObject(pointer); var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); if (overlappingEdges.length > 0) { return this.edges[overlappingEdges[overlappingEdges.length - 1]]; } else { return null; } }; /** * Add object to the selection array. * * @param obj * @private */ exports._addToSelection = function(obj) { if (obj instanceof Node) { this.selectionObj.nodes[obj.id] = obj; } else { this.selectionObj.edges[obj.id] = obj; } }; /** * Add object to the selection array. * * @param obj * @private */ exports._addToHover = function(obj) { if (obj instanceof Node) { this.hoverObj.nodes[obj.id] = obj; } else { this.hoverObj.edges[obj.id] = obj; } }; /** * Remove a single option from selection. * * @param {Object} obj * @private */ exports._removeFromSelection = function(obj) { if (obj instanceof Node) { delete this.selectionObj.nodes[obj.id]; } else { delete this.selectionObj.edges[obj.id]; } }; /** * Unselect all. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._unselectAll = function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { this.selectionObj.nodes[nodeId].unselect(); } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { this.selectionObj.edges[edgeId].unselect(); } } this.selectionObj = {nodes:{},edges:{}}; if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * Unselect all clusters. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._unselectClusters = function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { this.selectionObj.nodes[nodeId].unselect(); this._removeFromSelection(this.selectionObj.nodes[nodeId]); } } } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * return the number of selected nodes * * @returns {number} * @private */ exports._getSelectedNodeCount = function() { var count = 0; for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } return count; }; /** * return the selected node * * @returns {number} * @private */ exports._getSelectedNode = function() { for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { return this.selectionObj.nodes[nodeId]; } } return null; }; /** * return the selected edge * * @returns {number} * @private */ exports._getSelectedEdge = function() { for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { return this.selectionObj.edges[edgeId]; } } return null; }; /** * return the number of selected edges * * @returns {number} * @private */ exports._getSelectedEdgeCount = function() { var count = 0; for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }; /** * return the number of selected objects. * * @returns {number} * @private */ exports._getSelectedObjectCount = function() { var count = 0; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }; /** * Check if anything is selected * * @returns {boolean} * @private */ exports._selectionIsEmpty = function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { return false; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { return false; } } return true; }; /** * check if one of the selected nodes is a cluster. * * @returns {boolean} * @private */ exports._clusterInSelection = function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { return true; } } } return false; }; /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._selectConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.select(); this._addToSelection(edge); } }; /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._hoverConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.hover = true; this._addToHover(edge); } }; /** * unselect the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._unselectConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.unselect(); this._removeFromSelection(edge); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @param {Boolean} append * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._selectObject = function(object, append, doNotTrigger, highlightEdges) { if (doNotTrigger === undefined) { doNotTrigger = false; } if (highlightEdges === undefined) { highlightEdges = true; } if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) { this._unselectAll(true); } if (object.selected == false) { object.select(); this._addToSelection(object); if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) { this._selectConnectedEdges(object); } } else { object.unselect(); this._removeFromSelection(object); } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ exports._blurObject = function(object) { if (object.hover == true) { object.hover = false; this.emit("blurNode",{node:object.id}); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ exports._hoverObject = function(object) { if (object.hover == false) { object.hover = true; this._addToHover(object); if (object instanceof Node) { this.emit("hoverNode",{node:object.id}); } } if (object instanceof Node) { this._hoverConnectedEdges(object); } }; /** * handles the selection part of the touch, only for navigation controls elements; * Touch is triggered before tap, also before hold. Hold triggers after a while. * This is the most responsive solution * * @param {Object} pointer * @private */ exports._handleTouch = function(pointer) { }; /** * handles the selection part of the tap; * * @param {Object} pointer * @private */ exports._handleTap = function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,false); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,false); } else { this._unselectAll(); } } this.emit("click", this.getSelection()); this._redraw(); }; /** * handles the selection part of the double tap and opens a cluster if needed * * @param {Object} pointer * @private */ exports._handleDoubleTap = function(pointer) { var node = this._getNodeAt(pointer); if (node != null && node !== undefined) { // we reset the areaCenter here so the opening of the node will occur this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this.openCluster(node); } this.emit("doubleClick", this.getSelection()); }; /** * Handle the onHold selection part * * @param pointer * @private */ exports._handleOnHold = function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,true); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,true); } } this._redraw(); }; /** * handle the onRelease event. These functions are here for the navigation controls module. * * @private */ exports._handleOnRelease = function(pointer) { }; /** * * retrieve the currently selected objects * @return {{nodes: Array.<String>, edges: Array.<String>}} selection */ exports.getSelection = function() { var nodeIds = this.getSelectedNodes(); var edgeIds = this.getSelectedEdges(); return {nodes:nodeIds, edges:edgeIds}; }; /** * * retrieve the currently selected nodes * @return {String[]} selection An array with the ids of the * selected nodes. */ exports.getSelectedNodes = function() { var idArray = []; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { idArray.push(nodeId); } } return idArray }; /** * * retrieve the currently selected edges * @return {Array} selection An array with the ids of the * selected nodes. */ exports.getSelectedEdges = function() { var idArray = []; for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { idArray.push(edgeId); } } return idArray; }; /** * select zero or more nodes * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ exports.setSelection = function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true); } console.log("setSelection is deprecated. Please use selectNodes instead.") this.redraw(); }; /** * select zero or more nodes with the option to highlight edges * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. * @param {boolean} [highlightEdges] */ exports.selectNodes = function(selection, highlightEdges) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true,highlightEdges); } this.redraw(); }; /** * select zero or more edges * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ exports.selectEdges = function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var edge = this.edges[id]; if (!edge) { throw new RangeError('Edge with id "' + id + '" not found'); } this._selectObject(edge,true,true,highlightEdges); } this.redraw(); }; /** * Validate the selection: remove ids of nodes which no longer exist * @private */ exports._updateSelection = function () { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (!this.nodes.hasOwnProperty(nodeId)) { delete this.selectionObj.nodes[nodeId]; } } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { if (!this.edges.hasOwnProperty(edgeId)) { delete this.selectionObj.edges[edgeId]; } } } }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Node = __webpack_require__(37); var Edge = __webpack_require__(34); /** * clears the toolbar div element of children * * @private */ exports._clearManipulatorBar = function() { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } }; /** * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore * these functions to their original functionality, we saved them in this.cachedFunctions. * This function restores these functions to their original function. * * @private */ exports._restoreOverloadedFunctions = function() { for (var functionName in this.cachedFunctions) { if (this.cachedFunctions.hasOwnProperty(functionName)) { this[functionName] = this.cachedFunctions[functionName]; } } }; /** * Enable or disable edit-mode. * * @private */ exports._toggleEditMode = function() { this.editMode = !this.editMode; var toolbar = document.getElementById("network-manipulationDiv"); var closeDiv = document.getElementById("network-manipulation-closeDiv"); var editModeDiv = document.getElementById("network-manipulation-editMode"); if (this.editMode == true) { toolbar.style.display="block"; closeDiv.style.display="block"; editModeDiv.style.display="none"; closeDiv.onclick = this._toggleEditMode.bind(this); } else { toolbar.style.display="none"; closeDiv.style.display="none"; editModeDiv.style.display="block"; closeDiv.onclick = null; } this._createManipulatorBar() }; /** * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. * * @private */ exports._createManipulatorBar = function() { // remove bound functions if (this.boundFunction) { this.off('select', this.boundFunction); } var locale = this.constants.locales[this.constants.locale]; if (this.edgeBeingEdited !== undefined) { this.edgeBeingEdited._disableControlNodes(); this.edgeBeingEdited = undefined; this.selectedControlNode = null; this.controlNodesActive = false; } // restore overloaded functions this._restoreOverloadedFunctions(); // resume calculation this.freezeSimulation = false; // reset global variables this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.editMode == true) { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } // add the icons to the manipulator div this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI add' id='network-manipulate-addNode'>" + "<span class='network-manipulationLabel'>"+locale['addNode'] +"</span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI connect' id='network-manipulate-connectNode'>" + "<span class='network-manipulationLabel'>"+locale['addEdge'] +"</span></span>"; if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI edit' id='network-manipulate-editNode'>" + "<span class='network-manipulationLabel'>"+locale['editNode'] +"</span></span>"; } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI edit' id='network-manipulate-editEdge'>" + "<span class='network-manipulationLabel'>"+locale['editEdge'] +"</span></span>"; } if (this._selectionIsEmpty() == false) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI delete' id='network-manipulate-delete'>" + "<span class='network-manipulationLabel'>"+locale['del'] +"</span></span>"; } // bind the icons var addNodeButton = document.getElementById("network-manipulate-addNode"); addNodeButton.onclick = this._createAddNodeToolbar.bind(this); var addEdgeButton = document.getElementById("network-manipulate-connectNode"); addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this); if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { var editButton = document.getElementById("network-manipulate-editNode"); editButton.onclick = this._editNode.bind(this); } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { var editButton = document.getElementById("network-manipulate-editEdge"); editButton.onclick = this._createEditEdgeToolbar.bind(this); } if (this._selectionIsEmpty() == false) { var deleteButton = document.getElementById("network-manipulate-delete"); deleteButton.onclick = this._deleteSelected.bind(this); } var closeDiv = document.getElementById("network-manipulation-closeDiv"); closeDiv.onclick = this._toggleEditMode.bind(this); this.boundFunction = this._createManipulatorBar.bind(this); this.on('select', this.boundFunction); } else { this.editModeDiv.innerHTML = "" + "<span class='network-manipulationUI edit editmode' id='network-manipulate-editModeButton'>" + "<span class='network-manipulationLabel'>" + locale['edit'] + "</span></span>"; var editModeButton = document.getElementById("network-manipulate-editModeButton"); editModeButton.onclick = this._toggleEditMode.bind(this); } }; /** * Create the toolbar for adding Nodes * * @private */ exports._createAddNodeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); if (this.boundFunction) { this.off('select', this.boundFunction); } var locale = this.constants.locales[this.constants.locale]; // create the toolbar contents this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + locale['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + locale['addDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._addNode.bind(this); this.on('select', this.boundFunction); }; /** * create the toolbar to connect nodes * * @private */ exports._createAddEdgeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); this._unselectAll(true); this.freezeSimulation = true; var locale = this.constants.locales[this.constants.locale]; if (this.boundFunction) { this.off('select', this.boundFunction); } this._unselectAll(); this.forceAppendSelection = false; this.blockConnectingEdgeSelection = true; this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + locale['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + locale['edgeDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._handleConnect.bind(this); this.on('select', this.boundFunction); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this.cachedFunctions["_handleDragStart"] = this._handleDragStart; this.cachedFunctions["_handleDragEnd"] = this._handleDragEnd; this._handleTouch = this._handleConnect; this._handleOnRelease = function () {}; this._handleDragStart = function () {}; this._handleDragEnd = this._finishConnect; // redraw to show the unselect this._redraw(); }; /** * create the toolbar to edit edges * * @private */ exports._createEditEdgeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); this.controlNodesActive = true; if (this.boundFunction) { this.off('select', this.boundFunction); } this.edgeBeingEdited = this._getSelectedEdge(); this.edgeBeingEdited._enableControlNodes(); var locale = this.constants.locales[this.constants.locale]; this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + locale['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + locale['editEdgeDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this.cachedFunctions["_handleTap"] = this._handleTap; this.cachedFunctions["_handleDragStart"] = this._handleDragStart; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleTouch = this._selectControlNode; this._handleTap = function () {}; this._handleOnDrag = this._controlNodeDrag; this._handleDragStart = function () {} this._handleOnRelease = this._releaseControlNode; // redraw to show the unselect this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._selectControlNode = function(pointer) { this.edgeBeingEdited.controlNodes.from.unselect(); this.edgeBeingEdited.controlNodes.to.unselect(); this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y)); if (this.selectedControlNode !== null) { this.selectedControlNode.select(); this.freezeSimulation = true; } this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._controlNodeDrag = function(event) { var pointer = this._getPointer(event.gesture.center); if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) { this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x); this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y); } this._redraw(); }; exports._releaseControlNode = function(pointer) { var newNode = this._getNodeAt(pointer); if (newNode != null) { if (this.edgeBeingEdited.controlNodes.from.selected == true) { this._editEdge(newNode.id, this.edgeBeingEdited.to.id); this.edgeBeingEdited.controlNodes.from.unselect(); } if (this.edgeBeingEdited.controlNodes.to.selected == true) { this._editEdge(this.edgeBeingEdited.from.id, newNode.id); this.edgeBeingEdited.controlNodes.to.unselect(); } } else { this.edgeBeingEdited._restoreControlNodes(); } this.freezeSimulation = false; this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._handleConnect = function(pointer) { if (this._getSelectedNodeCount() == 0) { var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert(this.constants.locales[this.constants.locale]['createEdgeError']) } else { this._selectObject(node,false); var supportNodes = this.sectors['support']['nodes']; // create a node the temporary line can look at supportNodes['targetNode'] = new Node({id:'targetNode'},{},{},this.constants); var targetNode = supportNodes['targetNode']; targetNode.x = node.x; targetNode.y = node.y; // create a temporary edge this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:targetNode.id}, this, this.constants); var connectionEdge = this.edges['connectionEdge']; connectionEdge.from = node; connectionEdge.connected = true; connectionEdge.options.smoothCurves = {enabled: true, dynamic: false, type: "continuous", roundness: 0.5 }; connectionEdge.selected = true; connectionEdge.to = targetNode; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleOnDrag = function(event) { var pointer = this._getPointer(event.gesture.center); var connectionEdge = this.edges['connectionEdge']; connectionEdge.to.x = this._XconvertDOMtoCanvas(pointer.x); connectionEdge.to.y = this._YconvertDOMtoCanvas(pointer.y); }; this.moving = true; this.start(); } } } }; exports._finishConnect = function(event) { if (this._getSelectedNodeCount() == 1) { var pointer = this._getPointer(event.gesture.center); // restore the drag function this._handleOnDrag = this.cachedFunctions["_handleOnDrag"]; delete this.cachedFunctions["_handleOnDrag"]; // remember the edge id var connectFromId = this.edges['connectionEdge'].fromId; // remove the temporary nodes and edge delete this.edges['connectionEdge']; delete this.sectors['support']['nodes']['targetNode']; delete this.sectors['support']['nodes']['targetViaNode']; var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert(this.constants.locales[this.constants.locale]["createEdgeError"]) } else { this._createEdge(connectFromId,node.id); this._createManipulatorBar(); } } this._unselectAll(); } }; /** * Adds a node on the specified location */ exports._addNode = function() { if (this._selectionIsEmpty() && this.editMode == true) { var positionObject = this._pointerToPositionObject(this.pointerPosition); var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true}; if (this.triggerFunctions.add) { if (this.triggerFunctions.add.length == 2) { var me = this; this.triggerFunctions.add(defaultData, function(finalizedData) { me.nodesData.add(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { throw new Error('The function for add does not support two arguments (data,callback)'); this._createManipulatorBar(); this.moving = true; this.start(); } } else { this.nodesData.add(defaultData); this._createManipulatorBar(); this.moving = true; this.start(); } } }; /** * connect two nodes with a new edge. * * @private */ exports._createEdge = function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.connect) { if (this.triggerFunctions.connect.length == 2) { var me = this; this.triggerFunctions.connect(defaultData, function(finalizedData) { me.edgesData.add(finalizedData); me.moving = true; me.start(); }); } else { throw new Error('The function for connect does not support two arguments (data,callback)'); this.moving = true; this.start(); } } else { this.edgesData.add(defaultData); this.moving = true; this.start(); } } }; /** * connect two nodes with a new edge. * * @private */ exports._editEdge = function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.editEdge) { if (this.triggerFunctions.editEdge.length == 2) { var me = this; this.triggerFunctions.editEdge(defaultData, function(finalizedData) { me.edgesData.update(finalizedData); me.moving = true; me.start(); }); } else { throw new Error('The function for edit does not support two arguments (data, callback)'); this.moving = true; this.start(); } } else { this.edgesData.update(defaultData); this.moving = true; this.start(); } } }; /** * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color. * * @private */ exports._editNode = function() { if (this.triggerFunctions.edit && this.editMode == true) { var node = this._getSelectedNode(); var data = {id:node.id, label: node.label, group: node.options.group, shape: node.options.shape, color: { background:node.options.color.background, border:node.options.color.border, highlight: { background:node.options.color.highlight.background, border:node.options.color.highlight.border } }}; if (this.triggerFunctions.edit.length == 2) { var me = this; this.triggerFunctions.edit(data, function (finalizedData) { me.nodesData.update(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { throw new Error('The function for edit does not support two arguments (data, callback)'); } } else { throw new Error('No edit function has been bound to this button'); } }; /** * delete everything in the selection * * @private */ exports._deleteSelected = function() { if (!this._selectionIsEmpty() && this.editMode == true) { if (!this._clusterInSelection()) { var selectedNodes = this.getSelectedNodes(); var selectedEdges = this.getSelectedEdges(); if (this.triggerFunctions.del) { var me = this; var data = {nodes: selectedNodes, edges: selectedEdges}; if (this.triggerFunctions.del.length = 2) { this.triggerFunctions.del(data, function (finalizedData) { me.edgesData.remove(finalizedData.edges); me.nodesData.remove(finalizedData.nodes); me._unselectAll(); me.moving = true; me.start(); }); } else { throw new Error('The function for delete does not support two arguments (data, callback)') } } else { this.edgesData.remove(selectedEdges); this.nodesData.remove(selectedNodes); this._unselectAll(); this.moving = true; this.start(); } } else { alert(this.constants.locales[this.constants.locale]["deleteClusterError"]); } } }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Hammer = __webpack_require__(42); exports._cleanNavigation = function() { // clean hammer bindings if (this.navigationHammers.existing.length != 0) { for (var i = 0; i < this.navigationHammers.existing.length; i++) { this.navigationHammers.existing[i].dispose(); } this.navigationHammers.existing = []; } // clean up previous navigation items var wrapper = document.getElementById('network-navigation_wrapper'); if (wrapper && wrapper.parentNode) { wrapper.parentNode.removeChild(wrapper); } }; /** * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas. * * @private */ exports._loadNavigationElements = function() { this._cleanNavigation(); this.navigationDivs = {}; var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends']; var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','_zoomExtent']; this.navigationDivs['wrapper'] = document.createElement('div'); this.navigationDivs['wrapper'].id = 'network-navigation_wrapper'; this.frame.appendChild(this.navigationDivs['wrapper']); for (var i = 0; i < navigationDivs.length; i++) { this.navigationDivs[navigationDivs[i]] = document.createElement('div'); this.navigationDivs[navigationDivs[i]].id = 'network-navigation_' + navigationDivs[i]; this.navigationDivs[navigationDivs[i]].className = 'network-navigation ' + navigationDivs[i]; this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]); var hammer = Hammer(this.navigationDivs[navigationDivs[i]], {prevent_default: true}); hammer.on('touch', this[navigationDivActions[i]].bind(this)); this.navigationHammers.new.push(hammer); } var hammerDoc = Hammer(document, {prevent_default: false}); hammerDoc.on('release', this._stopMovement.bind(this)); this.navigationHammers.new.push(hammerDoc); this.navigationHammers.existing = this.navigationHammers.new; }; /** * this stops all movement induced by the navigation buttons * * @private */ exports._zoomExtent = function(event) { // FIXME: this is a workaround because the binding of Hammer on Document makes this fire twice if (this._zoomExtentLastTime === undefined || new Date() - this._zoomExtentLastTime > 200) { this._zoomExtentLastTime = new Date(); this.zoomExtent({duration:800}); event.stopPropagation(); } }; /** * this stops all movement induced by the navigation buttons * * @private */ exports._stopMovement = function() { this._xStopMoving(); this._yStopMoving(); this._stopZoom(); }; /** * move the screen up * By using the increments, instead of adding a fixed number to the translation, we keep fluent and * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently * To avoid this behaviour, we do the translation in the start loop. * * @private */ exports._moveUp = function(event) { this.yIncrement = this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done event.preventDefault(); }; /** * move the screen down * @private */ exports._moveDown = function(event) { this.yIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done event.preventDefault(); }; /** * move the screen left * @private */ exports._moveLeft = function(event) { this.xIncrement = this.constants.keyboard.speed.x; this.start(); // if there is no node movement, the calculation wont be done event.preventDefault(); }; /** * move the screen right * @private */ exports._moveRight = function(event) { this.xIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done event.preventDefault(); }; /** * Zoom in, using the same method as the movement. * @private */ exports._zoomIn = function(event) { this.zoomIncrement = this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done event.preventDefault(); }; /** * Zoom out * @private */ exports._zoomOut = function(event) { this.zoomIncrement = -this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done event.preventDefault(); }; /** * Stop zooming and unhighlight the zoom controls * @private */ exports._stopZoom = function(event) { this.zoomIncrement = 0; event && event.preventDefault(); }; /** * Stop moving in the Y direction and unHighlight the up and down * @private */ exports._yStopMoving = function(event) { this.yIncrement = 0; event && event.preventDefault(); }; /** * Stop moving in the X direction and unHighlight left and right. * @private */ exports._xStopMoving = function(event) { this.xIncrement = 0; event && event.preventDefault(); }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { exports._resetLevels = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.preassignedLevel == false) { node.level = -1; node.hierarchyEnumerated = false; } } } }; /** * This is the main function to layout the nodes in a hierarchical way. * It checks if the node details are supplied correctly * * @private */ exports._setupHierarchicalLayout = function() { if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) { if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") { this.constants.hierarchicalLayout.levelSeparation *= -1; } else { this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation); } if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") { if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.type = "vertical"; } } else { if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.type = "horizontal"; } } // get the size of the largest hubs and check if the user has defined a level for a node. var hubsize = 0; var node, nodeId; var definedLevel = false; var undefinedLevel = false; for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level != -1) { definedLevel = true; } else { undefinedLevel = true; } if (hubsize < node.edges.length) { hubsize = node.edges.length; } } } // if the user defined some levels but not all, alert and run without hierarchical layout if (undefinedLevel == true && definedLevel == true) { throw new Error("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes."); this.zoomExtent(undefined,true,this.constants.clustering.enabled); if (!this.constants.clustering.enabled) { this.start(); } } else { // setup the system to use hierarchical method. this._changeConstants(); // define levels if undefined by the users. Based on hubsize if (undefinedLevel == true) { if (this.constants.hierarchicalLayout.layout == "hubsize") { this._determineLevels(hubsize); } else { this._determineLevelsDirected(); } } // check the distribution of the nodes per level. var distribution = this._getDistribution(); // place the nodes on the canvas. This also stablilizes the system. this._placeNodesByHierarchy(distribution); // start the simulation. this.start(); } } }; /** * This function places the nodes on the canvas based on the hierarchial distribution. * * @param {Object} distribution | obtained by the function this._getDistribution() * @private */ exports._placeNodesByHierarchy = function(distribution) { var nodeId, node; // start placing all the level 0 nodes first. Then recursively position their branches. for (var level in distribution) { if (distribution.hasOwnProperty(level)) { for (nodeId in distribution[level].nodes) { if (distribution[level].nodes.hasOwnProperty(nodeId)) { node = distribution[level].nodes[nodeId]; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (node.xFixed) { node.x = distribution[level].minPos; node.xFixed = false; distribution[level].minPos += distribution[level].nodeSpacing; } } else { if (node.yFixed) { node.y = distribution[level].minPos; node.yFixed = false; distribution[level].minPos += distribution[level].nodeSpacing; } } this._placeBranchNodes(node.edges,node.id,distribution,node.level); } } } } // stabilize the system after positioning. This function calls zoomExtent. this._stabilize(); }; /** * This function get the distribution of levels based on hubsize * * @returns {Object} * @private */ exports._getDistribution = function() { var distribution = {}; var nodeId, node, level; // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. // the fix of X is removed after the x value has been set. for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.xFixed = true; node.yFixed = true; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { node.y = this.constants.hierarchicalLayout.levelSeparation*node.level; } else { node.x = this.constants.hierarchicalLayout.levelSeparation*node.level; } if (distribution[node.level] === undefined) { distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0}; } distribution[node.level].amount += 1; distribution[node.level].nodes[nodeId] = node; } } // determine the largest amount of nodes of all levels var maxCount = 0; for (level in distribution) { if (distribution.hasOwnProperty(level)) { if (maxCount < distribution[level].amount) { maxCount = distribution[level].amount; } } } // set the initial position and spacing of each nodes accordingly for (level in distribution) { if (distribution.hasOwnProperty(level)) { distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing; distribution[level].nodeSpacing /= (distribution[level].amount + 1); distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing); } } return distribution; }; /** * this function allocates nodes in levels based on the recursive branching from the largest hubs. * * @param hubsize * @private */ exports._determineLevels = function(hubsize) { var nodeId, node; // determine hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.edges.length == hubsize) { node.level = 0; } } } // branch from hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level == 0) { this._setLevel(1,node.edges,node.id); } } } }; /** * this function allocates nodes in levels based on the recursive branching from the largest hubs. * * @param hubsize * @private */ exports._determineLevelsDirected = function() { var nodeId, node; // set first node to source for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.nodes[nodeId].level = 10000; break; } } // branch from hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level == 10000) { this._setLevelDirected(10000,node.edges,node.id); } } } // branch from hubs var minLevel = 10000; for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; minLevel = node.level < minLevel ? node.level : minLevel; } } // branch from hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.level -= minLevel; } } }; /** * Since hierarchical layout does not support: * - smooth curves (based on the physics), * - clustering (based on dynamic node counts) * * We disable both features so there will be no problems. * * @private */ exports._changeConstants = function() { this.constants.clustering.enabled = false; this.constants.physics.barnesHut.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = true; this._loadSelectedForceSolver(); if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.dynamic = false; } this._configureSmoothCurves(); }; /** * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes * on a X position that ensures there will be no overlap. * * @param edges * @param parentId * @param distribution * @param parentLevel * @private */ exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. var nodeMoved = false; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (childNode.xFixed && childNode.level > parentLevel) { childNode.xFixed = false; childNode.x = distribution[childNode.level].minPos; nodeMoved = true; } } else { if (childNode.yFixed && childNode.level > parentLevel) { childNode.yFixed = false; childNode.y = distribution[childNode.level].minPos; nodeMoved = true; } } if (nodeMoved == true) { distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing; if (childNode.edges.length > 1) { this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level); } } } }; /** * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. * * @param level * @param edges * @param parentId * @private */ exports._setLevel = function(level, edges, parentId) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } if (childNode.level == -1 || childNode.level > level) { childNode.level = level; if (childNode.edges.length > 1) { this._setLevel(level+1, childNode.edges, childNode.id); } } } }; /** * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. * * @param level * @param edges * @param parentId * @private */ exports._setLevelDirected = function(level, edges, parentId) { this.nodes[parentId].hierarchyEnumerated = true; for (var i = 0; i < edges.length; i++) { var childNode = null; var direction = 1; if (edges[i].toId == parentId) { childNode = edges[i].from; direction = -1; } else { childNode = edges[i].to; } if (childNode.level == -1) { childNode.level = level + direction; } } for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) {childNode = edges[i].from;} else {childNode = edges[i].to;} if (childNode.edges.length > 1 && childNode.hierarchyEnumerated === false) { this._setLevelDirected(childNode.level, childNode.edges, childNode.id); } } }; /** * Unfix nodes * * @private */ exports._restoreNodes = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.nodes[nodeId].xFixed = false; this.nodes[nodeId].yFixed = false; } } }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var RepulsionMixin = __webpack_require__(62); var HierarchialRepulsionMixin = __webpack_require__(63); var BarnesHutMixin = __webpack_require__(64); /** * Toggling barnes Hut calculation on and off. * * @private */ exports._toggleBarnesHut = function () { this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled; this._loadSelectedForceSolver(); this.moving = true; this.start(); }; /** * This loads the node force solver based on the barnes hut or repulsion algorithm * * @private */ exports._loadSelectedForceSolver = function () { // this overloads the this._calculateNodeForces if (this.constants.physics.barnesHut.enabled == true) { this._clearMixin(RepulsionMixin); this._clearMixin(HierarchialRepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity; this.constants.physics.springLength = this.constants.physics.barnesHut.springLength; this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant; this.constants.physics.damping = this.constants.physics.barnesHut.damping; this._loadMixin(BarnesHutMixin); } else if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._clearMixin(BarnesHutMixin); this._clearMixin(RepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength; this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant; this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping; this._loadMixin(HierarchialRepulsionMixin); } else { this._clearMixin(BarnesHutMixin); this._clearMixin(HierarchialRepulsionMixin); this.barnesHutTree = undefined; this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.repulsion.springLength; this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant; this.constants.physics.damping = this.constants.physics.repulsion.damping; this._loadMixin(RepulsionMixin); } }; /** * Before calculating the forces, we check if we need to cluster to keep up performance and we check * if there is more than one node. If it is just one node, we dont calculate anything. * * @private */ exports._initializeForceCalculation = function () { // stop calculation if there is only one node if (this.nodeIndices.length == 1) { this.nodes[this.nodeIndices[0]]._setForce(0, 0); } else { // if there are too many nodes on screen, we cluster without repositioning if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) { this.clusterToFit(this.constants.clustering.reduceToNodes, false); } // we now start the force calculation this._calculateForces(); } }; /** * Calculate the external forces acting on the nodes * Forces are caused by: edges, repulsing forces between nodes, gravity * @private */ exports._calculateForces = function () { // Gravity is required to keep separated groups from floating off // the forces are reset to zero in this loop by using _setForce instead // of _addForce this._calculateGravitationalForces(); this._calculateNodeForces(); if (this.constants.physics.springConstant > 0) { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._calculateSpringForcesWithSupport(); } else { if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._calculateHierarchicalSpringForces(); } else { this._calculateSpringForces(); } } } }; /** * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also * handled in the calculateForces function. We then use a quadratic curve with the center node as control. * This function joins the datanodes and invisible (called support) nodes into one object. * We do this so we do not contaminate this.nodes with the support nodes. * * @private */ exports._updateCalculationNodes = function () { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this.calculationNodes = {}; this.calculationNodeIndices = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId] = this.nodes[nodeId]; } } var supportNodes = this.sectors['support']['nodes']; for (var supportNodeId in supportNodes) { if (supportNodes.hasOwnProperty(supportNodeId)) { if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) { this.calculationNodes[supportNodeId] = supportNodes[supportNodeId]; } else { supportNodes[supportNodeId]._setForce(0, 0); } } } for (var idx in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(idx)) { this.calculationNodeIndices.push(idx); } } } else { this.calculationNodes = this.nodes; this.calculationNodeIndices = this.nodeIndices; } }; /** * this function applies the central gravity effect to keep groups from floating off * * @private */ exports._calculateGravitationalForces = function () { var dx, dy, distance, node, i; var nodes = this.calculationNodes; var gravity = this.constants.physics.centralGravity; var gravityForce = 0; for (i = 0; i < this.calculationNodeIndices.length; i++) { node = nodes[this.calculationNodeIndices[i]]; node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters. // gravity does not apply when we are in a pocket sector if (this._sector() == "default" && gravity != 0) { dx = -node.x; dy = -node.y; distance = Math.sqrt(dx * dx + dy * dy); gravityForce = (distance == 0) ? 0 : (gravity / distance); node.fx = dx * gravityForce; node.fy = dy * gravityForce; } else { node.fx = 0; node.fy = 0; } } }; /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ exports._calculateSpringForces = function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; edge.from.fx += fx; edge.from.fy += fy; edge.to.fx -= fx; edge.to.fy -= fy; } } } } }; /** * This function calculates the springforces on the nodes, accounting for the support nodes. * * @private */ exports._calculateSpringForcesWithSupport = function () { var edgeLength, edge, edgeId, combinedClusterSize; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { if (edge.via != null) { var node1 = edge.to; var node2 = edge.via; var node3 = edge.from; edgeLength = edge.physics.springLength; combinedClusterSize = node1.clusterSize + node3.clusterSize - 2; // this implies that the edges between big clusters are longer edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth; this._calculateSpringForce(node1, node2, 0.5 * edgeLength); this._calculateSpringForce(node2, node3, 0.5 * edgeLength); } } } } } }; /** * This is the code actually performing the calculation for the function above. It is split out to avoid repetition. * * @param node1 * @param node2 * @param edgeLength * @private */ exports._calculateSpringForce = function (node1, node2, edgeLength) { var dx, dy, fx, fy, springForce, distance; dx = (node1.x - node2.x); dy = (node1.y - node2.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; node1.fx += fx; node1.fy += fy; node2.fx -= fx; node2.fy -= fy; }; /** * Load the HTML for the physics config and bind it * @private */ exports._loadPhysicsConfiguration = function () { if (this.physicsConfiguration === undefined) { this.backupConstants = {}; util.deepExtend(this.backupConstants,this.constants); var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"]; this.physicsConfiguration = document.createElement('div'); this.physicsConfiguration.className = "PhysicsConfiguration"; this.physicsConfiguration.innerHTML = '' + '<table><tr><td><b>Simulation Mode:</b></td></tr>' + '<tr>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' + '</tr>' + '</table>' + '<table id="graph_BH_table" style="display:none">' + '<tr><td><b>Barnes Hut</b></td></tr>' + '<tr>' + '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_R_table" style="display:none">' + '<tr><td><b>Repulsion</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_H_table" style="display:none">' + '<tr><td width="150"><b>Hierarchical</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table><tr><td><b>Options:</b></td></tr>' + '<tr>' + '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' + '</tr>' + '</table>' this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement); this.optionsDiv = document.createElement("div"); this.optionsDiv.style.fontSize = "14px"; this.optionsDiv.style.fontFamily = "verdana"; this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement); var rangeElement; rangeElement = document.getElementById('graph_BH_gc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant"); rangeElement = document.getElementById('graph_BH_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_BH_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_BH_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_BH_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_R_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance"); rangeElement = document.getElementById('graph_R_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_R_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_R_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_R_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); rangeElement = document.getElementById('graph_H_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_H_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_H_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_H_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_direction'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction"); rangeElement = document.getElementById('graph_H_levsep'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation"); rangeElement = document.getElementById('graph_H_nspac'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing"); var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); var radioButton3 = document.getElementById("graph_physicsMethod3"); radioButton2.checked = true; if (this.constants.physics.barnesHut.enabled) { radioButton1.checked = true; } if (this.constants.hierarchicalLayout.enabled) { radioButton3.checked = true; } var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); var graph_repositionNodes = document.getElementById("graph_repositionNodes"); var graph_generateOptions = document.getElementById("graph_generateOptions"); graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this); graph_repositionNodes.onclick = graphRepositionNodes.bind(this); graph_generateOptions.onclick = graphGenerateOptions.bind(this); if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) { graph_toggleSmooth.style.background = "#A4FF56"; } else { graph_toggleSmooth.style.background = "#FF8532"; } switchConfigurations.apply(this); radioButton1.onchange = switchConfigurations.bind(this); radioButton2.onchange = switchConfigurations.bind(this); radioButton3.onchange = switchConfigurations.bind(this); } }; /** * This overwrites the this.constants. * * @param constantsVariableName * @param value * @private */ exports._overWriteGraphConstants = function (constantsVariableName, value) { var nameArray = constantsVariableName.split("_"); if (nameArray.length == 1) { this.constants[nameArray[0]] = value; } else if (nameArray.length == 2) { this.constants[nameArray[0]][nameArray[1]] = value; } else if (nameArray.length == 3) { this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value; } }; /** * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype. */ function graphToggleSmoothCurves () { this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled; var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this._configureSmoothCurves(false); } /** * this function is used to scramble the nodes * */ function graphRepositionNodes () { for (var nodeId in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0; this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0; } } if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity"); showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant"); showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength"); showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping"); } else { this.repositionNodes(); } this.moving = true; this.start(); } /** * this is used to generate an options file from the playing with physics system. */ function graphGenerateOptions () { var options = "No options are required, default values used."; var optionsSpecific = []; var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); if (radioButton1.checked == true) { if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);} if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options = "var options = {"; options += "physics: {barnesHut: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) { if (optionsSpecific.length == 0) {options = "var options = {";} else {options += ", "} options += "smoothCurves: " + this.constants.smoothCurves.enabled; } if (options != "No options are required, default values used.") { options += '};' } } else if (radioButton2.checked == true) { options = "var options = {"; options += "physics: {barnesHut: {enabled: false}"; if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += ", repulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (optionsSpecific.length == 0) {options += "}"} if (this.constants.smoothCurves != this.backupConstants.smoothCurves) { options += ", smoothCurves: " + this.constants.smoothCurves; } options += '};' } else { options = "var options = {"; if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += "physics: {hierarchicalRepulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", "; } } options += '}},'; } options += 'hierarchicalLayout: {'; optionsSpecific = []; if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);} if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);} if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);} if (optionsSpecific.length != 0) { for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}' } else { options += "enabled:true}"; } options += '};' } this.optionsDiv.innerHTML = options; } /** * this is used to switch between barnesHut, repulsion and hierarchical. * */ function switchConfigurations () { var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"]; var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value; var tableId = "graph_" + radioButton + "_table"; var table = document.getElementById(tableId); table.style.display = "block"; for (var i = 0; i < ids.length; i++) { if (ids[i] != tableId) { table = document.getElementById(ids[i]); table.style.display = "none"; } } this._restoreNodes(); if (radioButton == "R") { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = false; } else if (radioButton == "H") { if (this.constants.hierarchicalLayout.enabled == false) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; this.constants.smoothCurves.enabled = false; this._setupHierarchicalLayout(); } } else { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = true; } this._loadSelectedForceSolver(); var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this.moving = true; this.start(); } /** * this generates the ranges depending on the iniital values. * * @param id * @param map * @param constantsVariableName */ function showValueOfRange (id,map,constantsVariableName) { var valueId = id + "_value"; var rangeValue = document.getElementById(id).value; if (map instanceof Array) { document.getElementById(valueId).value = map[parseInt(rangeValue)]; this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]); } else { document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue); this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue)); } if (constantsVariableName == "hierarchicalLayout_direction" || constantsVariableName == "hierarchicalLayout_levelSeparation" || constantsVariableName == "hierarchicalLayout_nodeSpacing") { this._setupHierarchicalLayout(); } this.moving = true; this.start(); } /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { function webpackContext(req) { throw new Error("Cannot find module '" + req + "'."); } webpackContext.resolve = webpackContext; webpackContext.keys = function() { return []; }; module.exports = webpackContext; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /** * Calculate the forces the nodes apply on each other based on a repulsion field. * This field is linearly approximated. * * @private */ exports._calculateNodeForces = function () { var dx, dy, angle, distance, fx, fy, combinedClusterSize, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // approximation constants var a_base = -2 / 3; var b = 4 / 3; // repulsing forces between nodes var nodeDistance = this.constants.physics.repulsion.nodeDistance; var minimumDistance = nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; combinedClusterSize = node1.clusterSize + node2.clusterSize - 2; dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification)); var a = a_base / minimumDistance; if (distance < 2 * minimumDistance) { if (distance < 0.5 * minimumDistance) { repulsingForce = 1.0; } else { repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)) } // amplify the repulsion for clusters. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification; repulsingForce = repulsingForce / distance; fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } }; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /** * Calculate the forces the nodes apply on eachother based on a repulsion field. * This field is linearly approximated. * * @private */ exports._calculateNodeForces = function () { var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // repulsing forces between nodes var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; // nodes only affect nodes on their level if (node1.level == node2.level) { dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); var steepness = 0.05; if (distance < nodeDistance) { repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2); } else { repulsingForce = 0; } // normalize force with if (distance == 0) { distance = 0.01; } else { repulsingForce = repulsingForce / distance; } fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } }; /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ exports._calculateHierarchicalSpringForces = function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; for (var i = 0; i < nodeIndices.length; i++) { var node1 = nodes[nodeIndices[i]]; node1.springFx = 0; node1.springFy = 0; } // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; if (edge.to.level != edge.from.level) { edge.to.springFx -= fx; edge.to.springFy -= fy; edge.from.springFx += fx; edge.from.springFy += fy; } else { var factor = 0.5; edge.to.fx -= factor*fx; edge.to.fy -= factor*fy; edge.from.fx += factor*fx; edge.from.fy += factor*fy; } } } } } // normalize spring forces var springForce = 1; var springFx, springFy; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; springFx = Math.min(springForce,Math.max(-springForce,node.springFx)); springFy = Math.min(springForce,Math.max(-springForce,node.springFy)); node.fx += springFx; node.fy += springFy; } // retain energy balance var totalFx = 0; var totalFy = 0; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; totalFx += node.fx; totalFy += node.fy; } var correctionFx = totalFx / nodeIndices.length; var correctionFy = totalFy / nodeIndices.length; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; node.fx -= correctionFx; node.fy -= correctionFy; } }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /** * This function calculates the forces the nodes apply on eachother based on a gravitational model. * The Barnes Hut method is used to speed up this N-body simulation. * * @private */ exports._calculateNodeForces = function() { if (this.constants.physics.barnesHut.gravitationalConstant != 0) { var node; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; var nodeCount = nodeIndices.length; this._formBarnesHutTree(nodes,nodeIndices); var barnesHutTree = this.barnesHutTree; // place the nodes one by one recursively for (var i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; if (node.options.mass > 0) { // starting with root is irrelevant, it never passes the BarnesHut condition this._getForceContribution(barnesHutTree.root.children.NW,node); this._getForceContribution(barnesHutTree.root.children.NE,node); this._getForceContribution(barnesHutTree.root.children.SW,node); this._getForceContribution(barnesHutTree.root.children.SE,node); } } } }; /** * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. * If a region contains a single node, we check if it is not itself, then we apply the force. * * @param parentBranch * @param node * @private */ exports._getForceContribution = function(parentBranch,node) { // we get no force contribution from an empty region if (parentBranch.childrenCount > 0) { var dx,dy,distance; // get the distance from the center of mass to the node. dx = parentBranch.centerOfMass.x - node.x; dy = parentBranch.centerOfMass.y - node.y; distance = Math.sqrt(dx * dx + dy * dy); // BarnesHut condition // original condition : s/d < theta = passed === d/s > 1/theta = passed // calcSize = 1/s --> d * 1/s > 1/theta = passed if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) { // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.1*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } else { // Did not pass the condition, go into children if available if (parentBranch.childrenCount == 4) { this._getForceContribution(parentBranch.children.NW,node); this._getForceContribution(parentBranch.children.NE,node); this._getForceContribution(parentBranch.children.SW,node); this._getForceContribution(parentBranch.children.SE,node); } else { // parentBranch must have only one node, if it was empty we wouldnt be here if (parentBranch.children.data.id != node.id) { // if it is not self // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.5*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } } } } }; /** * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. * * @param nodes * @param nodeIndices * @private */ exports._formBarnesHutTree = function(nodes,nodeIndices) { var node; var nodeCount = nodeIndices.length; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX =-Number.MAX_VALUE, maxY =-Number.MAX_VALUE; // get the range of the nodes for (var i = 0; i < nodeCount; i++) { var x = nodes[nodeIndices[i]].x; var y = nodes[nodeIndices[i]].y; if (nodes[nodeIndices[i]].options.mass > 0) { if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } } } // make the range a square var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize var minimumTreeSize = 1e-5; var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX)); var halfRootSize = 0.5 * rootSize; var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY); // construct the barnesHutTree var barnesHutTree = { root:{ centerOfMass: {x:0, y:0}, mass:0, range: { minX: centerX-halfRootSize,maxX:centerX+halfRootSize, minY: centerY-halfRootSize,maxY:centerY+halfRootSize }, size: rootSize, calcSize: 1 / rootSize, children: { data:null}, maxWidth: 0, level: 0, childrenCount: 4 } }; this._splitBranch(barnesHutTree.root); // place the nodes one by one recursively for (i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; if (node.options.mass > 0) { this._placeInTree(barnesHutTree.root,node); } } // make global this.barnesHutTree = barnesHutTree }; /** * this updates the mass of a branch. this is increased by adding a node. * * @param parentBranch * @param node * @private */ exports._updateBranchMass = function(parentBranch, node) { var totalMass = parentBranch.mass + node.options.mass; var totalMassInv = 1/totalMass; parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.options.mass; parentBranch.centerOfMass.x *= totalMassInv; parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.options.mass; parentBranch.centerOfMass.y *= totalMassInv; parentBranch.mass = totalMass; var biggestSize = Math.max(Math.max(node.height,node.radius),node.width); parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth; }; /** * determine in which branch the node will be placed. * * @param parentBranch * @param node * @param skipMassUpdate * @private */ exports._placeInTree = function(parentBranch,node,skipMassUpdate) { if (skipMassUpdate != true || skipMassUpdate === undefined) { // update the mass of the branch. this._updateBranchMass(parentBranch,node); } if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW if (parentBranch.children.NW.range.maxY > node.y) { // in NW this._placeInRegion(parentBranch,node,"NW"); } else { // in SW this._placeInRegion(parentBranch,node,"SW"); } } else { // in NE or SE if (parentBranch.children.NW.range.maxY > node.y) { // in NE this._placeInRegion(parentBranch,node,"NE"); } else { // in SE this._placeInRegion(parentBranch,node,"SE"); } } }; /** * actually place the node in a region (or branch) * * @param parentBranch * @param node * @param region * @private */ exports._placeInRegion = function(parentBranch,node,region) { switch (parentBranch.children[region].childrenCount) { case 0: // place node here parentBranch.children[region].children.data = node; parentBranch.children[region].childrenCount = 1; this._updateBranchMass(parentBranch.children[region],node); break; case 1: // convert into children // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) // we move one node a pixel and we do not put it in the tree. if (parentBranch.children[region].children.data.x == node.x && parentBranch.children[region].children.data.y == node.y) { node.x += Math.random(); node.y += Math.random(); } else { this._splitBranch(parentBranch.children[region]); this._placeInTree(parentBranch.children[region],node); } break; case 4: // place in branch this._placeInTree(parentBranch.children[region],node); break; } }; /** * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch * after the split is complete. * * @param parentBranch * @private */ exports._splitBranch = function(parentBranch) { // if the branch is shaded with a node, replace the node in the new subset. var containedNode = null; if (parentBranch.childrenCount == 1) { containedNode = parentBranch.children.data; parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0; } parentBranch.childrenCount = 4; parentBranch.children.data = null; this._insertRegion(parentBranch,"NW"); this._insertRegion(parentBranch,"NE"); this._insertRegion(parentBranch,"SW"); this._insertRegion(parentBranch,"SE"); if (containedNode != null) { this._placeInTree(parentBranch,containedNode); } }; /** * This function subdivides the region into four new segments. * Specifically, this inserts a single new segment. * It fills the children section of the parentBranch * * @param parentBranch * @param region * @param parentRange * @private */ exports._insertRegion = function(parentBranch, region) { var minX,maxX,minY,maxY; var childSize = 0.5 * parentBranch.size; switch (region) { case "NW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "NE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "SW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; case "SE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; } parentBranch.children[region] = { centerOfMass:{x:0,y:0}, mass:0, range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY}, size: 0.5 * parentBranch.size, calcSize: 2 * parentBranch.calcSize, children: {data:null}, maxWidth: 0, level: parentBranch.level+1, childrenCount: 0 }; }; /** * This function is for debugging purposed, it draws the tree. * * @param ctx * @param color * @private */ exports._drawTree = function(ctx,color) { if (this.barnesHutTree !== undefined) { ctx.lineWidth = 1; this._drawBranch(this.barnesHutTree.root,ctx,color); } }; /** * This function is for debugging purposes. It draws the branches recursively. * * @param branch * @param ctx * @param color * @private */ exports._drawBranch = function(branch,ctx,color) { if (color === undefined) { color = "#FF0000"; } if (branch.childrenCount == 4) { this._drawBranch(branch.children.NW,ctx); this._drawBranch(branch.children.NE,ctx); this._drawBranch(branch.children.SE,ctx); this._drawBranch(branch.children.SW,ctx); } ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.minY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.minY); ctx.stroke(); /* if (branch.mass > 0) { ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); ctx.stroke(); } */ }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ } /******/ ]) });
src/components/MessageItem/MessageItem.js
bertho-zero/react-redux-universal-hot-example
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Message from './Message'; import MessageEdition from './MessageEdition'; export default class MessageItem extends Component { static propTypes = { user: PropTypes.shape({ email: PropTypes.string }), styles: PropTypes.shape({ controlBtn: PropTypes.string }).isRequired, patchMessage: PropTypes.func.isRequired, message: PropTypes.objectOf(PropTypes.any).isRequired }; static defaultProps = { user: null }; state = { editing: {} }; startEdit = msg => { const { editing } = this.state; this.setState({ editing: { ...editing, [msg._id]: true } }); }; stopEdit = msg => { const { editing } = this.state; this.setState({ editing: { ...editing, [msg._id]: null } }); }; render() { const { message, user, patchMessage, styles } = this.props; const { editing } = this.state; const inEdition = editing[message._id]; return ( <div className="media" key={`chat.msg.${message._id}`}> <div className="media-body"> {inEdition ? ( <MessageEdition message={message} patchMessage={patchMessage} styles={styles} stopEdit={this.stopEdit} /> ) : ( <Message message={message} user={user} styles={styles} startEdit={this.startEdit} /> )} </div> </div> ); } }
packages/cf-component-copyable-textarea/src/CopyableTextarea.js
koddsson/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; import { TextareaUnstyled, TextareaTheme } from 'cf-component-textarea'; import { createComponent, applyTheme } from 'cf-style-container'; const Textarea = applyTheme(TextareaUnstyled, TextareaTheme, theme => ({ height: '7rem', wordBreak: 'break-all', cursor: 'text', resize: 'none', color: theme.color.charcoal, fontFamily: 'monaco, courier, monospace' })); const styles = ({ theme }) => ({ marginTop: '1rem', cursor: 'pointer' }); const HelpText = createComponent( ({ theme }) => ({ fontSize: '0.8em', color: theme.colorGray, marginTop: '-0.5em', marginBottom: '1em' }), 'p' ); class CopyableTextarea extends React.Component { constructor(props) { super(props); this.state = { helpText: this.props.clickToCopyText, copied: false }; this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); } handleFocus(e) { e.target.select(); const { onCopy } = this.props; let success; try { success = document.execCommand('copy'); } catch (err) { success = false; } if (success && onCopy) { onCopy(); } this.setState({ helpText: success ? this.props.copiedTextToClipboardText : this.props.pressCommandOrCtrlCToCopyText, copied: success }); } handleBlur() { this.setState({ helpText: this.props.clickToCopyText, copied: false }); } render() { return ( <div className={this.props.className}> <Textarea ref={node => this.textarea = node} readOnly name={this.props.name} value={this.props.value} onFocus={this.handleFocus} onBlur={this.handleBlur} /> <HelpText>{this.state.helpText}</HelpText> </div> ); } } CopyableTextarea.propTypes = { name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, onCopy: PropTypes.func, clickToCopyText: PropTypes.string, copiedTextToClipboardText: PropTypes.string, pressCommandOrCtrlCToCopyText: PropTypes.string }; CopyableTextarea.defaultProps = { clickToCopyText: 'Click to copy', copiedTextToClipboardText: 'Copied text to clipboard', pressCommandOrCtrlCToCopyText: 'Press Command/Ctrl+C to copy' }; export default createComponent(styles, CopyableTextarea);
example/App.js
kib357/react-object-inspector
import React, { Component } from 'react'; import ObjectInspector from '../src/ObjectInspector'; function testFunction(){ console.log("hello world"); } export default class App extends Component { render() { const testObject = { "id": 2, "name": "An ice sculpture", // "price": 12.50, "tags": ["cold", "ice"], "dimensions": { "length": 7.0, "width": 12.0, "height": 9.5 }, "warehouseLocation": { "latitude": -78.75, "longitude": 20.4 } }; const test2 = {"employees":[ {"firstName":"John", "lastName":"Doe", "fullTime": true}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]}; const test3 = { "a1": 1, "a2": "A2", "a3": true, "a4": undefined, "a5": { "a5-1": null, "a5-2": ["a5-2-1", "a5-2-2"], "a5-3": {} }, "a6": function(){ console.log("hello world") }, "a7": new Date("2005-04-03") }; const test4 = { "login": "defunkt", "id": 2, "avatar_url": "https://avatars.githubusercontent.com/u/2?v=3", "gravatar_id": "", "url": "https://api.github.com/users/defunkt", "html_url": "https://github.com/defunkt", "followers_url": "https://api.github.com/users/defunkt/followers", "following_url": "https://api.github.com/users/defunkt/following{/other_user}", "gists_url": "https://api.github.com/users/defunkt/gists{/gist_id}", "starred_url": "https://api.github.com/users/defunkt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/defunkt/subscriptions", "organizations_url": "https://api.github.com/users/defunkt/orgs", "repos_url": "https://api.github.com/users/defunkt/repos", "events_url": "https://api.github.com/users/defunkt/events{/privacy}", "received_events_url": "https://api.github.com/users/defunkt/received_events", "type": "User", "site_admin": true, "name": "Chris Wanstrath", "company": "GitHub", "blog": "http://chriswanstrath.com/", "location": "San Francisco", "email": "[email protected]", "hireable": true, "bio": null, "public_repos": 108, "public_gists": 280, "followers": 14509, "following": 208, "created_at": "2007-10-20T05:24:19Z", "updated_at": "2015-08-03T18:05:52Z" }; const test5 = { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }; // { // "a": function(){ // // iife ajax call // } // } const testObjects = [undefined, testFunction, null, true, false, "testString", 42, NaN, Symbol('foo'), testObject, test2, test3, test4, test5, [], ["a"], ["a", 1], new Date()]; return ( <div> {(() => { // https://facebook.github.io/react/tips/if-else-in-JSX.html return testObjects.map(function(object, index){ return ( <div key={index} style={{marginBottom:"10px"}}> <ObjectInspector data={object}> </ObjectInspector> </div>); }); })()} </div> ); } }
docs/app/Examples/collections/Table/Variations/TableExampleColumnCount.js
vageeshb/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleColumnCount = () => { return ( <Table columns={5}> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Age</Table.HeaderCell> <Table.HeaderCell>Gender</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>22</Table.Cell> <Table.Cell>Male</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>32</Table.Cell> <Table.Cell>Male</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell>22</Table.Cell> <Table.Cell>Female</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> </Table.Body> <Table.Footer> <Table.Row> <Table.HeaderCell>3 People</Table.HeaderCell> <Table.HeaderCell>2 Approved</Table.HeaderCell> <Table.HeaderCell /> <Table.HeaderCell /> <Table.HeaderCell /> </Table.Row> </Table.Footer> </Table> ) } export default TableExampleColumnCount
newclient/scripts/components/admin/detail-view/upload-attachments-panel/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import {AdminActions} from '../../../../actions/admin-actions'; import {FileUpload} from '../../../file-upload'; import classNames from 'classnames'; export default function UploadAttachmentsPanel(props) { return ( <div name='Upload Attachments Panel' className={classNames(styles.container, props.className)}> <div className={styles.header}> <span className={styles.close} onClick={AdminActions.hideUploadAttachmentsPanel}> <i className="fa fa-times" style={{fontSize: 23}} /> CLOSE </span> <span className={styles.title}>UPLOAD ATTACHMENTS</span> </div> <FileUpload fileType='Admin' readonly={props.readonly} onDrop={AdminActions.addAdminAttachment} delete={AdminActions.deleteAdminAttachment} files={props.files} multiple={true} className={`${styles.override} ${styles.fileUploadStyles}`} > <div>Drag and drop or upload your attachments</div> <div style={{fontSize: 10, marginTop: 2}}>Acceptable Formats: .pdf, .png, .doc, .jpeg</div> </FileUpload> </div> ); }
example/components/simple.js
boromisp/react-leaflet
import React, { Component } from 'react'; import { Map, TileLayer, Marker, Popup } from '../../src'; export default class SimpleExample extends Component { constructor() { super(); this.state = { lat: 51.505, lng: -0.09, zoom: 13, }; } render() { const position = [this.state.lat, this.state.lng]; return ( <Map center={position} zoom={this.state.zoom}> <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' /> <Marker position={position}> <Popup> <span>A pretty CSS3 popup. <br/> Easily customizable.</span> </Popup> </Marker> </Map> ); } }
generators/generator-defaults.js
cbornet/generator-jhipster
/** * Copyright 2013-2020 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ const constants = require('./generator-constants'); const ANGULAR = constants.SUPPORTED_CLIENT_FRAMEWORKS.ANGULAR; /** Required config for prompts to be skipped */ const appRequiredConfig = { applicationType: 'monolith', }; const appDefaultConfig = { ...appRequiredConfig, skipClient: false, skipServer: false, skipUserManagement: false, skipCheckLengthOfIdentifier: false, skipFakeData: false, jhiPrefix: 'jhi', entitySuffix: '', dtoSuffix: 'DTO', reactive: false, testFrameworks: [], blueprints: [], otherModules: [], clientPackageManager: 'npm', pages: [], }; /** Required config for prompts to be skipped */ const serverRequiredConfig = { packageName: 'com.mycompany.myapp', cacheProvider: 'ehcache', websocket: false, databaseType: 'sql', prodDatabaseType: 'mysql', devDatabaseType: 'h2Disk', searchEngine: false, buildTool: 'maven', }; const serverDefaultConfig = { ...serverRequiredConfig, serverPort: 8080, authenticationType: 'jwt', serviceDiscoveryType: false, enableHibernateCache: true, }; /** Required config for prompts to be skipped */ const clientRequiredConfig = { clientFramework: ANGULAR, }; const clientDefaultConfig = { ...clientRequiredConfig, clientTheme: 'none', clientThemeVariant: 'primary', useSass: true, }; const translationDefaultConfig = { enableTranslation: true, nativeLanguage: 'en', languages: [], }; /** Required config for prompts to be skipped, baseName is missing */ const requiredDefaultConfig = { ...appRequiredConfig, ...serverRequiredConfig, ...clientRequiredConfig, }; const defaultConfig = { ...appDefaultConfig, ...serverDefaultConfig, ...clientDefaultConfig, ...translationDefaultConfig, }; const entityDefaultConfig = { fields: [], relationships: [], pagination: 'no', validation: false, dto: 'no', service: 'no', jpaMetamodelFiltering: false, readOnly: false, embedded: false, skipUiGrouping: false, entityAngularJSSuffix: '', fluentMethods: true, clientRootFolder: '', }; module.exports = { appDefaultConfig, serverDefaultConfig, clientDefaultConfig, defaultConfig, requiredDefaultConfig, entityDefaultConfig, };
app/src/components/user/VerifyMail/Active/index.js
ouxu/NEUQ-OJ
/** * Created by out_xu on 17/4/18. */ import React from 'react' import { Input } from 'antd' const Active = (props) => { return ( <div> <p className='h-title' key='verify-mail-p-1'>如果你的账号已经注册但仍未激活,或者验证链接超时,请重新进行邮箱验证!</p> <p className='h-title' key='verify-mail-p-2'>验证邮件 60s 只能发送一次,请勿重复点击!</p> <div className='verify-mail-input' key='verify-mail-input'> <Input placeholder='请输入您的邮箱' addonAfter={props.addonAfter} onChange={props.onInputChange} /> </div> </div> ) } export default Active
frontend/src/routes.js
OpenCollective/opencollective-website
import React from 'react'; import { Route, Redirect } from 'react-router'; import About from './containers/About'; import AddGroup from './containers/AddGroup'; import ConnectedAccounts from './components/ConnectedAccounts'; import ConnectProvider from './containers/ConnectProvider'; import Discover from './containers/Discover'; import DonatePage from './containers/DonatePage'; import EditTwitter from './components/EditTwitter'; import Faq from './containers/Faq'; import GroupTierList from './containers/GroupTierList'; import Homepage from './containers/HomePage'; import LearnMore from './containers/LearnMore'; import Ledger from './containers/Ledger'; import Login from './containers/Login'; import NewGroup from './containers/NewGroup'; import NotFound from './components/NotFound'; import OnBoarding from './containers/OnBoarding'; import PublicPage from './containers/PublicPage'; import Response from './containers/Response'; import Settings from './containers/Settings'; import Subscriptions from './containers/Subscriptions'; import { requireAuthentication } from './components/AuthenticatedComponent'; export default ( <Route> <Route path="/" component={Homepage} /> <Route path="/about" component={About} /> <Route path="/faq" component={Faq} /> <Route path="/discover(/:tag)" component={Discover} /> <Route path="/learn-more" component={LearnMore} /> <Route path="/apply" component={NewGroup} /> <Route path="/create" component={NewGroup} /> <Route path="/addgroup" component={requireAuthentication(AddGroup)} /> <Route path="/login/:token" component={Login} /> <Route path="/login" component={Login} />, <Route path="/subscriptions" component={requireAuthentication(Subscriptions)} /> <Route path="/opensource/apply/:token" component={OnBoarding} /> <Route path="/opensource/apply" component={OnBoarding} /> <Redirect from="/github/apply/:token" to="/opensource/apply/:token" /> <Redirect from="/github/apply" to="/opensource/apply" /> <Route path="/services/email/unsubscribe" action="unsubscribe" component={Response} /> <Route path="/services/email/approve" action="approve" component={Response} /> <Route path="/:slug/apply/:type" component={NewGroup} /> <Route path="/:slug/apply" component={NewGroup} /> <Route path="/:slug/connected-accounts" component={ConnectedAccounts} /> <Route path="/:slug/connect/:provider" component={ConnectProvider} /> <Route path="/:slug/edit-twitter" component={EditTwitter} /> <Route path="/:slug/transactions" type="transactions" component={Ledger} /> <Route path="/:slug/donations" type="donations" component={Ledger} /> <Route path="/:slug/expenses" type="expenses" component={Ledger} /> <Route path="/:slug/expenses/new" action="new" component={Ledger} /> <Route path="/:slug/expenses/:expenseid/approve" action="approve" component={Ledger} /> <Route path="/:slug/expenses/:expenseid/reject" action="reject" component={Ledger} /> <Route path="/:slug/settings" component={requireAuthentication(Settings)} /> // :verb can be donate, pay or contribute <Route path="/:slug/:verb/:amount/:interval/:description" component={DonatePage} /> <Route path="/:slug/:verb/:amount/:interval" component={DonatePage} /> <Route path="/:slug/:verb/:amount" component={DonatePage} /> <Route path="/:slug/donate" component={DonatePage} /> // TODO: this is generating the searchbox on 404s right now <Route path="/:slug/:tier" component={GroupTierList} /> <Route path="/:slug" component={PublicPage} /> <Route path='*' component={NotFound} /> </Route> );
components/admin/pages/table/actions/DeleteAction.js
resource-watch/resource-watch
import React from 'react'; import PropTypes from 'prop-types'; // Services import { deletePage } from 'services/pages'; import { toastr } from 'react-redux-toastr'; class DeleteAction extends React.Component { handleOnClickDelete = (e) => { if (e) { e.preventDefault(); e.stopPropagation(); } const { data, authorization } = this.props; toastr.confirm(`Are you sure that you want to delete: "${data.title}"`, { onOk: () => { deletePage(data.id, authorization) .then(() => { this.props.onRowDelete(data.id); toastr.success('Success', `The page "${data.id}" - "${data.title}" has been removed correctly`); }) .catch((err) => { toastr.error('Error', `The page "${data.id}" - "${data.title}" was not deleted. Try again. ${err}`); }); }, }); } render() { return ( <span> <a className="c-btn" href="#delete-dataset" onClick={this.handleOnClickDelete}> Remove </a> </span> ); } } DeleteAction.propTypes = { data: PropTypes.object.isRequired, authorization: PropTypes.string.isRequired, onRowDelete: PropTypes.func.isRequired, }; export default DeleteAction;
src/SplitToggle.js
apkiernan/react-bootstrap
import React from 'react'; import DropdownToggle from './DropdownToggle'; class SplitToggle extends React.Component { render() { return ( <DropdownToggle {...this.props} useAnchor={false} noCaret={false} /> ); } } SplitToggle.defaultProps = DropdownToggle.defaultProps; export default SplitToggle;
src/components/posts_show.js
hirodashi/ReduxSimpleStarter-blog
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost, deletePost } from '../actions/index.js' class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } onDeleteClick() { const { id } = this.props.match.params; this.props.deletePost(id, () => { this.props.history.push('/'); }); } render() { const { post } = this.props; if ( !post ) { return <div>Loading...</div>; } return ( <div> <Link className="btn btn-primary" to="/">All Posts</Link> <button className="btn btn-danger pull-xs-right" onClick={this.onDeleteClick.bind(this)} > Delete Post </button> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
src/components/ReactComponent/ReactComponent.js
cgvarela/react-styleguidist
import { Component, PropTypes } from 'react'; import Props from 'components/Props'; import Playground from 'components/Playground'; import s from './ReactComponent.css'; export default class ReactComponent extends Component { static propTypes = { component: PropTypes.object.isRequired } renderDescription() { let description = this.props.component.props.description; if (!description) { return null; } return ( <div className={s.description}>{description}</div> ); } renderExamples() { let { examples } = this.props.component; if (!examples) { return null; } return examples.map((example, index) => { switch (example.type) { case 'code': return ( <Playground code={example.content} key={index}/> ); case 'html': return ( <div dangerouslySetInnerHTML={{__html: example.content}} key={index}></div> ); } }); } render() { let { component } = this.props; return ( <div className={s.root}> <h2 className={s.heading}>{component.name}</h2> {this.renderDescription()} <Props props={component.props}/> {this.renderExamples()} </div> ); } }
app/assets/javascripts/components/story/ExpandedStory/ExpandedStoryOwnedBy.js
Codeminer42/cm42-central
import React from 'react'; import PropTypes from 'prop-types'; import SelectUser from '../select_user/SelectUser'; import { editingStoryPropTypesShape } from '../../../models/beta/story'; import ExpandedStorySection from './ExpandedStorySection'; const ExpandedStoryOwnedBy = ({ users, story, onEdit, disabled }) => <ExpandedStorySection title={I18n.t('activerecord.attributes.story.owned_by')} > <SelectUser users={users} selectedUserId={story._editing.ownedById} onEdit={onEdit} disabled={disabled} /> </ExpandedStorySection> ExpandedStoryOwnedBy.propTypes = { users: PropTypes.array.isRequired, story: editingStoryPropTypesShape.isRequired, onEdit: PropTypes.func.isRequired, disabled: PropTypes.bool.isRequired } export default ExpandedStoryOwnedBy;
ajax/libs/analytics.js/2.8.22/analytics.js
qooxdoo/cdnjs
(function umd(require){ if ('object' == typeof exports) { module.exports = require('1'); } else if ('function' == typeof define && define.amd) { define(function(){ return require('1'); }); } else { this['analytics'] = require('1'); } })((function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** * Analytics.js * * (C) 2013 Segment.io Inc. */ var _analytics = window.analytics; var Integrations = require('analytics.js-integrations'); var Analytics = require('./analytics'); var each = require('each'); /** * Expose the `analytics` singleton. */ var analytics = module.exports = exports = new Analytics(); /** * Expose require */ analytics.require = require; /** * Expose `VERSION`. */ exports.VERSION = require('../bower.json').version; /** * Add integrations. */ each(Integrations, function (name, Integration) { analytics.use(Integration); }); }, {"analytics.js-integrations":2,"./analytics":3,"each":4,"../bower.json":5}], 2: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var plugins = require('./integrations.js'); /** * Expose the integrations, using their own `name` from their `prototype`. */ each(plugins, function(plugin){ var name = (plugin.Integration || plugin).prototype.name; exports[name] = plugin; }); }, {"each":4,"./integrations.js":6}], 4: [function(require, module, exports) { /** * Module dependencies. */ var type = require('type'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)`. * * @param {String|Array|Object} obj * @param {Function} fn * @api public */ 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); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @api private */ function string(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @api private */ function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @api private */ function array(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj[i], i); } } }, {"type":7}], 7: [function(require, module, exports) { /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object Error]': return 'error'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val !== val) return 'nan'; if (val && val.nodeType === 1) return 'element'; val = val.valueOf ? val.valueOf() : Object.prototype.valueOf.apply(val) return typeof val; }; }, {}], 6: [function(require, module, exports) { /** * DON'T EDIT THIS FILE. It's automatically generated! */ module.exports = [ require('./lib/adroll'), require('./lib/adwords'), require('./lib/alexa'), require('./lib/amplitude'), require('./lib/appcues'), require('./lib/atatus'), require('./lib/autosend'), require('./lib/awesm'), require('./lib/bing-ads'), require('./lib/blueshift'), require('./lib/bronto'), require('./lib/bugherd'), require('./lib/bugsnag'), require('./lib/chameleon'), require('./lib/chartbeat'), require('./lib/clicktale'), require('./lib/clicky'), require('./lib/comscore'), require('./lib/crazy-egg'), require('./lib/curebit'), require('./lib/customerio'), require('./lib/drip'), require('./lib/errorception'), require('./lib/evergage'), require('./lib/extole'), require('./lib/facebook-conversion-tracking'), require('./lib/foxmetrics'), require('./lib/frontleaf'), require('./lib/fullstory'), require('./lib/gauges'), require('./lib/get-satisfaction'), require('./lib/google-analytics'), require('./lib/google-tag-manager'), require('./lib/gosquared'), require('./lib/heap'), require('./lib/hellobar'), require('./lib/hittail'), require('./lib/hubspot'), require('./lib/improvely'), require('./lib/insidevault'), require('./lib/inspectlet'), require('./lib/intercom'), require('./lib/keen-io'), require('./lib/kenshoo'), require('./lib/kissmetrics'), require('./lib/klaviyo'), require('./lib/livechat'), require('./lib/lucky-orange'), require('./lib/lytics'), require('./lib/mixpanel'), require('./lib/mojn'), require('./lib/mouseflow'), require('./lib/mousestats'), require('./lib/navilytics'), require('./lib/nudgespot'), require('./lib/olark'), require('./lib/optimizely'), require('./lib/outbound'), require('./lib/perfect-audience'), require('./lib/pingdom'), require('./lib/piwik'), require('./lib/preact'), require('./lib/qualaroo'), require('./lib/quantcast'), require('./lib/rollbar'), require('./lib/saasquatch'), require('./lib/satismeter'), require('./lib/segmentio'), require('./lib/sentry'), require('./lib/snapengage'), require('./lib/spinnakr'), require('./lib/supporthero'), require('./lib/tapstream'), require('./lib/trakio'), require('./lib/twitter-ads'), require('./lib/userlike'), require('./lib/uservoice'), require('./lib/vero'), require('./lib/visual-website-optimizer'), require('./lib/webengage'), require('./lib/woopra'), require('./lib/yandex-metrica') ]; }, {"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/atatus":13,"./lib/autosend":14,"./lib/awesm":15,"./lib/bing-ads":16,"./lib/blueshift":17,"./lib/bronto":18,"./lib/bugherd":19,"./lib/bugsnag":20,"./lib/chameleon":21,"./lib/chartbeat":22,"./lib/clicktale":23,"./lib/clicky":24,"./lib/comscore":25,"./lib/crazy-egg":26,"./lib/curebit":27,"./lib/customerio":28,"./lib/drip":29,"./lib/errorception":30,"./lib/evergage":31,"./lib/extole":32,"./lib/facebook-conversion-tracking":33,"./lib/foxmetrics":34,"./lib/frontleaf":35,"./lib/fullstory":36,"./lib/gauges":37,"./lib/get-satisfaction":38,"./lib/google-analytics":39,"./lib/google-tag-manager":40,"./lib/gosquared":41,"./lib/heap":42,"./lib/hellobar":43,"./lib/hittail":44,"./lib/hubspot":45,"./lib/improvely":46,"./lib/insidevault":47,"./lib/inspectlet":48,"./lib/intercom":49,"./lib/keen-io":50,"./lib/kenshoo":51,"./lib/kissmetrics":52,"./lib/klaviyo":53,"./lib/livechat":54,"./lib/lucky-orange":55,"./lib/lytics":56,"./lib/mixpanel":57,"./lib/mojn":58,"./lib/mouseflow":59,"./lib/mousestats":60,"./lib/navilytics":61,"./lib/nudgespot":62,"./lib/olark":63,"./lib/optimizely":64,"./lib/outbound":65,"./lib/perfect-audience":66,"./lib/pingdom":67,"./lib/piwik":68,"./lib/preact":69,"./lib/qualaroo":70,"./lib/quantcast":71,"./lib/rollbar":72,"./lib/saasquatch":73,"./lib/satismeter":74,"./lib/segmentio":75,"./lib/sentry":76,"./lib/snapengage":77,"./lib/spinnakr":78,"./lib/supporthero":79,"./lib/tapstream":80,"./lib/trakio":81,"./lib/twitter-ads":82,"./lib/userlike":83,"./lib/uservoice":84,"./lib/vero":85,"./lib/visual-website-optimizer":86,"./lib/webengage":87,"./lib/woopra":88,"./lib/yandex-metrica":89}], 8: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var snake = require('to-snake-case'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); var del = require('obj-case').del; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdRoll` integration. */ var AdRoll = module.exports = integration('AdRoll') .assumesPageview() .global('__adroll_loaded') .global('adroll_adv_id') .global('adroll_pix_id') .global('adroll_custom_data') .option('advId', '') .option('pixId', '') .tag('http', '<script src="http://a.adroll.com/j/roundtrip.js">') .tag('https', '<script src="https://s.adroll.com/j/roundtrip.js">') .mapping('events'); /** * Initialize. * * http://support.adroll.com/getting-started-in-4-easy-steps/#step-one * http://support.adroll.com/enhanced-conversion-tracking/ * * @param {Object} page */ AdRoll.prototype.initialize = function(page){ window.adroll_adv_id = this.options.advId; window.adroll_pix_id = this.options.pixId; window.__adroll_loaded = true; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ AdRoll.prototype.loaded = function(){ return window.__adroll; }; /** * Page. * * http://support.adroll.com/segmenting-clicks/ * * @param {Page} page */ AdRoll.prototype.page = function(page){ var name = page.fullName(); this.track(page.track(name)); }; /** * Track. * * @param {Track} track */ AdRoll.prototype.track = function(track){ var event = track.event(); var user = this.analytics.user(); var events = this.events(event); var total = track.revenue() || track.total() || 0; var orderId = track.orderId() || 0; var productId = track.id(); var sku = track.sku(); var customProps = track.properties(); var data = {}; if (user.id()) data.user_id = user.id(); if (orderId) data.order_id = orderId; if (productId) data.product_id = productId; if (sku) data.sku = sku; if (total) data.adroll_conversion_value_in_dollars = total; del(customProps, "revenue"); del(customProps, "total"); del(customProps, "orderId"); del(customProps, "id"); del(customProps, "sku"); if (!is.empty(customProps)) data.adroll_custom_data = customProps; each(events, function(event){ // the adroll interface only allows for // segment names which are snake cased. data.adroll_segments = snake(event); window.__adroll.record_user(data); }); // no events found if (!events.length) { data.adroll_segments = snake(event); window.__adroll.record_user(data); } }; }, {"analytics.js-integration":90,"to-snake-case":91,"use-https":92,"each":4,"is":93,"obj-case":94}], 90: [function(require, module, exports) { /** * Module dependencies. */ var bind = require('bind'); var clone = require('clone'); var debug = require('debug'); var defaults = require('defaults'); var extend = require('extend'); var slug = require('slug'); var protos = require('./protos'); var statics = require('./statics'); /** * Create a new `Integration` constructor. * * @constructs Integration * @param {string} name * @return {Function} Integration */ function createIntegration(name){ /** * Initialize a new `Integration`. * * @class * @param {Object} options */ function Integration(options){ if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } 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.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); } Integration.prototype.defaults = {}; Integration.prototype.globals = []; Integration.prototype.templates = {}; Integration.prototype.name = name; extend(Integration, statics); extend(Integration.prototype, protos); return Integration; } /** * Exports. */ module.exports = createIntegration; }, {"bind":95,"clone":96,"debug":97,"defaults":98,"extend":99,"slug":100,"./protos":101,"./statics":102}], 95: [function(require, module, exports) { var bind = require('bind') , bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ 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; } }, {"bind":103,"bind-all":104}], 103: [function(require, module, exports) { /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ 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))); } }; }, {}], 104: [function(require, module, exports) { 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; }; }, {"bind":103,"type":7}], 96: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ 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': // from millermedeiros/amd-utils - MIT 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: // string, number, boolean, … return obj; } } }, {"type":7}], 97: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":105,"./debug":106}], 105: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , 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'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 106: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ 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); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ 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 + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , 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'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ 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; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 98: [function(require, module, exports) { 'use strict'; /** * Merge default values. * * @param {Object} dest * @param {Object} defaults * @return {Object} * @api public */ 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; }; /** * Expose `defaults`. */ module.exports = defaults; }, {}], 99: [function(require, module, exports) { module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }, {}], 100: [function(require, module, exports) { /** * Generate a slug from the given `str`. * * example: * * generate('foo bar'); * // > foo-bar * * @param {String} str * @param {Object} options * @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g` * @config {String} [separator] separator to insert, defaulted to `-` * @return {String} */ module.exports = function (str, options) { options || (options = {}); return str.toLowerCase() .replace(options.replace || /[^a-z0-9]/g, ' ') .replace(/^ +| +$/g, '') .replace(/ +/g, options.separator || '-') }; }, {}], 101: [function(require, module, exports) { /* global setInterval:true setTimeout:true */ /** * Module dependencies. */ var Emitter = require('emitter'); var after = require('after'); var each = require('each'); var events = require('analytics-events'); var fmt = require('fmt'); var foldl = require('foldl'); var loadIframe = require('load-iframe'); var loadScript = require('load-script'); var normalize = require('to-no-case'); var nextTick = require('next-tick'); var type = require('type'); /** * Noop. */ function noop(){} /** * hasOwnProperty reference. */ var has = Object.prototype.hasOwnProperty; /** * Window defaults. */ var onerror = window.onerror; var onload = null; var setInterval = window.setInterval; var setTimeout = window.setTimeout; /** * Mixin emitter. */ /* eslint-disable new-cap */ Emitter(exports); /* eslint-enable new-cap */ /** * Initialize. */ exports.initialize = function(){ var ready = this.ready; nextTick(ready); }; /** * Loaded? * * @api private * @return {boolean} */ exports.loaded = function(){ return false; }; /** * Page. * * @api public * @param {Page} page */ /* eslint-disable no-unused-vars */ exports.page = function(page){}; /* eslint-enable no-unused-vars */ /** * Track. * * @api public * @param {Track} track */ /* eslint-disable no-unused-vars */ exports.track = function(track){}; /* eslint-enable no-unused-vars */ /** * Get events that match `event`. * * @api public * @param {Object|Object[]} events An object or array of objects pulled from * settings.mapping. * @param {string} event The name of the event whose metdata we're looking for. * @return {Array} An array of settings that match the input `event` name. * @example * var events = { my_event: 'a4991b88' }; * .map(events, 'My Event'); * // => ["a4991b88"] * .map(events, 'whatever'); * // => [] * * var events = [{ key: 'my event', value: '9b5eb1fa' }]; * .map(events, 'my_event'); * // => ["9b5eb1fa"] * .map(events, 'whatever'); * // => [] */ exports.map = function(events, event){ var normalizedEvent = normalize(event); return foldl(function(matchingEvents, val, key, events) { // If true, this is a `mixed` value, which is structured like so: // { key: 'testEvent', value: { event: 'testEvent', someValue: 'xyz' } } // We need to extract the key, which we use to match against // `normalizedEvent`, and return `value` as part of `matchingEvents` if that // match succeds. if (type(events) === 'array') { // If there's no key attached to this event mapping (unusual), skip this // item. if (!val.key) return matchingEvents; // Extract the key and value from the `mixed` object. key = val.key; val = val.value; } if (normalize(key) === normalizedEvent) { matchingEvents.push(val); } return matchingEvents; }, [], events); }; /** * Invoke a `method` that may or may not exist on the prototype with `args`, * queueing or not depending on whether the integration is "ready". Don't * trust the method call, since it contains integration party code. * * @api private * @param {string} method * @param {...*} args */ exports.invoke = function(method){ if (!this[method]) return; var args = Array.prototype.slice.call(arguments, 1); if (!this._ready) return this.queue(method, args); var ret; try { this.debug('%s with %o', method, args); ret = this[method].apply(this, args); } catch (e) { this.debug('error %o calling %s with %o', e, method, args); } return ret; }; /** * Queue a `method` with `args`. If the integration assumes an initial * pageview, then let the first call to `page` pass through. * * @api private * @param {string} method * @param {Array} args */ exports.queue = function(method, args){ if (method === 'page' && this._assumesPageview && !this._initialized) { return this.page.apply(this, args); } this._queue.push({ method: method, args: args }); }; /** * Flush the internal queue. * * @api private */ exports.flush = function(){ this._ready = true; var self = this; each(this._queue, function(call){ self[call.method].apply(self, call.args); }); // Empty the queue. this._queue.length = 0; }; /** * Reset the integration, removing its global variables. * * @api private */ exports.reset = function(){ for (var i = 0; i < this.globals.length; i++) { window[this.globals[i]] = undefined; } window.setTimeout = setTimeout; window.setInterval = setInterval; window.onerror = onerror; window.onload = onload; }; /** * Load a tag by `name`. * * @param {string} name The name of the tag. * @param {Object} locals Locals used to populate the tag's template variables * (e.g. `userId` in '<img src="https://whatever.com/{{ userId }}">'). * @param {Function} [callback=noop] A callback, invoked when the tag finishes * loading. */ exports.load = function(name, locals, callback){ // Argument shuffling if (typeof name === 'function') { callback = name; locals = null; name = null; } if (name && typeof name === 'object') { callback = locals; locals = name; name = null; } if (typeof locals === 'function') { callback = locals; locals = null; } // Default arguments name = name || 'library'; locals = locals || {}; locals = this.locals(locals); var template = this.templates[name]; if (!template) throw new Error(fmt('template "%s" not defined.', name)); var attrs = render(template, locals); callback = callback || noop; var self = this; var el; switch (template.type) { case 'img': attrs.width = 1; attrs.height = 1; el = loadImage(attrs, callback); break; case 'script': el = loadScript(attrs, function(err){ if (!err) return callback(); self.debug('error loading "%s" error="%s"', self.name, err); }); // TODO: hack until refactoring load-script delete attrs.src; each(attrs, function(key, val){ el.setAttribute(key, val); }); break; case 'iframe': el = loadIframe(attrs, callback); break; default: // No default case } return el; }; /** * Locals for tag templates. * * By default it includes a cache buster and all of the options. * * @param {Object} [locals] * @return {Object} */ exports.locals = function(locals){ locals = locals || {}; var cache = Math.floor(new Date().getTime() / 3600000); if (!locals.hasOwnProperty('cache')) locals.cache = cache; each(this.options, function(key, val){ if (!locals.hasOwnProperty(key)) locals[key] = val; }); return locals; }; /** * Simple way to emit ready. * * @api public */ exports.ready = function(){ this.emit('ready'); }; /** * Wrap the initialize method in an exists check, so we don't have to do it for * every single integration. * * @api private */ exports._wrapInitialize = function(){ var initialize = this.initialize; this.initialize = function(){ this.debug('initialize'); this._initialized = true; var ret = initialize.apply(this, arguments); this.emit('initialize'); return ret; }; if (this._assumesPageview) this.initialize = after(2, this.initialize); }; /** * Wrap the page method to call `initialize` instead if the integration assumes * a pageview. * * @api private */ exports._wrapPage = function(){ var page = this.page; this.page = function(){ if (this._assumesPageview && !this._initialized) { return this.initialize.apply(this, arguments); } return page.apply(this, arguments); }; }; /** * Wrap the track method to call other ecommerce methods if available depending * on the `track.event()`. * * @api private */ exports._wrapTrack = function(){ var t = this.track; this.track = function(track){ var event = track.event(); var called; var ret; for (var method in events) { if (has.call(events, method)) { var regexp = events[method]; if (!this[method]) continue; if (!regexp.test(event)) continue; ret = this[method].apply(this, arguments); called = true; break; } } if (!called) ret = t.apply(this, arguments); return ret; }; }; /** * TODO: Document me * * @api private * @param {Object} attrs * @param {Function} fn * @return {undefined} */ function loadImage(attrs, fn){ fn = fn || function(){}; var img = new Image(); img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; img.src = attrs.src; img.width = 1; img.height = 1; return img; } /** * TODO: Document me * * @api private * @param {Function} fn * @param {string} message * @param {Element} img * @return {Function} */ 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); }; } /** * Render template + locals into an `attrs` object. * * @api private * @param {Object} template * @param {Object} locals * @return {Object} */ function render(template, locals){ return foldl(function(attrs, val, key) { attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){ return locals[$1]; }); return attrs; }, {}, template.attrs); } }, {"emitter":107,"after":108,"each":109,"analytics-events":110,"fmt":111,"foldl":112,"load-iframe":113,"load-script":114,"to-no-case":115,"next-tick":116,"type":117}], 107: [function(require, module, exports) { /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ 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; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ 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; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {"indexof":118}], 118: [function(require, module, exports) { 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; }; }, {}], 108: [function(require, module, exports) { module.exports = function after (times, func) { // After 0, really? if (times <= 0) return func(); // That's more like it. return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; }, {}], 109: [function(require, module, exports) { /** * Module dependencies. */ try { var type = require('type'); } catch (err) { var type = require('component-type'); } var toFunction = require('to-function'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)` * in optional context `ctx`. * * @param {String|Array|Object} obj * @param {Function} fn * @param {Object} [ctx] * @api public */ module.exports = function(obj, fn, ctx){ fn = toFunction(fn); ctx = ctx || this; switch (type(obj)) { case 'array': return array(obj, fn, ctx); case 'object': if ('number' == typeof obj.length) return array(obj, fn, ctx); return object(obj, fn, ctx); case 'string': return string(obj, fn, ctx); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @param {Object} ctx * @api private */ function string(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function object(obj, fn, ctx) { for (var key in obj) { if (has.call(obj, key)) { fn.call(ctx, key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function array(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj[i], i); } } }, {"type":117,"component-type":117,"to-function":119}], 117: [function(require, module, exports) { /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ 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; }; }, {}], 119: [function(require, module, exports) { /** * Module Dependencies */ var expr; try { expr = require('props'); } catch(e) { expr = require('component-props'); } /** * Expose `toFunction()`. */ module.exports = toFunction; /** * Convert `obj` to a `Function`. * * @param {Mixed} obj * @return {Function} * @api private */ function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } } /** * Default to strict equality. * * @param {Mixed} val * @return {Function} * @api private */ function defaultToFunction(val) { return function(obj){ return val === obj; }; } /** * Convert `re` to a function. * * @param {RegExp} re * @return {Function} * @api private */ function regexpToFunction(re) { return function(obj){ return re.test(obj); }; } /** * Convert property `str` to a function. * * @param {String} str * @return {Function} * @api private */ function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" or "age > 18 && age < 36" return new Function('_', 'return ' + get(str)); } /** * Convert `object` to a function. * * @param {Object} object * @return {Function} * @api private */ function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; } /** * Built the getter function. Supports getter style functions * * @param {String} str * @return {String} * @api private */ function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; } /** * Mimic negative lookbehind to avoid problems with nested properties. * * See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript * * @param {String} prop * @param {String} str * @param {String} val * @return {String} * @api private */ function stripNested (prop, str, val) { return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) { return $1 ? $0 : val; }); } }, {"props":120,"component-props":120}], 120: [function(require, module, exports) { /** * Global Names */ var globals = /\b(this|Array|Date|Object|Math|JSON)\b/g; /** * Return immediate identifiers parsed from `str`. * * @param {String} str * @param {String|Function} map function or prefix * @return {Array} * @api public */ module.exports = function(str, fn){ var p = unique(props(str)); if (fn && 'string' == typeof fn) fn = prefixed(fn); if (fn) return map(str, p, fn); return p; }; /** * Return immediate identifiers in `str`. * * @param {String} str * @return {Array} * @api private */ function props(str) { return str .replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '') .replace(globals, '') .match(/[$a-zA-Z_]\w*/g) || []; } /** * Return `str` with `props` mapped with `fn`. * * @param {String} str * @param {Array} props * @param {Function} fn * @return {String} * @api private */ function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); } /** * Return unique array. * * @param {Array} arr * @return {Array} * @api private */ function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; } /** * Map with prefix `str`. */ function prefixed(str) { return function(_){ return str + _; }; } }, {}], 110: [function(require, module, exports) { module.exports = { removedProduct: /^[ _]?removed[ _]?product[ _]?$/i, viewedProduct: /^[ _]?viewed[ _]?product[ _]?$/i, viewedProductCategory: /^[ _]?viewed[ _]?product[ _]?category[ _]?$/i, addedProduct: /^[ _]?added[ _]?product[ _]?$/i, completedOrder: /^[ _]?completed[ _]?order[ _]?$/i, startedOrder: /^[ _]?started[ _]?order[ _]?$/i, updatedOrder: /^[ _]?updated[ _]?order[ _]?$/i, refundedOrder: /^[ _]?refunded?[ _]?order[ _]?$/i, viewedProductDetails: /^[ _]?viewed[ _]?product[ _]?details?[ _]?$/i, clickedProduct: /^[ _]?clicked[ _]?product[ _]?$/i, viewedPromotion: /^[ _]?viewed[ _]?promotion?[ _]?$/i, clickedPromotion: /^[ _]?clicked[ _]?promotion?[ _]?$/i, viewedCheckoutStep: /^[ _]?viewed[ _]?checkout[ _]?step[ _]?$/i, completedCheckoutStep: /^[ _]?completed[ _]?checkout[ _]?step[ _]?$/i }; }, {}], 111: [function(require, module, exports) { /** * toString. */ var toString = window.JSON ? JSON.stringify : function(_){ return String(_); }; /** * Export `fmt` */ module.exports = fmt; /** * Formatters */ fmt.o = toString; fmt.s = String; fmt.d = parseInt; /** * Format the given `str`. * * @param {String} str * @param {...} args * @return {String} * @api public */ function fmt(str){ var args = [].slice.call(arguments, 1); var j = 0; return str.replace(/%([a-z])/gi, function(_, f){ return fmt[f] ? fmt[f](args[j++]) : _ + f; }); } }, {}], 112: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ // XXX: Hacky fix for Duo not supporting scoped modules var each; try { each = require('@ndhoule/each'); } catch(e) { each = require('each'); } /** * Reduces all the values in a collection down into a single value. Does so by iterating through the * collection from left to right, repeatedly calling an `iterator` function and passing to it four * arguments: `(accumulator, value, index, collection)`. * * Returns the final return value of the `iterator` function. * * @name foldl * @api public * @param {Function} iterator The function to invoke per iteration. * @param {*} accumulator The initial accumulator value, passed to the first invocation of `iterator`. * @param {Array|Object} collection The collection to iterate over. * @return {*} The return value of the final call to `iterator`. * @example * foldl(function(total, n) { * return total + n; * }, 0, [1, 2, 3]); * //=> 6 * * var phonebook = { bob: '555-111-2345', tim: '655-222-6789', sheila: '655-333-1298' }; * * foldl(function(results, phoneNumber) { * if (phoneNumber[0] === '6') { * return results.concat(phoneNumber); * } * return results; * }, [], phonebook); * // => ['655-222-6789', '655-333-1298'] */ var foldl = function foldl(iterator, accumulator, collection) { if (typeof iterator !== 'function') { throw new TypeError('Expected a function but received a ' + typeof iterator); } each(function(val, i, collection) { accumulator = iterator(accumulator, val, i, collection); }, collection); return accumulator; }; /** * Exports. */ module.exports = foldl; }, {"each":121}], 121: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ // XXX: Hacky fix for Duo not supporting scoped modules var keys; try { keys = require('@ndhoule/keys'); } catch(e) { keys = require('keys'); } /** * Object.prototype.toString reference. */ var objToString = Object.prototype.toString; /** * Tests if a value is a number. * * @name isNumber * @api private * @param {*} val The value to test. * @return {boolean} Returns `true` if `val` is a number, otherwise `false`. */ // TODO: Move to library var isNumber = function isNumber(val) { var type = typeof val; return type === 'number' || (type === 'object' && objToString.call(val) === '[object Number]'); }; /** * Tests if a value is an array. * * @name isArray * @api private * @param {*} val The value to test. * @return {boolean} Returns `true` if the value is an array, otherwise `false`. */ // TODO: Move to library var isArray = typeof Array.isArray === 'function' ? Array.isArray : function isArray(val) { return objToString.call(val) === '[object Array]'; }; /** * Tests if a value is array-like. Array-like means the value is not a function and has a numeric * `.length` property. * * @name isArrayLike * @api private * @param {*} val * @return {boolean} */ // TODO: Move to library var isArrayLike = function isArrayLike(val) { return val != null && (isArray(val) || (val !== 'function' && isNumber(val.length))); }; /** * Internal implementation of `each`. Works on arrays and array-like data structures. * * @name arrayEach * @api private * @param {Function(value, key, collection)} iterator The function to invoke per iteration. * @param {Array} array The array(-like) structure to iterate over. * @return {undefined} */ var arrayEach = function arrayEach(iterator, array) { for (var i = 0; i < array.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(array[i], i, array) === false) { break; } } }; /** * Internal implementation of `each`. Works on objects. * * @name baseEach * @api private * @param {Function(value, key, collection)} iterator The function to invoke per iteration. * @param {Object} object The object to iterate over. * @return {undefined} */ var baseEach = function baseEach(iterator, object) { var ks = keys(object); for (var i = 0; i < ks.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(object[ks[i]], ks[i], object) === false) { break; } } }; /** * Iterate over an input collection, invoking an `iterator` function for each element in the * collection and passing to it three arguments: `(value, index, collection)`. The `iterator` * function can end iteration early by returning `false`. * * @name each * @api public * @param {Function(value, key, collection)} iterator The function to invoke per iteration. * @param {Array|Object|string} collection The collection to iterate over. * @return {undefined} Because `each` is run only for side effects, always returns `undefined`. * @example * var log = console.log.bind(console); * * each(log, ['a', 'b', 'c']); * //-> 'a', 0, ['a', 'b', 'c'] * //-> 'b', 1, ['a', 'b', 'c'] * //-> 'c', 2, ['a', 'b', 'c'] * //=> undefined * * each(log, 'tim'); * //-> 't', 2, 'tim' * //-> 'i', 1, 'tim' * //-> 'm', 0, 'tim' * //=> undefined * * // Note: Iteration order not guaranteed across environments * each(log, { name: 'tim', occupation: 'enchanter' }); * //-> 'tim', 'name', { name: 'tim', occupation: 'enchanter' } * //-> 'enchanter', 'occupation', { name: 'tim', occupation: 'enchanter' } * //=> undefined */ var each = function each(iterator, collection) { return (isArrayLike(collection) ? arrayEach : baseEach).call(this, iterator, collection); }; /** * Exports. */ module.exports = each; }, {"keys":122}], 122: [function(require, module, exports) { 'use strict'; /** * charAt reference. */ var strCharAt = String.prototype.charAt; /** * Returns the character at a given index. * * @param {string} str * @param {number} index * @return {string|undefined} */ // TODO: Move to a library var charAt = function(str, index) { return strCharAt.call(str, index); }; /** * hasOwnProperty reference. */ var hop = Object.prototype.hasOwnProperty; /** * Object.prototype.toString reference. */ var toStr = Object.prototype.toString; /** * hasOwnProperty, wrapped as a function. * * @name has * @api private * @param {*} context * @param {string|number} prop * @return {boolean} */ // TODO: Move to a library var has = function has(context, prop) { return hop.call(context, prop); }; /** * Returns true if a value is a string, otherwise false. * * @name isString * @api private * @param {*} val * @return {boolean} */ // TODO: Move to a library var isString = function isString(val) { return toStr.call(val) === '[object String]'; }; /** * Returns true if a value is array-like, otherwise false. Array-like means a * value is not null, undefined, or a function, and has a numeric `length` * property. * * @name isArrayLike * @api private * @param {*} val * @return {boolean} */ // TODO: Move to a library var isArrayLike = function isArrayLike(val) { return val != null && (typeof val !== 'function' && typeof val.length === 'number'); }; /** * indexKeys * * @name indexKeys * @api private * @param {} target * @param {} pred * @return {Array} */ var indexKeys = function indexKeys(target, pred) { pred = pred || has; var results = []; for (var i = 0, len = target.length; i < len; i += 1) { if (pred(target, i)) { results.push(String(i)); } } return results; }; /** * Returns an array of all the owned * * @name objectKeys * @api private * @param {*} target * @param {Function} pred Predicate function used to include/exclude values from * the resulting array. * @return {Array} */ var objectKeys = function objectKeys(target, pred) { pred = pred || has; var results = []; for (var key in target) { if (pred(target, key)) { results.push(String(key)); } } return results; }; /** * Creates an array composed of all keys on the input object. Ignores any non-enumerable properties. * More permissive than the native `Object.keys` function (non-objects will not throw errors). * * @name keys * @api public * @category Object * @param {Object} source The value to retrieve keys from. * @return {Array} An array containing all the input `source`'s keys. * @example * keys({ likes: 'avocado', hates: 'pineapple' }); * //=> ['likes', 'pineapple']; * * // Ignores non-enumerable properties * var hasHiddenKey = { name: 'Tim' }; * Object.defineProperty(hasHiddenKey, 'hidden', { * value: 'i am not enumerable!', * enumerable: false * }) * keys(hasHiddenKey); * //=> ['name']; * * // Works on arrays * keys(['a', 'b', 'c']); * //=> ['0', '1', '2'] * * // Skips unpopulated indices in sparse arrays * var arr = [1]; * arr[4] = 4; * keys(arr); * //=> ['0', '4'] */ module.exports = function keys(source) { if (source == null) { return []; } // IE6-8 compatibility (string) if (isString(source)) { return indexKeys(source, charAt); } // IE6-8 compatibility (arguments) if (isArrayLike(source)) { return indexKeys(source, has); } return objectKeys(source); }; }, {}], 113: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadIframe(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<iframe>` element and insert it before the first iframe on the // page, which is guaranteed to exist since this Javaiframe is running. var iframe = document.createElement('iframe'); iframe.src = options.src; iframe.width = options.width || 1; iframe.height = options.height || 1; iframe.style.display = 'none'; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(iframe, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(iframe, firstScript); }); // Return the iframe element in case they want to do anything special, like // give it an ID or attributes. return iframe; }; }, {"script-onload":123,"next-tick":116,"type":7}], 123: [function(require, module, exports) { // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html /** * Invoke `fn(err)` when the given `el` script loads. * * @param {Element} el * @param {Function} fn * @api public */ module.exports = function(el, fn){ return el.addEventListener ? add(el, fn) : attach(el, fn); }; /** * Add event listener to `el`, `fn()`. * * @param {Element} el * @param {Function} fn * @api private */ function add(el, fn){ el.addEventListener('load', function(_, e){ fn(null, e); }, false); el.addEventListener('error', function(e){ var err = new Error('script error "' + el.src + '"'); err.event = e; fn(err); }, false); } /** * Attach event. * * @param {Element} el * @param {Function} fn * @api private */ function attach(el, fn){ el.attachEvent('onreadystatechange', function(e){ if (!/complete|loaded/.test(el.readyState)) return; fn(null, e); }); el.attachEvent('onerror', function(e){ var err = new Error('failed to load the script "' + el.src + '"'); err.event = e || window.event; fn(err); }); } }, {}], 116: [function(require, module, exports) { "use strict" if (typeof setImmediate == 'function') { module.exports = function(f){ setImmediate(f) } } // legacy node.js else if (typeof process != 'undefined' && typeof process.nextTick == 'function') { module.exports = process.nextTick } // fallback for other environments / postMessage behaves badly on IE8 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); } } }, {}], 114: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":123,"next-tick":116,"type":7}], 115: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) return unseparate(string).toLowerCase(); return uncamelize(string).toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 102: [function(require, module, exports) { /** * Module dependencies. */ var Emitter = require('emitter'); var domify = require('domify'); var each = require('each'); var includes = require('includes'); /** * Mix in emitter. */ /* eslint-disable new-cap */ Emitter(exports); /* eslint-enable new-cap */ /** * Add a new option to the integration by `key` with default `value`. * * @api public * @param {string} key * @param {*} value * @return {Integration} */ exports.option = function(key, value){ this.prototype.defaults[key] = value; return this; }; /** * Add a new mapping option. * * This will create a method `name` that will return a mapping for you to use. * * @api public * @param {string} name * @return {Integration} * @example * Integration('My Integration') * .mapping('events'); * * new MyIntegration().track('My Event'); * * .track = function(track){ * var events = this.events(track.event()); * each(events, send); * }; */ exports.mapping = function(name){ this.option(name, []); this.prototype[name] = function(str){ return this.map(this.options[name], str); }; return this; }; /** * Register a new global variable `key` owned by the integration, which will be * used to test whether the integration is already on the page. * * @api public * @param {string} key * @return {Integration} */ exports.global = function(key){ this.prototype.globals.push(key); return this; }; /** * Mark the integration as assuming an initial pageview, so to defer loading * the script until the first `page` call, noop the first `initialize`. * * @api public * @return {Integration} */ exports.assumesPageview = function(){ this.prototype._assumesPageview = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @api public * @return {Integration} */ exports.readyOnLoad = function(){ this.prototype._readyOnLoad = true; return this; }; /** * Mark the integration as being "ready" once `initialize` is called. * * @api public * @return {Integration} */ exports.readyOnInitialize = function(){ this.prototype._readyOnInitialize = true; return this; }; /** * Define a tag to be loaded. * * @api public * @param {string} [name='library'] A nicename for the tag, commonly used in * #load. Helpful when the integration has multiple tags and you need a way to * specify which of the tags you want to load at a given time. * @param {String} str DOM tag as string or URL. * @return {Integration} */ exports.tag = function(name, tag){ if (tag == null) { tag = name; name = 'library'; } this.prototype.templates[name] = objectify(tag); return this; }; /** * Given a string, give back DOM attributes. * * Do it in a way where the browser doesn't load images or iframes. It turns * out domify will load images/iframes because whenever you construct those * DOM elements, the browser immediately loads them. * * @api private * @param {string} str * @return {Object} */ function objectify(str) { // replace `src` with `data-src` to prevent image loading str = str.replace(' src="', ' data-src="'); var el = domify(str); var attrs = {}; each(el.attributes, function(attr){ // then replace it back var name = attr.name === 'data-src' ? 'src' : attr.name; if (!includes(attr.name + '=', str)) return; attrs[name] = attr.value; }); return { type: el.tagName.toLowerCase(), attrs: attrs }; } }, {"emitter":107,"domify":124,"each":109,"includes":125}], 124: [function(require, module, exports) { /** * Expose `parse`. */ module.exports = parse; /** * Tests for browser support. */ var div = document.createElement('div'); // Setup div.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>'; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE var innerHTMLBug = !div.getElementsByTagName('link').length; div = undefined; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], // for script/link/style tags to work in IE6-8, you have to wrap // in a div with a non-whitespace character in front, ha! _default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [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.polyline = map.ellipse = map.polygon = map.circle = map.text = map.line = map.path = map.rect = map.g = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return a DOM Node instance, which could be a TextNode, * HTML DOM Node of some kind (<div> for example), or a DocumentFragment * instance, depending on the contents of the `html` string. * * @param {String} html - HTML string to "domify" * @param {Document} doc - The `document` instance to create the Node for * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance * @api private */ function parse(html, doc) { if ('string' != typeof html) throw new TypeError('String expected'); // default to the global `document` object if (!doc) doc = document; // tag name var m = /<([\w:]+)/.exec(html); if (!m) return doc.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var el = doc.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = doc.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = doc.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }, {}], 125: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ // XXX: Hacky fix for duo not supporting scoped npm packages var each; try { each = require('@ndhoule/each'); } catch(e) { each = require('each'); } /** * String#indexOf reference. */ var strIndexOf = String.prototype.indexOf; /** * Object.is/sameValueZero polyfill. * * @api private * @param {*} value1 * @param {*} value2 * @return {boolean} */ // TODO: Move to library var sameValueZero = function sameValueZero(value1, value2) { // Normal values and check for 0 / -0 if (value1 === value2) { return value1 !== 0 || 1 / value1 === 1 / value2; } // NaN return value1 !== value1 && value2 !== value2; }; /** * Searches a given `collection` for a value, returning true if the collection * contains the value and false otherwise. Can search strings, arrays, and * objects. * * @name includes * @api public * @param {*} searchElement The element to search for. * @param {Object|Array|string} collection The collection to search. * @return {boolean} * @example * includes(2, [1, 2, 3]); * //=> true * * includes(4, [1, 2, 3]); * //=> false * * includes(2, { a: 1, b: 2, c: 3 }); * //=> true * * includes('a', { a: 1, b: 2, c: 3 }); * //=> false * * includes('abc', 'xyzabc opq'); * //=> true * * includes('nope', 'xyzabc opq'); * //=> false */ var includes = function includes(searchElement, collection) { var found = false; // Delegate to String.prototype.indexOf when `collection` is a string if (typeof collection === 'string') { return strIndexOf.call(collection, searchElement) !== -1; } // Iterate through enumerable/own array elements and object properties. each(function(value) { if (sameValueZero(value, searchElement)) { found = true; // Exit iteration early when found return false; } }, collection); return found; }; /** * Exports. */ module.exports = includes; }, {"each":121}], 91: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }, {"to-space-case":126}], 126: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }, {"to-no-case":127}], 127: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasCamel = /[a-z][A-Z]/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ 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(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 92: [function(require, module, exports) { /** * Protocol. */ module.exports = function (url) { switch (arguments.length) { case 0: return check(); case 1: return transform(url); } }; /** * Transform a protocol-relative `url` to the use the proper protocol. * * @param {String} url * @return {String} */ function transform (url) { return check() ? 'https:' + url : 'http:' + url; } /** * Check whether `https:` be used for loading scripts. * * @return {Boolean} */ function check () { return ( location.protocol == 'https:' || location.protocol == 'chrome-extension:' ); } }, {}], 93: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":128,"type":7,"component-type":7}], 128: [function(require, module, exports) { /** * Expose `isEmpty`. */ module.exports = isEmpty; /** * Has. */ var has = Object.prototype.hasOwnProperty; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ 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; } }, {}], 94: [function(require, module, exports) { var identity = function(_){ return _; }; /** * Module exports, export */ module.exports = multiple(find); module.exports.find = module.exports; /** * Export the replacement function, return the modified object */ module.exports.replace = function (obj, key, val, options) { multiple(replace).call(this, obj, key, val, options); return obj; }; /** * Export the delete function, return the modified object */ module.exports.del = function (obj, key, options) { multiple(del).call(this, obj, key, null, options); return obj; }; /** * Compose applying the function to a nested key */ function multiple (fn) { return function (obj, path, val, options) { var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize; path = normalize(path); var key; var finished = false; while (!finished) loop(); function loop() { for (key in obj) { var normalizedKey = normalize(key); if (0 === path.indexOf(normalizedKey)) { var temp = path.substr(normalizedKey.length); if (temp.charAt(0) === '.' || temp.length === 0) { path = temp.substr(1); var child = obj[key]; // we're at the end and there is nothing. if (null == child) { finished = true; return; } // we're at the end and there is something. if (!path.length) { finished = true; return; } // step into child obj = child; // but we're done here return; } } } key = undefined; // if we found no matching properties // on the current object, there's no match. finished = true; } if (!key) return; if (null == obj) return obj; // the `obj` and `key` is one above the leaf object and key, so // start object: { a: { 'b.c': 10 } } // end object: { 'b.c': 10 } // end key: 'b.c' // this way, you can do `obj[key]` and get `10`. return fn(obj, key, val); }; } /** * Find an object by its key * * find({ first_name : 'Calvin' }, 'firstName') */ function find (obj, key) { if (obj.hasOwnProperty(key)) return obj[key]; } /** * Delete a value for a given key * * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' } */ function del (obj, key) { if (obj.hasOwnProperty(key)) delete obj[key]; return obj; } /** * Replace an objects existing value with a new one * * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' } */ function replace (obj, key, val) { if (obj.hasOwnProperty(key)) obj[key] = val; return obj; } /** * Normalize a `dot.separated.path`. * * A.HELL(!*&#(!)O_WOR LD.bar => ahelloworldbar * * @param {String} path * @return {String} */ function defaultNormalize(path) { return path.replace(/[^a-zA-Z0-9\.]+/g, '').toLowerCase(); } /** * Check if a value is a function. * * @param {*} val * @return {boolean} Returns `true` if `val` is a function, otherwise `false`. */ function isFunction(val) { return typeof val === 'function'; } }, {}], 9: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var domify = require('domify'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdWords`. */ var AdWords = module.exports = integration('AdWords') .option('conversionId', '') .option('remarketing', false) .tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">') .mapping('events'); /** * Load. * * @param {Function} fn * @api public */ AdWords.prototype.initialize = function(){ this.load(this.ready); }; /** * Loaded. * * @return {Boolean} * @api public */ AdWords.prototype.loaded = function(){ return !! document.body; }; /** * Page. * * https://support.google.com/adwords/answer/3111920#standard_parameters * https://support.google.com/adwords/answer/3103357 * https://developers.google.com/adwords-remarketing-tag/asynchronous/ * https://developers.google.com/adwords-remarketing-tag/parameters * * @param {Page} page */ AdWords.prototype.page = function(page){ var remarketing = !!this.options.remarketing; var id = this.options.conversionId; var props = {}; window.google_trackConversion({ google_conversion_id: id, google_custom_params: props, google_remarketing_only: remarketing }); }; /** * Track. * * @param {Track} * @api public */ AdWords.prototype.track = function(track){ var id = this.options.conversionId; var events = this.events(track.event()); var revenue = track.revenue() || 0; each(events, function(label){ var props = track.properties(); delete props.revenue window.google_trackConversion({ google_conversion_id: id, google_custom_params: props, google_conversion_language: 'en', google_conversion_format: '3', google_conversion_color: 'ffffff', google_conversion_label: label, google_conversion_value: revenue, google_remarketing_only: false }); }); }; }, {"analytics.js-integration":90,"domify":124,"each":4}], 10: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose Alexa integration. */ var Alexa = module.exports = integration('Alexa') .assumesPageview() .global('_atrk_opts') .option('account', null) .option('domain', '') .option('dynamic', true) .tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">'); /** * Initialize. * * @param {Object} page */ Alexa.prototype.initialize = function(page){ var self = this; window._atrk_opts = { atrk_acct: this.options.account, domain: this.options.domain, dynamic: this.options.dynamic }; this.load(function(){ window.atrk(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Alexa.prototype.loaded = function(){ return !! window.atrk; }; }, {"analytics.js-integration":90}], 11: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var utm = require('utm-params'); var top = require('top-domain'); /** * UMD ? */ var umd = 'function' == typeof define && define.amd; /** * Source. */ var src = '//d24n15hnbwhuhn.cloudfront.net/libs/amplitude-2.1.0-min.js'; /** * Expose `Amplitude` integration. */ var Amplitude = module.exports = integration('Amplitude') .global('amplitude') .option('apiKey', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('trackUtmProperties', true) .tag('<script src="' + src + '">'); /** * Initialize. * * https://github.com/amplitude/Amplitude-Javascript * * @param {Object} page */ Amplitude.prototype.initialize = function(page){ // jscs:disable (function(e,t){var r=e.amplitude||{};r._q=[];function a(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var i=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];for(var o=0;o<i.length;o++){a(i[o])}e.amplitude=r})(window,document); // jscs:enable this.setDomain(window.location.href); window.amplitude.init(this.options.apiKey, null, { includeUtm: this.options.trackUtmProperties }); var self = this; if (umd) { window.require([src], function(amplitude){ window.amplitude = amplitude; self.ready(); }); return; } this.load(function(){ self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Amplitude.prototype.loaded = function(){ return !! (window.amplitude && window.amplitude.options); }; /** * Page. * * @param {Page} page */ Amplitude.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Identify. * * @param {Facade} identify */ Amplitude.prototype.identify = function(identify){ var id = identify.userId(); var traits = identify.traits(); if (id) window.amplitude.setUserId(id); if (traits) window.amplitude.setUserProperties(traits); }; /** * Track. * * @param {Track} event */ Amplitude.prototype.track = function(track){ var props = track.properties(); var event = track.event(); var revenue = track.revenue(); // track the event window.amplitude.logEvent(event, props); // also track revenue if (revenue) { window.amplitude.logRevenue(revenue, props.quantity, props.productId); } }; /** * Set domain name to root domain * * @param {String} href */ Amplitude.prototype.setDomain = function(href){ var domain = top(href); window.amplitude.setDomain(domain); }; /** * Override device ID * * @param {String} deviceId */ Amplitude.prototype.setDeviceId = function(deviceId){ if (deviceId) window.amplitude.setDeviceId(deviceId); }; }, {"analytics.js-integration":90,"utm-params":129,"top-domain":130}], 129: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('querystring').parse; /** * Expose `utm` */ module.exports = utm; /** * Get all utm params from the given `querystring` * * @param {String} query * @return {Object} * @api private */ function utm(query){ if ('?' == query.charAt(0)) query = query.substring(1); var query = query.replace(/\?/g, '&'); var params = parse(query); var param; var ret = {}; for (var key in params) { if (~key.indexOf('utm_')) { param = key.substr(4); if ('campaign' == param) param = 'name'; ret[param] = params[key]; } } return ret; } }, {"querystring":131}], 131: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); var pattern = /(\w+)\[(\d+)\]/ /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = pattern.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":132,"type":7}], 132: [function(require, module, exports) { 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*$/, ''); }; }, {}], 130: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('url').parse; /** * Expose `domain` */ module.exports = domain; /** * RegExp */ var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i; /** * Get the top domain. * * Official Grammar: http://tools.ietf.org/html/rfc883#page-56 * Look for tlds with up to 2-6 characters. * * Example: * * domain('http://localhost:3000/baz'); * // => '' * domain('http://dev:3000/baz'); * // => '' * domain('http://127.0.0.1:3000/baz'); * // => '' * domain('http://segment.io/baz'); * // => 'segment.io' * * @param {String} url * @return {String} * @api public */ function domain(url){ var host = parse(url).hostname; var match = host.match(regexp); return match ? match[0] : ''; }; }, {"url":133}], 133: [function(require, module, exports) { /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host || location.host, port: ('0' === a.port || '' === a.port) ? port(a.protocol) : a.port, hash: a.hash, hostname: a.hostname || location.hostname, pathname: a.pathname.charAt(0) != '/' ? '/' + a.pathname : a.pathname, protocol: !a.protocol || ':' == a.protocol ? location.protocol : a.protocol, search: a.search, query: a.search.slice(1) }; }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ return 0 == url.indexOf('//') || !!~url.indexOf('://'); }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return !exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); var location = exports.parse(window.location.href); return url.hostname !== location.hostname || url.port !== location.port || url.protocol !== location.protocol; }; /** * Return default port for `protocol`. * * @param {String} protocol * @return {String} * @api private */ function port (protocol){ switch (protocol) { case 'http:': return 80; case 'https:': return 443; default: return location.port; } } }, {}], 12: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var load = require('load-script'); var is = require('is'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(Appcues); }; /** * Expose `Appcues` integration. */ var Appcues = exports.Integration = integration('Appcues') .assumesPageview() .global('Appcues') .option('appcuesId', ''); /** * Initialize. * * http://appcues.com/docs/ * * @param {Object} */ Appcues.prototype.initialize = function(){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Appcues.prototype.loaded = function(){ return is.object(window.Appcues); }; /** * Load the Appcues library. * * @param {Function} callback */ Appcues.prototype.load = function(callback){ var id = this.options.appcuesId || 'appcues'; var script = load('//fast.appcues.com/' + id + '.js', callback); }; /** * Identify. * * http://appcues.com/docs#identify * * @param {Identify} identify */ Appcues.prototype.identify = function(identify){ window.Appcues.identify(identify.userId(), identify.traits()); }; }, {"analytics.js-integration":90,"load-script":134,"is":93}], 134: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":123,"next-tick":116,"type":7}], 13: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Atatus` integration. */ var Atatus = module.exports = integration('Atatus') .global('atatus') .option('apiKey', '') .tag('<script src="//www.atatus.com/atatus.js">'); /** * Initialize. * * https://www.atatus.com/docs.html * * @param {Object} page */ Atatus.prototype.initialize = function(page){ var self = this; this.load(function(){ // Configure Atatus and install default handler to capture uncaught exceptions window.atatus.config(self.options.apiKey).install(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Atatus.prototype.loaded = function(){ return is.object(window.atatus); }; /** * Identify. * * @param {Identify} identify */ Atatus.prototype.identify = function(identify){ window.atatus.setCustomData({ person: identify.traits() }); }; }, {"analytics.js-integration":90,"is":93}], 14: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `Autosend` integration. */ var Autosend = module.exports = integration('Autosend') .global('_autosend') .option('appKey', '') .tag('<script id="asnd-tracker" src="https://d2zjxodm1cz8d6.cloudfront.net/js/v1/autosend.js" data-auth-key="{{ appKey }}">'); /** * Initialize. * * http://autosend.io/faq/install-autosend-using-javascript/ * * @param {Object} page */ Autosend.prototype.initialize = function(page){ window._autosend = window._autosend || []; (function(){var a,b,c;a=function(f){return function(){window._autosend.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b=["identify", "track", "cb"];for (c=0;c<b.length;c++){window._autosend[b[c]]=a(b[c]); } })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Autosend.prototype.loaded = function(){ return !! (window._autosend); }; /** * Identify. * * http://autosend.io/faq/install-autosend-using-javascript/ * * @param {Identify} identify */ Autosend.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; var traits = identify.traits(); traits.id = id; window._autosend.identify(traits); }; /** * Track. * * http://autosend.io/faq/install-autosend-using-javascript/ * * @param {Track} track */ Autosend.prototype.track = function(track){ window._autosend.track(track.event()); }; }, {"analytics.js-integration":90}], 15: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var each = require('each'); /** * Expose `Awesm` integration. */ var Awesm = module.exports = integration('awe.sm') .assumesPageview() .global('AWESM') .option('apiKey', '') .tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">') .mapping('events'); /** * Initialize. * * http://developers.awe.sm/guides/javascript/ * * @param {Object} page */ Awesm.prototype.initialize = function(page){ window.AWESM = { api_key: this.options.apiKey }; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Awesm.prototype.loaded = function(){ return !! (window.AWESM && window.AWESM._exists); }; /** * Track. * * @param {Track} track */ Awesm.prototype.track = function(track){ var user = this.analytics.user(); var goals = this.events(track.event()); each(goals, function(goal){ window.AWESM.convert(goal, track.cents(), null, user.id()); }); }; }, {"analytics.js-integration":90,"each":4}], 16: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var onbody = require('on-body'); var domify = require('domify'); var extend = require('extend'); var bind = require('bind'); var when = require('when'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Noop. */ var noop = function(){}; /** * Expose `Bing`. * * https://bingads.microsoft.com/campaign/signup */ var Bing = module.exports = integration('Bing Ads') .global('uetq') .option('tagId', '') .tag('<script src="//bat.bing.com/bat.js">'); /** * Initialize * * inferred from their snippet * https://gist.github.com/sperand-io/8bef4207e9c66e1aa83b */ Bing.prototype.initialize = function(){ window.uetq = window.uetq || []; var self = this; self.load(function(){ var setup = { ti: self.options.tagId, q: window.uetq }; window.uetq = new UET(setup); self.ready(); }); }; /** * Loaded? * * Check for custom `push` method bestowed by UET constructor * * @return {Boolean} */ Bing.prototype.loaded = function(){ return !! (window.uetq && window.uetq.push !== Array.prototype.push); }; /** * Page */ Bing.prototype.page = function(){ window.uetq.push("pageLoad"); }; /** * Track * * Send all events then set goals based * on them retroactively: http://advertise.bingads.microsoft.com/en-us/uahelp-topic?market=en&project=Bing_Ads&querytype=topic&query=HLP_BA_PROC_UET.htm * * @param {Track} track */ Bing.prototype.track = function(track){ var event = { ea: 'track', el: track.event() }; if (track.category()) event.ec = track.category(); if (track.revenue()) event.ev = track.revenue(); window.uetq.push(event); }; }, {"analytics.js-integration":90,"on-body":135,"domify":124,"extend":136,"bind":103,"when":137,"each":4}], 135: [function(require, module, exports) { var each = require('each'); /** * Cache whether `<body>` exists. */ var body = false; /** * Callbacks to call when the body exists. */ var callbacks = []; /** * Export a way to add handlers to be invoked once the body exists. * * @param {Function} callback A function to call when the body exists. */ module.exports = function onBody (callback) { if (body) { call(callback); } else { callbacks.push(callback); } }; /** * Set an interval to check for `document.body`. */ var interval = setInterval(function () { if (!document.body) return; body = true; each(callbacks, call); clearInterval(interval); }, 5); /** * Call a callback, passing it the body. * * @param {Function} callback The callback to call. */ function call (callback) { callback(document.body); } }, {"each":109}], 136: [function(require, module, exports) { module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }, {}], 137: [function(require, module, exports) { var callback = require('callback'); /** * Expose `when`. */ module.exports = when; /** * Loop on a short interval until `condition()` is true, then call `fn`. * * @param {Function} condition * @param {Function} fn * @param {Number} interval (optional) */ function when (condition, fn, interval) { if (condition()) return callback.async(fn); var ref = setInterval(function () { if (!condition()) return; callback(fn); clearInterval(ref); }, interval || 10); } }, {"callback":138}], 138: [function(require, module, exports) { var next = require('next-tick'); /** * Expose `callback`. */ module.exports = callback; /** * Call an `fn` back synchronously if it exists. * * @param {Function} fn */ function callback (fn) { if ('function' === typeof fn) fn(); } /** * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the * `fn` will be called on next tick. * * @param {Function} fn * @param {Number} wait (optional) */ callback.async = function (fn, wait) { if ('function' !== typeof fn) return; if (!wait) return next(fn); setTimeout(fn, wait); }; /** * Symmetry. */ callback.sync = callback; }, {"next-tick":116}], 17: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `Blueshift` integration. */ var Blueshift = module.exports = integration('Blueshift') .global('blueshift') .global('_blueshiftid') .option('apiKey', '') .option('retarget', false) .tag('<script src="https://cdn.getblueshift.com/blueshift.js">'); /** * Initialize. * * Documentation: http://getblueshift.com/documentation * * @param {Object} page */ Blueshift.prototype.initialize = function(page){ window.blueshift=window.blueshift||[]; // jscs:disable window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click", "pageload", "capture", "retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])}; // jscs:enable window.blueshift.load(this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Blueshift.prototype.loaded = function(){ return !! (window.blueshift && window._blueshiftid); }; /** * Page. * * @param {Page} page */ Blueshift.prototype.page = function(page){ if (this.options.retarget) window.blueshift.retarget(); var properties = page.properties(); properties._bsft_source = 'segment.com'; window.blueshift.pageload(properties); }; /** * Identify. * * @param {Identify} identify */ Blueshift.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ created: 'created_at' }); traits._bsft_source = 'segment.com'; window.blueshift.identify(traits); }; /** * Group. * * @param {Group} group */ Blueshift.prototype.group = function(group){ var traits = group.traits({ created: 'created_at' }); traits._bsft_source = 'segment.com'; window.blueshift.track('group', traits); }; /** * Track. * * @param {Track} track */ Blueshift.prototype.track = function(track){ var properties = track.properties(); properties._bsft_source = 'segment.com'; window.blueshift.track(track.event(), properties); }; }, {"analytics.js-integration":90}], 18: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var pixel = require('load-pixel')('http://app.bronto.com/public/'); var qs = require('querystring'); var each = require('each'); /** * Expose `Bronto` integration. */ var Bronto = module.exports = integration('Bronto') .global('__bta') .option('siteId', '') .option('host', '') .tag('<script src="//p.bm23.com/bta.js">'); /** * Initialize. * * http://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_data_store_js#addingjavascriptconversiontrackingtoyoursite * http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB * http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB * * @param {Object} page */ Bronto.prototype.initialize = function(page){ var self = this; var params = qs.parse(window.location.search); if (!params._bta_tid && !params._bta_c) { this.debug('missing tracking URL parameters `_bta_tid` and `_bta_c`.'); } this.load(function(){ var opts = self.options; self.bta = new window.__bta(opts.siteId); if (opts.host) self.bta.setHost(opts.host); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bronto.prototype.loaded = function(){ return this.bta; }; /** * Completed order. * * The cookie is used to link the order being processed back to the delivery, * message, and contact which makes it a conversion. * Passing in just the email ensures that the order itself * gets linked to the contact record in Bronto even if the user * does not have a tracking cookie. * * @param {Track} track * @api private */ Bronto.prototype.completedOrder = function(track){ var user = this.analytics.user(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ userId: user.id(), traits: user.traits() }); var email = identify.email(); // 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(), }); }); // add conversion this.bta.addOrder({ order_id: track.orderId(), email: email, // they recommend not putting in a date // because it needs to be formatted correctly // YYYY-MM-DDTHH:MM:SS items: items }); }; }, {"analytics.js-integration":90,"facade":139,"load-pixel":140,"querystring":141,"each":4}], 139: [function(require, module, exports) { var Facade = require('./facade'); /** * Expose `Facade` facade. */ module.exports = Facade; /** * Expose specific-method facades. */ Facade.Alias = require('./alias'); Facade.Group = require('./group'); Facade.Identify = require('./identify'); Facade.Track = require('./track'); Facade.Page = require('./page'); Facade.Screen = require('./screen'); }, {"./facade":142,"./alias":143,"./group":144,"./identify":145,"./track":146,"./page":147,"./screen":148}], 142: [function(require, module, exports) { var traverse = require('isodate-traverse'); var isEnabled = require('./is-enabled'); var clone = require('./utils').clone; var type = require('./utils').type; var address = require('./address'); var objCase = require('obj-case'); var newDate = require('new-date'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = newDate(obj.timestamp); traverse(obj); this.obj = obj; } /** * Mixin address traits. */ address(Facade.prototype); /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return transform(obj); obj = objCase(obj, fields.join('.')); return transform(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { var obj = this.obj[field]; return transform(obj); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Proxy multiple `path`. * * @param {String} path * @return {Array} */ Facade.multi = function(path){ return function(){ var multi = this.proxy(path + 's'); if ('array' == type(multi)) return multi; var one = this.proxy(path); if (one) one = [clone(one)]; return one || []; }; }; /** * Proxy one `path`. * * @param {String} path * @return {Mixed} */ Facade.one = function(path){ return function(){ var one = this.proxy(path); if (one) return one; var multi = this.proxy(path + 's'); if ('array' == type(multi)) return multi[0]; }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { var ret = clone(this.obj); if (this.type) ret.type = this.type(); return ret; }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.context = Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; var integrations = this.integrations(); var value = integrations[integration] || objCase(integrations, integration); if ('boolean' == typeof value) value = {}; return value || {}; }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ 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 = this.proxy('integrations.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.integrations(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get all `integration` options. * * @param {String} integration * @return {Object} * @api private */ Facade.prototype.integrations = function(){ return this.obj.integrations || this.proxy('options.providers') || this.options(); }; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Get `sessionId / anonymousId`. * * @return {Mixed} * @api public */ Facade.prototype.sessionId = Facade.prototype.anonymousId = function(){ return this.field('anonymousId') || this.field('sessionId'); }; /** * Get `groupId` from `context.groupId`. * * @return {String} * @api public */ Facade.prototype.groupId = Facade.proxy('options.groupId'); /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @param {Object} aliases * @return {Object} */ Facade.prototype.traits = function (aliases) { var ret = this.proxy('options.traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('options.traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Add a convenient way to get the library name and version */ Facade.prototype.library = function(){ var library = this.proxy('options.library'); if (!library) return { name: 'unknown', version: null }; if (typeof library === 'string') return { name: library, version: null }; return library; }; /** * Setup some basic proxies. */ Facade.prototype.userId = Facade.field('userId'); Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.userAgent = Facade.proxy('options.userAgent'); Facade.prototype.ip = Facade.proxy('options.ip'); /** * Return the cloned and traversed object * * @param {Mixed} obj * @return {Mixed} */ function transform(obj){ var cloned = clone(obj); return cloned; } }, {"isodate-traverse":149,"./is-enabled":150,"./utils":151,"./address":152,"obj-case":94,"new-date":153}], 149: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var each; try { each = require('each'); } catch (err) { each = require('each-component'); } /** * Expose `traverse`. */ module.exports = traverse; /** * Traverse an object or array, and return a clone with all ISO strings parsed * into Date objects. * * @param {Object} obj * @return {Object} */ function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) return object(input, strict); if (is.array(input)) return array(input, strict); return input; } /** * Object traverser. * * @param {Object} obj * @param {Boolean} strict * @return {Object} */ 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; } /** * Array traverser. * * @param {Array} arr * @param {Boolean} strict * @return {Array} */ 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; } }, {"is":154,"isodate":155,"each":4}], 154: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":128,"type":7,"component-type":7}], 155: [function(require, module, exports) { /** * Matcher, slightly modified from: * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js */ var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/; /** * Convert an ISO date string to a date. Fallback to native `Date.parse`. * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js * * @param {String} iso * @return {Date} */ exports.parse = function (iso) { var numericKeys = [1, 5, 6, 7, 11, 12]; var arr = matcher.exec(iso); var offset = 0; // fallback to native parsing if (!arr) return new Date(iso); // remove undefined values for (var i = 0, val; val = numericKeys[i]; i++) { arr[val] = parseInt(arr[val], 10) || 0; } // allow undefined days and months arr[2] = parseInt(arr[2], 10) || 1; arr[3] = parseInt(arr[3], 10) || 1; // month is 0-11 arr[2]--; // allow abitrary sub-second precision arr[8] = arr[8] ? (arr[8] + '00').substring(0, 3) : 0; // apply timezone if one exists 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); }; /** * Checks whether a `string` is an ISO date string. `strict` mode requires that * the date string at least have a year, month and date. * * @param {String} string * @param {Boolean} strict * @return {Boolean} */ exports.is = function (string, strict) { if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false; return matcher.test(string); }; }, {}], 150: [function(require, module, exports) { /** * A few integrations are disabled by default. They must be explicitly * enabled by setting options[Provider] = true. */ var disabled = { Salesforce: true }; /** * Check whether an integration should be enabled by default. * * @param {String} integration * @return {Boolean} */ module.exports = function (integration) { return ! disabled[integration]; }; }, {}], 151: [function(require, module, exports) { /** * TODO: use component symlink, everywhere ? */ try { exports.inherit = require('inherit'); exports.clone = require('clone'); exports.type = require('type'); } catch (e) { exports.inherit = require('inherit-component'); exports.clone = require('clone-component'); exports.type = require('type-component'); } }, {"inherit":156,"clone":157,"type":7}], 156: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 157: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('component-type'); } catch (_) { type = require('type'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ 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': // from millermedeiros/amd-utils - MIT 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: // string, number, boolean, … return obj; } } }, {"component-type":7,"type":7}], 152: [function(require, module, exports) { /** * Module dependencies. */ var get = require('obj-case'); /** * Add address getters to `proto`. * * @param {Function} proto */ module.exports = function(proto){ proto.zip = trait('postalCode', 'zip'); proto.country = trait('country'); proto.street = trait('street'); proto.state = trait('state'); proto.city = trait('city'); function trait(a, b){ return function(){ var traits = this.traits(); var props = this.properties ? this.properties() : {}; return get(traits, 'address.' + a) || get(traits, a) || (b ? get(traits, 'address.' + b) : null) || (b ? get(traits, b) : null) || get(props, 'address.' + a) || get(props, a) || (b ? get(props, 'address.' + b) : null) || (b ? get(props, b) : null); }; } }; }, {"obj-case":94}], 153: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var milliseconds = require('./milliseconds'); var seconds = require('./seconds'); /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|String|Number} val */ module.exports = function newDate (val) { if (is.date(val)) return val; if (is.number(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) return isodate.parse(val); if (milliseconds.is(val)) return milliseconds.parse(val); if (seconds.is(val)) return seconds.parse(val); // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {Number} num */ function toMs (num) { if (num < 31557600000) return num * 1000; return num; } }, {"is":158,"isodate":155,"./milliseconds":159,"./seconds":160}], 158: [function(require, module, exports) { var isEmpty = require('is-empty') , typeOf = require('type'); /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":128,"type":7}], 159: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{13}/; /** * Check whether a string is a millisecond date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a millisecond string to a date. * * @param {String} millis * @return {Date} */ exports.parse = function (millis) { millis = parseInt(millis, 10); return new Date(millis); }; }, {}], 160: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{10}/; /** * Check whether a string is a second date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a second string to a date. * * @param {String} seconds * @return {Date} */ exports.parse = function (seconds) { var millis = parseInt(seconds, 10) * 1000; return new Date(millis); }; }, {}], 143: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var Facade = require('./facade'); /** * Expose `Alias` facade. */ module.exports = Alias; /** * Initialize a new `Alias` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @property {String} from * @property {String} to * @property {Object} options */ function Alias (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Alias, Facade); /** * Return type of facade. * * @return {String} */ Alias.prototype.type = Alias.prototype.action = function () { return 'alias'; }; /** * Get `previousId`. * * @return {Mixed} * @api public */ Alias.prototype.from = Alias.prototype.previousId = function(){ return this.field('previousId') || this.field('from'); }; /** * Get `userId`. * * @return {String} * @api public */ Alias.prototype.to = Alias.prototype.userId = function(){ return this.field('userId') || this.field('to'); }; }, {"./utils":151,"./facade":142}], 144: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var address = require('./address'); var isEmail = require('is-email'); var newDate = require('new-date'); var Facade = require('./facade'); /** * Expose `Group` facade. */ module.exports = Group; /** * Initialize a new `Group` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} groupId * @param {Object} properties * @param {Object} options */ function Group (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Group, Facade); /** * Get the facade's action. */ Group.prototype.type = Group.prototype.action = function () { return 'group'; }; /** * Setup some basic proxies. */ Group.prototype.groupId = Facade.field('groupId'); /** * Get created or createdAt. * * @return {Date} */ 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); }; /** * Get the group's email, falling back to the group ID if it's a valid email. * * @return {String} */ Group.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var groupId = this.groupId(); if (isEmail(groupId)) return groupId; }; /** * Get the group's traits. * * @param {Object} aliases * @return {Object} */ 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; }; /** * Special traits. */ Group.prototype.name = Facade.proxy('traits.name'); Group.prototype.industry = Facade.proxy('traits.industry'); Group.prototype.employees = Facade.proxy('traits.employees'); /** * Get traits or properties. * * TODO: remove me * * @return {Object} */ Group.prototype.properties = function(){ return this.field('traits') || this.field('properties') || {}; }; }, {"./utils":151,"./address":152,"is-email":161,"new-date":153,"./facade":142}], 161: [function(require, module, exports) { /** * Expose `isEmail`. */ module.exports = isEmail; /** * Email address matcher. */ var matcher = /.+\@.+\..+/; /** * Loosely validate an email address. * * @param {String} string * @return {Boolean} */ function isEmail (string) { return matcher.test(string); } }, {}], 145: [function(require, module, exports) { var address = require('./address'); var Facade = require('./facade'); var isEmail = require('is-email'); var newDate = require('new-date'); var utils = require('./utils'); var get = require('obj-case'); var trim = require('trim'); var inherit = utils.inherit; var clone = utils.clone; var type = utils.type; /** * Expose `Idenfity` facade. */ module.exports = Identify; /** * Initialize a new `Identify` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} sessionId * @param {Object} traits * @param {Object} options */ function Identify (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Identify, Facade); /** * Get the facade's action. */ Identify.prototype.type = Identify.prototype.action = function () { return 'identify'; }; /** * Get the user's traits. * * @param {Object} aliases * @return {Object} */ 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; if (alias !== aliases[alias]) delete ret[alias]; } return ret; }; /** * Get the user's email, falling back to their user ID if it's a valid email. * * @return {String} */ Identify.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the user's created date, optionally looking for `createdAt` since lots of * people do that instead. * * @return {Date or Undefined} */ Identify.prototype.created = function () { var created = this.proxy('traits.created') || this.proxy('traits.createdAt'); if (created) return newDate(created); }; /** * Get the company created date. * * @return {Date or undefined} */ Identify.prototype.companyCreated = function(){ var created = this.proxy('traits.company.created') || this.proxy('traits.company.createdAt'); if (created) return newDate(created); }; /** * Get the user's name, optionally combining a first and last name if that's all * that was provided. * * @return {String or Undefined} */ 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); }; /** * Get the user's first name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ 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]; }; /** * Get the user's last name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ 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)); }; /** * Get the user's unique id. * * @return {String or undefined} */ Identify.prototype.uid = function(){ return this.userId() || this.username() || this.email(); }; /** * Get description. * * @return {String} */ Identify.prototype.description = function(){ return this.proxy('traits.description') || this.proxy('traits.background'); }; /** * Get the age. * * If the age is not explicitly set * the method will compute it from `.birthday()` * if possible. * * @return {Number} */ Identify.prototype.age = function(){ var date = this.birthday(); var age = get(this.traits(), 'age'); if (null != age) return age; if ('date' != type(date)) return; var now = new Date; return now.getFullYear() - date.getFullYear(); }; /** * Get the avatar. * * .photoUrl needed because help-scout * implementation uses `.avatar || .photoUrl`. * * .avatarUrl needed because trakio uses it. * * @return {Mixed} */ Identify.prototype.avatar = function(){ var traits = this.traits(); return get(traits, 'avatar') || get(traits, 'photoUrl') || get(traits, 'avatarUrl'); }; /** * Get the position. * * .jobTitle needed because some integrations use it. * * @return {Mixed} */ Identify.prototype.position = function(){ var traits = this.traits(); return get(traits, 'position') || get(traits, 'jobTitle'); }; /** * Setup sme basic "special" trait proxies. */ Identify.prototype.username = Facade.proxy('traits.username'); Identify.prototype.website = Facade.one('traits.website'); Identify.prototype.websites = Facade.multi('traits.website'); Identify.prototype.phone = Facade.one('traits.phone'); Identify.prototype.phones = Facade.multi('traits.phone'); Identify.prototype.address = Facade.proxy('traits.address'); Identify.prototype.gender = Facade.proxy('traits.gender'); Identify.prototype.birthday = Facade.proxy('traits.birthday'); }, {"./address":152,"./facade":142,"is-email":161,"new-date":153,"./utils":151,"obj-case":94,"trim":132}], 146: [function(require, module, exports) { var inherit = require('./utils').inherit; var clone = require('./utils').clone; var type = require('./utils').type; var Facade = require('./facade'); var Identify = require('./identify'); var isEmail = require('is-email'); var get = require('obj-case'); /** * Expose `Track` facade. */ module.exports = Track; /** * Initialize a new `Track` facade with a `dictionary` of arguments. * * @param {object} dictionary * @property {String} event * @property {String} userId * @property {String} sessionId * @property {Object} properties * @property {Object} options */ function Track (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Track, Facade); /** * Return the facade's action. * * @return {String} */ Track.prototype.type = Track.prototype.action = function () { return 'track'; }; /** * Setup some basic proxies. */ Track.prototype.event = Facade.field('event'); Track.prototype.value = Facade.proxy('properties.value'); /** * Misc */ Track.prototype.category = Facade.proxy('properties.category'); /** * Ecommerce */ 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.shipping = Facade.proxy('properties.shipping'); Track.prototype.discount = Facade.proxy('properties.discount'); /** * Description */ Track.prototype.description = Facade.proxy('properties.description'); /** * Plan */ Track.prototype.plan = Facade.proxy('properties.plan'); /** * Order id. * * @return {String} * @api public */ Track.prototype.orderId = function(){ return this.proxy('properties.id') || this.proxy('properties.orderId'); }; /** * Get subtotal. * * @return {Number} */ Track.prototype.subtotal = function(){ var subtotal = get(this.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; if (n = this.discount()) total += n; return total; }; /** * Get products. * * @return {Array} */ Track.prototype.products = function(){ var props = this.properties(); var products = get(props, 'products'); return 'array' == type(products) ? products : []; }; /** * Get quantity. * * @return {Number} */ Track.prototype.quantity = function(){ var props = this.obj.properties || {}; return props.quantity || 1; }; /** * Get currency. * * @return {String} */ Track.prototype.currency = function(){ var props = this.obj.properties || {}; return props.currency || 'USD'; }; /** * BACKWARDS COMPATIBILITY: should probably re-examine where these come from. */ Track.prototype.referrer = Facade.proxy('properties.referrer'); Track.prototype.query = Facade.proxy('options.query'); /** * Get the call's properties. * * @param {Object} aliases * @return {Object} */ 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 ret; }; /** * Get the call's username. * * @return {String or Undefined} */ Track.prototype.username = function () { return this.proxy('traits.username') || this.proxy('properties.username') || this.userId() || this.sessionId(); }; /** * Get the call's email, using an the user ID if it's a valid email. * * @return {String or Undefined} */ Track.prototype.email = function () { var email = this.proxy('traits.email'); email = email || this.proxy('properties.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the call's revenue, parsing it from a string with an optional leading * dollar sign. * * For products/services that don't have shipping and are not directly taxed, * they only care about tracking `revenue`. These are things like * SaaS companies, who sell monthly subscriptions. The subscriptions aren't * taxed directly, and since it's a digital product, it has no shipping. * * The only case where there's a difference between `revenue` and `total` * (in the context of analytics) is on ecommerce platforms, where they want * the `revenue` function to actually return the `total` (which includes * tax and shipping, total = subtotal + tax + shipping). This is probably * because on their backend they assume tax and shipping has been applied to * the value, and so can get the revenue on their own. * * @return {Number} */ Track.prototype.revenue = function () { var revenue = this.proxy('properties.revenue'); var event = this.event(); // it's always revenue, unless it's called during an order completion. if (!revenue && event && event.match(/completed ?order/i)) { revenue = this.proxy('properties.total'); } return currency(revenue); }; /** * Get cents. * * @return {Number} */ Track.prototype.cents = function(){ var revenue = this.revenue(); return 'number' != typeof revenue ? this.value() || 0 : revenue * 100; }; /** * A utility to turn the pieces of a track call into an identify. Used for * integrations with super properties or rate limits. * * TODO: remove me. * * @return {Facade} */ Track.prototype.identify = function () { var json = this.json(); json.traits = this.traits(); return new Identify(json); }; /** * Get float from currency value. * * @param {Mixed} val * @return {Number} */ function currency(val) { if (!val) return; if (typeof val === 'number') return val; if (typeof val !== 'string') return; val = val.replace(/\$/g, ''); val = parseFloat(val); if (!isNaN(val)) return val; } }, {"./utils":151,"./facade":142,"./identify":145,"is-email":161,"obj-case":94}], 147: [function(require, module, exports) { var inherit = require('./utils').inherit; var Facade = require('./facade'); var Track = require('./track'); /** * Expose `Page` facade */ module.exports = Page; /** * Initialize new `Page` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Page(dictionary){ Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Page, Facade); /** * Get the facade's action. * * @return {String} */ Page.prototype.type = Page.prototype.action = function(){ return 'page'; }; /** * Fields */ Page.prototype.category = Facade.field('category'); Page.prototype.name = Facade.field('name'); /** * Proxies. */ Page.prototype.title = Facade.proxy('properties.title'); Page.prototype.path = Facade.proxy('properties.path'); Page.prototype.url = Facade.proxy('properties.url'); /** * Referrer. */ Page.prototype.referrer = function(){ return this.proxy('properties.referrer') || this.proxy('context.referrer.url'); }; /** * Get the page properties mixing `category` and `name`. * * @return {Object} */ 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; }; /** * Get the page fullName. * * @return {String} */ Page.prototype.fullName = function(){ var category = this.category(); var name = this.name(); return name && category ? category + ' ' + name : name; }; /** * Get event with `name`. * * @return {String} */ Page.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Page' : 'Loaded a Page'; }; /** * Convert this Page to a Track facade with `name`. * * @param {String} name * @return {Track} */ Page.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), timestamp: this.timestamp(), context: this.context(), properties: props }); }; }, {"./utils":151,"./facade":142,"./track":146}], 148: [function(require, module, exports) { var inherit = require('./utils').inherit; var Page = require('./page'); var Track = require('./track'); /** * Expose `Screen` facade */ module.exports = Screen; /** * Initialize new `Screen` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Screen(dictionary){ Page.call(this, dictionary); } /** * Inherit from `Page` */ inherit(Screen, Page); /** * Get the facade's action. * * @return {String} * @api public */ Screen.prototype.type = Screen.prototype.action = function(){ return 'screen'; }; /** * Get event with `name`. * * @param {String} name * @return {String} * @api public */ Screen.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Screen' : 'Loaded a Screen'; }; /** * Convert this Screen. * * @param {String} name * @return {Track} * @api public */ Screen.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), timestamp: this.timestamp(), context: this.context(), properties: props }); }; }, {"./utils":151,"./page":147,"./track":146}], 140: [function(require, module, exports) { /** * Module dependencies. */ var stringify = require('querystring').stringify; var sub = require('substitute'); /** * Factory function to create a pixel loader. * * @param {String} path * @return {Function} * @api public */ 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; }; }; /** * Create an error handler. * * @param {Fucntion} fn * @param {String} message * @param {Image} img * @return {Function} * @api private */ 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); }; } }, {"querystring":131,"substitute":162}], 162: [function(require, module, exports) { /** * Expose `substitute` */ module.exports = substitute; /** * Type. */ var type = Object.prototype.toString; /** * Substitute `:prop` with the given `obj` in `str` * * @param {String} str * @param {Object or Array} obj * @param {RegExp} expr * @return {String} * @api public */ function substitute(str, obj, expr){ if (!obj) throw new TypeError('expected an object'); expr = expr || /:(\w+)/g; return str.replace(expr, function(_, prop){ switch (type.call(obj)) { case '[object Object]': return null != obj[prop] ? obj[prop] : _; case '[object Array]': var val = obj.shift(); return null != val ? val : _; } }); } }, {}], 141: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":132,"type":7}], 19: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); /** * Expose `BugHerd` integration. */ var BugHerd = module.exports = integration('BugHerd') .assumesPageview() .global('BugHerdConfig') .global('_bugHerd') .option('apiKey', '') .option('showFeedbackTab', true) .tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">'); /** * Initialize. * * http://support.bugherd.com/home * * @param {Object} page */ BugHerd.prototype.initialize = function(page){ window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }}; var ready = this.ready; this.load(function(){ tick(ready); }); }; /** * Loaded? * * @return {Boolean} */ BugHerd.prototype.loaded = function(){ return !! window._bugHerd; }; }, {"analytics.js-integration":90,"next-tick":116}], 20: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); var extend = require('extend'); var onError = require('on-error'); /** * UMD ? */ var umd = 'function' == typeof define && define.amd; /** * Source. */ var src = '//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js'; /** * Expose `Bugsnag` integration. */ var Bugsnag = module.exports = integration('Bugsnag') .global('Bugsnag') .option('apiKey', '') .tag('<script src="' + src + '">'); /** * Initialize. * * https://bugsnag.com/docs/notifiers/js * * @param {Object} page */ Bugsnag.prototype.initialize = function(page){ var self = this; if (umd) { window.require([src], function(bugsnag){ bugsnag.apiKey = self.options.apiKey; window.Bugsnag = bugsnag; self.ready(); }); return; } this.load(function(){ window.Bugsnag.apiKey = self.options.apiKey; self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bugsnag.prototype.loaded = function(){ return is.object(window.Bugsnag); }; /** * Identify. * * @param {Identify} identify */ Bugsnag.prototype.identify = function(identify){ window.Bugsnag.metaData = window.Bugsnag.metaData || {}; extend(window.Bugsnag.metaData, identify.traits()); }; }, {"analytics.js-integration":90,"is":93,"extend":136,"on-error":163}], 163: [function(require, module, exports) { /** * Expose `onError`. */ module.exports = onError; /** * Callbacks. */ var callbacks = []; /** * Preserve existing handler. */ if ('function' == typeof window.onerror) callbacks.push(window.onerror); /** * Bind to `window.onerror`. */ window.onerror = handler; /** * Error handler. */ function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); } /** * Call a `fn` on `window.onerror`. * * @param {Function} fn */ function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } } }, {}], 21: [function(require, module, exports) { var integration = require('analytics.js-integration'), each = require('each'); /** * Expose `Chameleon` integration. */ var Chameleon = module.exports = integration('Chameleon') .assumesPageview() .readyOnInitialize() .readyOnLoad() .global('chmln') .option('accountId', null) .tag('<script src="//cdn.trychameleon.com/east/{{accountId}}.min.js"></script>'); /** * Initialize Chameleon. * * @param {Facade} page */ Chameleon.prototype.initialize = function(page){ var chmln=window.chmln||(window.chmln={}),names='setup alias track set'.split(' ');for (var i=0;i<names.length;i++){(function(){var t=chmln[names[i]+'_a']=[];chmln[names[i]]=function(){t.push(arguments);};})() } this.ready(); this.load(); }; /** * Has the Chameleon library been loaded yet? * * @return {Boolean} */ Chameleon.prototype.loaded = function(){ return !!window.chmln; }; /** * Identify a user. * * @param {Facade} identify */ Chameleon.prototype.identify = function(identify){ var options = identify.traits(); options.uid = options.id || identify.userId() || identify.anonymousId(); delete options.id; window.chmln.setup(options); }; /** * Associate the current user with a group of users. * * @param {Facade} group */ Chameleon.prototype.group = function(group){ var options = {}; each(group.traits(), function(key, value){ options['group:'+key] = value; }); options['group:id'] = group.groupId(); window.chmln.set(options); }; /** * Track an event. * * @param {Facade} track */ Chameleon.prototype.track = function(track){ window.chmln.track(track.event(), track.properties()); }; /** * Change the user identifier after we know who they are. * * @param {Facade} alias */ Chameleon.prototype.alias = function(alias){ var fromId = alias.previousId() || alias.anonymousId(); window.chmln.alias({ from: fromId, to: alias.userId() }); }; }, {"analytics.js-integration":90,"each":4}], 22: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var defaults = require('defaults'); var onBody = require('on-body'); /** * Expose `Chartbeat` integration. */ var Chartbeat = module.exports = integration('Chartbeat') .assumesPageview() .global('_sf_async_config') .global('_sf_endpt') .global('pSUPERFLY') .option('domain', '') .option('uid', null) .tag('<script src="//static.chartbeat.com/js/chartbeat.js">'); /** * Initialize. * * http://chartbeat.com/docs/configuration_variables/ * * @param {Object} page */ Chartbeat.prototype.initialize = function(page){ var self = this; window._sf_async_config = window._sf_async_config || {}; window._sf_async_config.useCanonical = true; defaults(window._sf_async_config, this.options); onBody(function(){ window._sf_endpt = new Date().getTime(); // Note: Chartbeat depends on document.body existing so the script does // not load until that is confirmed. Otherwise it may trigger errors. self.load(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Chartbeat.prototype.loaded = function(){ return !! window.pSUPERFLY; }; /** * Page. * * http://chartbeat.com/docs/handling_virtual_page_changes/ * * @param {Page} page */ Chartbeat.prototype.page = function(page){ var category = page.category(); if (category) window._sf_async_config.sections = category; var author = page.proxy('properties.author'); if (author) window._sf_async_config.authors = author; var props = page.properties(); var name = page.fullName(); window.pSUPERFLY.virtualPage(props.path, name || props.title); }; }, {"analytics.js-integration":90,"defaults":164,"on-body":135}], 164: [function(require, module, exports) { /** * Expose `defaults`. */ module.exports = defaults; function defaults (dest, defaults) { for (var prop in defaults) { if (! (prop in dest)) { dest[prop] = defaults[prop]; } } return dest; }; }, {}], 23: [function(require, module, exports) { /** * Module dependencies. */ var date = require('load-date'); var domify = require('domify'); var each = require('each'); var integration = require('analytics.js-integration'); var is = require('is'); var useHttps = require('use-https'); var onBody = require('on-body'); /** * Expose `ClickTale` integration. */ var ClickTale = module.exports = integration('ClickTale') .assumesPageview() .global('WRInitTime') .global('ClickTale') .global('ClickTaleSetUID') .global('ClickTaleField') .global('ClickTaleEvent') .option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js') .option('httpsCdnUrl', '') .option('projectId', '') .option('recordingRatio', 0.01) .option('partitionId', '') .tag('<script src="{{src}}">'); /** * Initialize. * * http://wiki.clicktale.com/Article/JavaScript_API * * @param {Object} page */ ClickTale.prototype.initialize = function(page){ var self = this; window.WRInitTime = date.getTime(); onBody(function(body){ body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">')); }); var http = this.options.httpCdnUrl; var https = this.options.httpsCdnUrl; if (useHttps() && !https) return this.debug('https option required'); var src = useHttps() ? https : http; this.load({ src: src }, function(){ window.ClickTale( self.options.projectId, self.options.recordingRatio, self.options.partitionId ); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ ClickTale.prototype.loaded = function(){ return is.fn(window.ClickTale); }; /** * Identify. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField * * @param {Identify} identify */ ClickTale.prototype.identify = function(identify){ var id = identify.userId(); window.ClickTaleSetUID(id); each(identify.traits(), function(key, value){ window.ClickTaleField(key, value); }); }; /** * Track. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent * * @param {Track} track */ ClickTale.prototype.track = function(track){ window.ClickTaleEvent(track.event()); }; }, {"load-date":165,"domify":124,"each":4,"analytics.js-integration":90,"is":93,"use-https":92,"on-body":135}], 165: [function(require, module, exports) { /* * Load date. * * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/ */ var time = new Date() , perf = window.performance; if (perf && perf.timing && perf.timing.responseEnd) { time = new Date(perf.timing.responseEnd); } module.exports = time; }, {}], 24: [function(require, module, exports) { /** * Module dependencies. */ var Identify = require('facade').Identify; var extend = require('extend'); var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Clicky` integration. */ var Clicky = module.exports = integration('Clicky') .assumesPageview() .global('clicky') .global('clicky_site_ids') .global('clicky_custom') .option('siteId', null) .tag('<script src="//static.getclicky.com/js"></script>'); /** * Initialize. * * http://clicky.com/help/customization * * @param {Object} page */ Clicky.prototype.initialize = function(page){ var user = this.analytics.user(); window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId]; this.identify(new Identify({ userId: user.id(), traits: user.traits() })); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Clicky.prototype.loaded = function(){ return is.object(window.clicky); }; /** * Page. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Page} page */ 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); }; /** * Identify. * * @param {Identify} id (optional) */ Clicky.prototype.identify = function(identify){ window.clicky_custom = window.clicky_custom || {}; window.clicky_custom.session = window.clicky_custom.session || {}; var traits = identify.traits(); var username = identify.username(); var email = identify.email(); var name = identify.name(); if (username || email || name) traits.username = username || email || name; extend(window.clicky_custom.session, traits); }; /** * Track. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Track} event */ Clicky.prototype.track = function(track){ window.clicky.goal(track.event(), track.revenue()); }; }, {"facade":139,"extend":136,"analytics.js-integration":90,"is":93}], 25: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `Comscore` integration. */ var Comscore = module.exports = integration('comScore') .assumesPageview() .global('_comscore') .global('COMSCORE') .option('c1', '2') .option('c2', '') .tag('http', '<script src="http://b.scorecardresearch.com/beacon.js">') .tag('https', '<script src="https://sb.scorecardresearch.com/beacon.js">'); /** * Initialize. * * @param {Object} page */ Comscore.prototype.initialize = function(page){ window._comscore = window._comscore || [this.options]; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Comscore.prototype.loaded = function(){ return !! window.COMSCORE; }; /** * Page * * @param {Object} page */ Comscore.prototype.page = function(page){ window.COMSCORE.beacon(this.options); }; }, {"analytics.js-integration":90,"use-https":92}], 26: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `CrazyEgg` integration. */ var CrazyEgg = module.exports = integration('Crazy Egg') .assumesPageview() .global('CE2') .option('accountNumber', '') .tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ CrazyEgg.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,4) + '/' + number.slice(4); var cache = Math.floor(new Date().getTime() / 3600000); this.load({ path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ CrazyEgg.prototype.loaded = function(){ return !! window.CE2; }; }, {"analytics.js-integration":90}], 27: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_curebitq'); var Identify = require('facade').Identify; var throttle = require('throttle'); var Track = require('facade').Track; var iso = require('to-iso-string'); var clone = require('clone'); var each = require('each'); var bind = require('bind'); /** * Expose `Curebit` integration. */ var Curebit = module.exports = integration('Curebit') .global('_curebitq') .global('curebit') .option('siteId', '') .option('iframeWidth', '100%') .option('iframeHeight', '480') .option('iframeBorder', 0) .option('iframeId', 'curebit_integration') .option('responsive', true) .option('device', '') .option('insertIntoId', '') .option('campaigns', {}) .option('server', 'https://www.curebit.com') .tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">'); /** * Initialize. * * @param {Object} page */ Curebit.prototype.initialize = function(page){ push('init', { site_id: this.options.siteId, server: this.options.server }); this.load(this.ready); // throttle the call to `page` since curebit needs to append an iframe this.page = throttle(bind(this, this.page), 250); }; /** * Loaded? * * @return {Boolean} */ Curebit.prototype.loaded = function(){ return !!window.curebit; }; /** * Page. * * Call the `register_affiliate` method of the Curebit API that will load a * custom iframe onto the page, only if this page's path is marked as a * campaign. * * http://www.curebit.com/docs/affiliate/registration * * This is throttled to prevent accidentally drawing the iframe multiple times, * from multiple `.page()` calls. The `250` is from the curebit script. * * @param {String} url * @param {String} id * @param {Function} fn * @api private */ Curebit.prototype.injectIntoId = function(url, id, fn){ var server = this.options.server; when(function(){ return document.getElementById(id); }, function(){ var script = document.createElement('script'); script.src = url; var parent = document.getElementById(id); parent.appendChild(script); onload(script, fn); }); }; /** * Campaign tags. * * @param {Page} page */ Curebit.prototype.page = function(page){ var user = this.analytics.user(); var campaigns = this.options.campaigns; var path = window.location.pathname; if (!campaigns[path]) return; var tags = (campaigns[path] || '').split(','); if (!tags.length) return; var settings = { responsive: this.options.responsive, device: this.options.device, campaign_tags: tags, iframe: { width: this.options.iframeWidth, height: this.options.iframeHeight, id: this.options.iframeId, frameborder: this.options.iframeBorder, container: this.options.insertIntoId } }; var identify = new Identify({ userId: user.id(), traits: user.traits() }); // if we have an email, add any information about the user if (identify.email()) { settings.affiliate_member = { email: identify.email(), first_name: identify.firstName(), last_name: identify.lastName(), customer_id: identify.userId() }; } push('register_affiliate', settings); }; /** * Completed order. * * Fire the Curebit `register_purchase` with the order details and items. * * https://www.curebit.com/docs/ecommerce/custom * * @param {Track} track */ Curebit.prototype.completedOrder = function(track){ var user = this.analytics.user(); 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 }); }; }, {"analytics.js-integration":90,"global-queue":166,"facade":139,"throttle":167,"to-iso-string":168,"clone":96,"each":4,"bind":103}], 166: [function(require, module, exports) { /** * Expose `generate`. */ module.exports = generate; /** * Generate a global queue pushing method with `name`. * * @param {String} name * @param {Object} options * @property {Boolean} wrap * @return {Function} */ 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); }; } }, {}], 167: [function(require, module, exports) { /** * Module exports. */ module.exports = throttle; /** * Returns a new function that, when invoked, invokes `func` at most one time per * `wait` milliseconds. * * @param {Function} func The `Function` instance to wrap. * @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations. * @return {Function} A new function that wraps the `func` function passed in. * @api public */ function throttle (func, wait) { var rtn; // return value var last = 0; // last invokation timestamp return function throttled () { var now = new Date().getTime(); var delta = now - last; if (delta >= wait) { rtn = func.apply(this, arguments); last = now; } return rtn; }; } }, {}], 168: [function(require, module, exports) { /** * Expose `toIsoString`. */ module.exports = toIsoString; /** * Turn a `date` into an ISO string. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString * * @param {Date} date * @return {String} */ 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()/1000).toFixed(3)).slice(2, 5) + 'Z'; } /** * Pad a `number` with a ten's place zero. * * @param {Number} number * @return {String} */ function pad (number) { var n = number.toString(); return n.length === 1 ? '0' + n : n; } }, {}], 28: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var convertDates = require('convert-dates'); var Identify = require('facade').Identify; var integration = require('analytics.js-integration'); /** * Expose `Customerio` integration. */ var Customerio = module.exports = integration('Customer.io') .global('_cio') .option('siteId', '') .tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">'); /** * Initialize. * * http://customer.io/docs/api/javascript.html * * @param {Object} page */ 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(this.ready); }; /** * Loaded? * * @return {Boolean} */ Customerio.prototype.loaded = function(){ return (!! window._cio) && (window._cio.push !== Array.prototype.push); }; /** * Identify. * * http://customer.io/docs/api/javascript.html#section-Identify_customers * * @param {Identify} identify */ Customerio.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ createdAt: 'created' }); traits = alias(traits, { created: 'created_at' }); traits = convertDates(traits, convertDate); window._cio.identify(traits); }; /** * Group. * * @param {Group} group */ Customerio.prototype.group = function(group){ var traits = group.traits(); var user = this.analytics.user(); traits = alias(traits, function(trait){ return 'Group ' + trait; }); this.identify(new Identify({ userId: user.id(), traits: traits })); }; /** * Track. * * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event * * @param {Track} track */ Customerio.prototype.track = function(track){ var properties = track.properties(); properties = convertDates(properties, convertDate); window._cio.track(track.event(), properties); }; /** * Convert a date to the format Customer.io supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date.getTime() / 1000); } }, {"alias":169,"convert-dates":170,"facade":139,"analytics.js-integration":90}], 169: [function(require, module, exports) { var type = require('type'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `alias`. */ module.exports = alias; /** * Alias an `object`. * * @param {Object} obj * @param {Mixed} method */ function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } } /** * Convert the keys in an `obj` using a dictionary of `aliases`. * * @param {Object} obj * @param {Object} aliases */ function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; } /** * Convert the keys in an `obj` using a `convert` function. * * @param {Object} obj * @param {Function} convert */ function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; } }, {"type":7,"clone":157}], 170: [function(require, module, exports) { var is = require('is'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `convertDates`. */ module.exports = convertDates; /** * Recursively convert an `obj`'s dates to new values. * * @param {Object} obj * @param {Function} convert * @return {Object} */ 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; } }, {"is":93,"clone":96}], 29: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var integration = require('analytics.js-integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_dcq'); /** * Expose `Drip` integration. */ var Drip = module.exports = integration('Drip') .assumesPageview() .global('_dc') .global('_dcqi') .global('_dcq') .global('_dcs') .option('account', '') .tag('<script src="//tag.getdrip.com/{{ account }}.js">'); /** * Initialize. * * @param {Object} page */ Drip.prototype.initialize = function(page){ window._dcq = window._dcq || []; window._dcs = window._dcs || {}; window._dcs.account = this.options.account; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Drip.prototype.loaded = function(){ return is.object(window._dc); }; /** * Track. * * @param {Track} track */ Drip.prototype.track = function(track){ var props = track.properties(); var cents = track.cents(); if (cents) props.value = cents; delete props.revenue; push('track', track.event(), props); }; /** * Identify. * * @param {Identify} identify */ Drip.prototype.identify = function(identify){ push('identify', identify.traits()); }; }, {"alias":169,"analytics.js-integration":90,"is":93,"load-script":134,"global-queue":166}], 30: [function(require, module, exports) { /** * Module dependencies. */ var extend = require('extend'); var integration = require('analytics.js-integration'); var onError = require('on-error'); var push = require('global-queue')('_errs'); /** * Expose `Errorception` integration. */ var Errorception = module.exports = integration('Errorception') .assumesPageview() .global('_errs') .option('projectId', '') .option('meta', true) .tag('<script src="//beacon.errorception.com/{{ projectId }}.js">'); /** * Initialize. * * https://github.com/amplitude/Errorception-Javascript * * @param {Object} page */ Errorception.prototype.initialize = function(page){ window._errs = window._errs || [this.options.projectId]; onError(push); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Errorception.prototype.loaded = function(){ return !! (window._errs && window._errs.push !== Array.prototype.push); }; /** * Identify. * * http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html * * @param {Object} identify */ 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); }; }, {"extend":136,"analytics.js-integration":90,"on-error":163,"global-queue":166}], 31: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var integration = require('analytics.js-integration'); var push = require('global-queue')('_aaq'); /** * Expose `Evergage` integration.integration. */ var Evergage = module.exports = integration('Evergage') .assumesPageview() .global('_aaq') .option('account', '') .option('dataset', '') .tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">'); /** * Initialize. * * @param {Object} page */ 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(this.ready); }; /** * Loaded? * * @return {Boolean} */ Evergage.prototype.loaded = function(){ return !! (window._aaq && window._aaq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ 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); }; /** * Identify. * * @param {Identify} identify */ 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'); }); }; /** * Group. * * @param {Group} group */ 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'); }); }; /** * Track. * * @param {Track} track */ Evergage.prototype.track = function(track){ push('trackAction', track.event(), track.properties()); }; }, {"each":4,"analytics.js-integration":90,"global-queue":166}], 32: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ var bind = require('bind'); var domify = require('domify'); var each = require('each'); var extend = require('extend'); var integration = require('analytics.js-integration'); var json = require('json'); /** * Expose `Extole` integration. */ var Extole = module.exports = integration('Extole') .global('extole') .option('clientId', '') .mapping('events') .tag('main', '<script src="//tags.extole.com/{{ clientId }}/core.js">'); /** * Initialize. * * @param {Object} page */ Extole.prototype.initialize = function(){ if (this.loaded()) return this.ready(); this.load('main', bind(this, this.ready)); }; /** * Loaded? * * @return {Boolean} */ Extole.prototype.loaded = function(){ return !!window.extole; }; /** * Track. * * @param {Track} track */ Extole.prototype.track = function(track){ var user = this.analytics.user(); var traits = user.traits(); var userId = user.id(); var email = traits.email; if (!userId && !email) { return this.debug('User must be identified before `#track` calls'); } var event = track.event(); var extoleEvents = this.events(event); if (!extoleEvents.length) { return this.debug('No events found for %s', event); } each(extoleEvents, bind(this, function(extoleEvent){ this._registerConversion(this._createConversionTag({ type: extoleEvent, params: this._formatConversionParams(event, email, userId, track.properties()) })); })); }; /** * Register a conversion to Extole. * * @api private * @param {HTMLElement} conversionTag An Extole conversion tag. */ // TODO: If I understand Extole's lib correctly, this is sometimes async, // sometimes sync. Should probably refactor this into more predictable/sane // behavior Extole.prototype._registerConversion = function(conversionTag){ if (window.extole.main && window.extole.main.fireConversion) { return window.extole.main.fireConversion(conversionTag); } if (window.extole.initializeGo) { window.extole.initializeGo().andWhenItsReady(function(){ window.extole.main.fireConversion(conversionTag); }); } }; /** * formatConversionParams. Formats details from a Segment track event into a * data format Extole can accept. * * @param {string} event * @param {string} email * @param {string|number} userId * @param {Object} properties The result of calling `track.properties()`. * @return {Object} */ Extole.prototype._formatConversionParams = function(event, email, userId, properties){ var total; if (properties.total) { total = properties.total; delete properties.total; properties['tag:cart_value'] = total; } return extend({ 'tag:segment_event': event, e: email, partner_conversion_id: userId }, properties); }; /** * Create an Extole conversion tag. * * @param {Object} conversion An Extole conversion object. * @return {HTMLElement} */ Extole.prototype._createConversionTag = function(conversion){ return domify('<script type="extole/conversion">' + json.stringify(conversion) + '</script>'); }; }, {"bind":103,"domify":124,"each":4,"extend":136,"analytics.js-integration":90,"json":171}], 171: [function(require, module, exports) { var json = window.JSON || {}; var stringify = json.stringify; var parse = json.parse; module.exports = parse && stringify ? JSON : require('json-fallback'); }, {"json-fallback":172}], 172: [function(require, module, exports) { /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. (function () { 'use strict'; var JSON = module.exports = {}; function f(n) { // Format integers to have at least two digits. 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) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. 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) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. 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 { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. 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 = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. 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) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. 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); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. 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); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. 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, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); }, {}], 33: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_fbq'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Facebook` */ var Facebook = module.exports = integration('Facebook Conversion Tracking') .global('_fbq') .option('currency', 'USD') .tag('<script src="//connect.facebook.net/en_US/fbds.js">') .mapping('events'); /** * Initialize Facebook Conversion Tracking * * https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration * * @param {Object} page */ Facebook.prototype.initialize = function(page){ window._fbq = window._fbq || []; this.load(this.ready); window._fbq.loaded = true; }; /** * Loaded? * * @return {Boolean} */ Facebook.prototype.loaded = function(){ return !! (window._fbq && window._fbq.loaded); }; /** * Page. * * @param {Page} page */ Facebook.prototype.page = function(page){ var name = page.fullName(); this.track(page.track(name)); } /** * Track. * * https://developers.facebook.com/docs/reference/ads-api/custom-audience-website-faq/#fbpixel * * @param {Track} track */ Facebook.prototype.track = function(track){ var event = track.event(); var events = this.events(event); var revenue = track.revenue() || 0; var self = this; each(events, function(event){ push('track', event, { value: String(revenue.toFixed(2)), currency: self.options.currency }); }); }; }, {"analytics.js-integration":90,"global-queue":166,"each":4}], 34: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_fxm'); var integration = require('analytics.js-integration'); var Track = require('facade').Track; var each = require('each'); /** * Expose `FoxMetrics` integration. */ var FoxMetrics = module.exports = integration('FoxMetrics') .assumesPageview() .global('_fxm') .option('appId', '') .tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">'); /** * Initialize. * * http://foxmetrics.com/documentation/apijavascript * * @param {Object} page */ FoxMetrics.prototype.initialize = function(page){ window._fxm = window._fxm || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ FoxMetrics.prototype.loaded = function(){ return !! (window._fxm && window._fxm.appId); }; /** * Page. * * @param {Page} page */ FoxMetrics.prototype.page = function(page){ var properties = page.proxy('properties'); var category = page.category(); var name = page.name(); this._category = category; // store for later push( '_fxm.pages.view', properties.title, // title name, // name category, // category properties.url, // url properties.referrer // referrer ); }; /** * Identify. * * @param {Identify} identify */ FoxMetrics.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push( '_fxm.visitor.profile', id, // user id identify.firstName(), // first name identify.lastName(), // last name identify.email(), // email identify.address(), // address undefined, // social undefined, // partners identify.traits() // attributes ); }; /** * Track. * * @param {Track} track */ FoxMetrics.prototype.track = function(track){ var props = track.properties(); var category = this._category || props.category; push(track.event(), category, props); }; /** * Viewed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.viewedProduct = function(track){ ecommerce('productview', track); }; /** * Removed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.removedProduct = function(track){ ecommerce('removecartitem', track); }; /** * Added product. * * @param {Track} track * @api private */ FoxMetrics.prototype.addedProduct = function(track){ ecommerce('cartitem', track); }; /** * Completed Order. * * @param {Track} track * @api private */ FoxMetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); // transaction push( '_fxm.ecommerce.order', orderId, track.subtotal(), track.shipping(), track.tax(), track.city(), track.state(), track.zip(), track.quantity() ); // items each(track.products(), function(product){ var track = new Track({ properties: product }); ecommerce('purchaseitem', track, [ track.quantity(), track.price(), orderId ]); }); }; /** * Track ecommerce `event` with `track` * with optional `arr` to append. * * @param {String} event * @param {Track} track * @param {Array} arr * @api private */ function ecommerce(event, track, arr){ push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); } }, {"global-queue":166,"analytics.js-integration":90,"facade":139,"each":4}], 35: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Frontleaf` integration. */ var Frontleaf = module.exports = integration('Frontleaf') .global('_fl') .global('_flBaseUrl') .option('baseUrl', 'https://api.frontleaf.com') .option('token', '') .option('stream', '') .option('trackNamedPages', false) .option('trackCategorizedPages', false) .tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">'); /** * Initialize. * * http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon * * @param {Object} page */ Frontleaf.prototype.initialize = function(page){ window._fl = window._fl || []; window._flBaseUrl = window._flBaseUrl || this.options.baseUrl; this._push('setApiToken', this.options.token); this._push('setStream', this.options.stream); var loaded = bind(this, this.loaded); var ready = this.ready; this.load({ baseUrl: window._flBaseUrl }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Frontleaf.prototype.loaded = function(){ return is.array(window._fl) && window._fl.ready === true; }; /** * Identify. * * @param {Identify} identify */ Frontleaf.prototype.identify = function(identify){ var userId = identify.userId(); if (userId) { this._push('setUser', { id: userId, name: identify.name() || identify.username(), data: clean(identify.traits()) }); } }; /** * Group. * * @param {Group} group */ Frontleaf.prototype.group = function(group){ var groupId = group.groupId(); if (groupId) { this._push('setAccount', { id: groupId, name: group.proxy('traits.name'), data: clean(group.traits()) }); } }; /** * Page. * * @param {Page} page */ Frontleaf.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * @param {Track} track */ Frontleaf.prototype.track = function(track){ var event = track.event(); this._push('event', event, clean(track.properties())); }; /** * Push a command onto the global Frontleaf queue. * * @param {String} command * @return {Object} args * @api private */ Frontleaf.prototype._push = function(command){ var args = [].slice.call(arguments, 1); window._fl.push(function(t){ t[command].apply(command, args); }); }; /** * Clean all nested objects and arrays. * * @param {Object} obj * @return {Object} * @api private */ function clean(obj){ var ret = {}; // Remove traits/properties that are already represented // outside of the data container var excludeKeys = ["id","name","firstName","lastName"]; var len = excludeKeys.length; for (var i = 0; i < len; i++) { clear(obj, excludeKeys[i]); } // Flatten nested hierarchy, preserving arrays obj = flatten(obj); // Discard nulls, represent arrays as comma-separated strings for (var key in obj) { var val = obj[key]; if (null == val) { continue; } if (is.array(val)) { ret[key] = val.toString(); continue; } ret[key] = val; } return ret; } /** * Remove a property from an object if set. * * @param {Object} obj * @param {String} key * @api private */ function clear(obj, key){ if (obj.hasOwnProperty(key)) { delete obj[key]; } } /** * Flatten a nested object into a single level space-delimited * hierarchy. * * Based on https://github.com/hughsk/flat * * @param {Object} source * @return {Object} * @api private */ function flatten(source){ var output = {}; function step(object, prev){ for (var key in object) { var value = object[key]; var newKey = prev ? prev + ' ' + key : key; if (!is.array(value) && is.object(value)) { return step(value, newKey); } output[newKey] = value; } } step(source); return output; } }, {"analytics.js-integration":90,"bind":103,"when":137,"is":93}], 36: [function(require, module, exports) { /** * Module dependencies. */ var foldl = require('foldl'); var is = require('is'); var camel = require('to-camel-case'); var integration = require('analytics.js-integration'); /** * Expose `FullStory` integration. * * https://www.fullstory.com/docs/developer */ var FullStory = module.exports = integration('FullStory') .option('org', '') .option('debug', false) .tag('<script src="https://www.fullstory.com/s/fs.js"></script>') /** * Initialize. */ FullStory.prototype.initialize = function(){ var self = this; window._fs_debug = this.options.debug; window._fs_host = 'www.fullstory.com'; window._fs_org = this.options.org; (function(m,n,e,t,l,o,g,y){ g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b);};g.q=[]; // jscs:disable g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){FS(l,v)}; // jscs:enable g.setSessionVars=function(v){FS('session',v)};g.setPageVars=function(v){FS('page',v)}; self.ready(); self.load(); })(window,document,'FS','script','user'); }; /** * Loaded? * * @return {Boolean} */ FullStory.prototype.loaded = function(){ return !! window.FS; }; /** * Identify. * * @param {Identify} identify */ FullStory.prototype.identify = function(identify){ var id = identify.userId() || identify.anonymousId(); var traits = identify.traits({ name: 'displayName' }); var newTraits = foldl(function(results, value, key){ if (key !== 'id') results[key === 'displayName' || key === 'email' ? key : convert(key, value)] = value; return results; }, {}, traits); window.FS.identify(String(id), newTraits); }; /** * Convert to FullStory format. * * @param {String} trait * @param {Property} value */ function convert (trait, value) { trait = camel(trait); if (is.string(value)) return trait += '_str'; if (isInt(value)) return trait += '_int'; if (isFloat(value)) return trait += '_real'; if (is.date(value)) return trait += '_date'; if (is.boolean(value)) return trait += '_bool'; } /** * Check if n is a float. */ function isFloat(n) { return n === +n && n !== (n|0); } /** * Check if n is an integer. */ function isInt(n) { return n === +n && n === (n|0); } }, {"foldl":173,"is":93,"to-camel-case":174,"analytics.js-integration":90}], 173: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ var each = require('each'); /** * Reduces all the values in a collection down into a single value. Does so by iterating through the * collection from left to right, repeatedly calling an `iterator` function and passing to it four * arguments: `(accumulator, value, index, collection)`. * * Returns the final return value of the `iterator` function. * * @name foldl * @api public * @param {Function} iterator The function to invoke per iteration. * @param {*} accumulator The initial accumulator value, passed to the first invocation of `iterator`. * @param {Array|Object} collection The collection to iterate over. * @return {*} The return value of the final call to `iterator`. * @example * foldl(function(total, n) { * return total + n; * }, 0, [1, 2, 3]); * //=> 6 * * var phonebook = { bob: '555-111-2345', tim: '655-222-6789', sheila: '655-333-1298' }; * * foldl(function(results, phoneNumber) { * if (phoneNumber[0] === '6') { * return results.concat(phoneNumber); * } * return results; * }, [], phonebook); * // => ['655-222-6789', '655-333-1298'] */ var foldl = function foldl(iterator, accumulator, collection) { if (typeof iterator !== 'function') { throw new TypeError('Expected a function but received a ' + typeof iterator); } each(function(val, i, collection) { accumulator = iterator(accumulator, val, i, collection); }, collection); return accumulator; }; /** * Exports. */ module.exports = foldl; }, {"each":121}], 174: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toCamelCase`. */ module.exports = toCamelCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase (string) { return toSpace(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }, {"to-space-case":126}], 37: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_gauges'); /** * Expose `Gauges` integration. */ var Gauges = module.exports = integration('Gauges') .assumesPageview() .global('_gauges') .option('siteId', '') .tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">'); /** * Initialize Gauges. * * http://get.gaug.es/documentation/tracking/ * * @param {Object} page */ Gauges.prototype.initialize = function(page){ window._gauges = window._gauges || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Gauges.prototype.loaded = function(){ return !! (window._gauges && window._gauges.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Gauges.prototype.page = function(page){ push('track'); }; }, {"analytics.js-integration":90,"global-queue":166}], 38: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var onBody = require('on-body'); /** * Expose `GetSatisfaction` integration. */ var GetSatisfaction = module.exports = integration('Get Satisfaction') .assumesPageview() .global('GSFN') .option('widgetId', '') .tag('<script src="https://loader.engage.gsfn.us/loader.js">'); /** * Initialize. * * https://console.getsatisfaction.com/start/101022?signup=true#engage * * @param {Object} page */ GetSatisfaction.prototype.initialize = function(page){ var self = this; var widget = this.options.widgetId; var div = document.createElement('div'); var id = div.id = 'getsat-widget-' + widget; onBody(function(body){ body.appendChild(div); }); // usually the snippet is sync, so wait for it before initializing the tab this.load(function(){ window.GSFN.loadWidget(widget, { containerId: id }); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ GetSatisfaction.prototype.loaded = function(){ return !! window.GSFN; }; }, {"analytics.js-integration":90,"on-body":135}], 39: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_gaq'); var length = require('object').length; var canonical = require('canonical'); var useHttps = require('use-https'); var Track = require('facade').Track; var callback = require('callback'); var defaults = require('defaults'); var load = require('load-script'); var keys = require('object').keys; var select = require('select'); var dot = require('obj-case'); var each = require('each'); var type = require('type'); var url = require('url'); var is = require('is'); var group; var user; /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(GA); group = analytics.group(); user = analytics.user(); }; /** * Expose `GA` integration. * * http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867 * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate */ var GA = exports.Integration = integration('Google Analytics') .readyOnLoad() .global('ga') .global('gaplugins') .global('_gaq') .global('GoogleAnalyticsObject') .option('anonymizeIp', false) .option('classic', false) .option('domain', 'auto') .option('doubleClick', false) .option('enhancedEcommerce', false) .option('enhancedLinkAttribution', false) .option('nonInteraction', false) .option('ignoredReferrers', null) .option('includeSearch', false) .option('siteSpeedSampleRate', 1) .option('trackingId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('sendUserId', false) .option('metrics', {}) .option('dimensions', {}) .tag('library', '<script src="//www.google-analytics.com/analytics.js">') .tag('double click', '<script src="//stats.g.doubleclick.net/dc.js">') .tag('http', '<script src="http://www.google-analytics.com/ga.js">') .tag('https', '<script src="https://ssl.google-analytics.com/ga.js">'); /** * On `construct` swap any config-based methods to the proper implementation. */ GA.on('construct', function(integration){ if (integration.options.classic) { integration.initialize = integration.initializeClassic; integration.loaded = integration.loadedClassic; integration.page = integration.pageClassic; integration.track = integration.trackClassic; integration.completedOrder = integration.completedOrderClassic; } else if (integration.options.enhancedEcommerce) { integration.viewedProduct = integration.viewedProductEnhanced; integration.clickedProduct = integration.clickedProductEnhanced; integration.addedProduct = integration.addedProductEnhanced; integration.removedProduct = integration.removedProductEnhanced; integration.startedOrder = integration.startedOrderEnhanced; integration.viewedCheckoutStep = integration.viewedCheckoutStepEnhanced; integration.completedCheckoutStep = integration.completedCheckoutStepEnhanced; integration.updatedOrder = integration.updatedOrderEnhanced; integration.completedOrder = integration.completedOrderEnhanced; integration.refundedOrder = integration.refundedOrderEnhanced; integration.viewedPromotion = integration.viewedPromotionEnhanced; integration.clickedPromotion = integration.clickedPromotionEnhanced; } }); /** * Initialize. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */ GA.prototype.initialize = function(){ var opts = this.options; // setup the tracker globals 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(); if (window.location.hostname === 'localhost') opts.domain = 'none'; window.ga('create', opts.trackingId, { cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string siteSpeedSampleRate: opts.siteSpeedSampleRate, allowLinker: true }); // display advertising if (opts.doubleClick) { window.ga('require', 'displayfeatures'); } // send global id if (opts.sendUserId && user.id()) { window.ga('set', 'userId', user.id()); } // anonymize after initializing, otherwise a warning is shown // in google analytics debugger if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true); // custom dimensions & metrics var custom = metrics(user.traits(), opts); if (length(custom)) window.ga('set', custom); this.load('library', this.ready); }; /** * Loaded? * * @return {Boolean} */ GA.prototype.loaded = function(){ return !! window.gaplugins; }; /** * Page. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications#multiple-hits * * * @param {Page} page */ GA.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var campaign = page.proxy('context.campaign') || {}; var pageview = {}; var pagePath = path(props, this.options); var pageTitle = name || props.title; var track; this._category = category; // store for later pageview.page = pagePath; pageview.title = pageTitle; pageview.location = props.url; if (campaign.name) pageview.campaignName = campaign.name; if (campaign.source) pageview.campaignSource = campaign.source; if (campaign.medium) pageview.campaignMedium = campaign.medium; if (campaign.content) pageview.campaignContent = campaign.content; if (campaign.term) pageview.campaignKeyword = campaign.term; // custom dimensions and metrics var custom = metrics(props, opts); if (length(custom)) window.ga('set', custom); // set window.ga('set', { page: pagePath, title: pageTitle }); // send window.ga('send', 'pageview', pageview); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { nonInteraction: 1 }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { nonInteraction: 1 }); } }; /** * Identify. * * @param {Identify} event */ GA.prototype.identify = function(identify){ var opts = this.options; //set userId if (opts.sendUserId && identify.userId()) { window.ga('set', 'userId', identify.userId()); } //set dimensions var custom = metrics(user.traits(), opts); if (length(custom)) window.ga('set', custom); }; /** * Track. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/events * https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference * * @param {Track} event */ GA.prototype.track = function(track, options){ var contextOpts = track.options(this.name); var interfaceOpts = this.options; var opts = defaults(options || {}, contextOpts); opts = defaults(opts, interfaceOpts); var props = track.properties(); var campaign = track.proxy('context.campaign') || {}; // custom dimensions & metrics var custom = metrics(props, interfaceOpts); if (length(custom)) window.ga('set', custom); var payload = { eventAction: track.event(), eventCategory: props.category || this._category || 'All', eventLabel: props.label, eventValue: formatValue(props.value || track.revenue()), nonInteraction: !!(props.nonInteraction || opts.nonInteraction) }; if (campaign.name) payload.campaignName = campaign.name; if (campaign.source) payload.campaignSource = campaign.source; if (campaign.medium) payload.campaignMedium = campaign.medium; if (campaign.content) payload.campaignContent = campaign.content; if (campaign.term) payload.campaignKeyword = campaign.term; window.ga('send', 'event', payload); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multicurrency * * @param {Track} track * @api private */ GA.prototype.completedOrder = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; // require ecommerce if (!this.ecommerce) { window.ga('require', 'ecommerce'); this.ecommerce = true; } // add transaction window.ga('ecommerce:addTransaction', { affiliation: props.affiliation, shipping: track.shipping(), revenue: total, tax: track.tax(), id: orderId, currency: track.currency() }); // add products each(products, function(product){ var productTrack = createProductTrack(track, product); window.ga('ecommerce:addItem', { category: productTrack.category(), quantity: productTrack.quantity(), price: productTrack.price(), name: productTrack.name(), sku: productTrack.sku(), id: orderId, currency: productTrack.currency() }); }); // send window.ga('ecommerce:send'); }; /** * Initialize (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration */ 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.ignoredReferrers; 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); }); } if (this.options.doubleClick) { this.load('double click', this.ready); } else { var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); } }; /** * Loaded? (classic) * * @return {Boolean} */ GA.prototype.loadedClassic = function(){ return !! (window._gaq && window._gaq.push !== Array.prototype.push); }; /** * Page (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration * * @param {Page} page */ 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)); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { nonInteraction: 1 }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { nonInteraction: 1 }); } }; /** * Track (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking * * @param {Track} track */ 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); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#localcurrencies * * @param {Track} track * @api private */ GA.prototype.completedOrderClassic = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products() || []; var props = track.properties(); var currency = track.currency(); // required if (!orderId) return; // add transaction push('_addTrans', orderId, props.affiliation, total, track.tax(), track.shipping(), track.city(), track.state(), track.country()); // add items each(products, function(product){ var track = new Track({ properties: product }); push('_addItem', orderId, track.sku(), track.name(), track.category(), track.price(), track.quantity()); }); // send push('_set', 'currencyCode', currency); push('_trackTrans'); }; /** * Return the path based on `properties` and `options`. * * @param {Object} properties * @param {Object} options */ function path(properties, options) { if (!properties) return; var str = properties.path; if (options.includeSearch && properties.search) str += properties.search; return str; } /** * Format the value property to Google's liking. * * @param {Number} value * @return {Number} */ function formatValue(value) { if (!value || value < 0) return 0; return Math.round(value); } /** * Map google's custom dimensions & metrics with `obj`. * * Example: * * metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } }); * // => { metric8: 1.9 } * * metrics({ revenue: 1.9 }, {}); * // => {} * * @param {Object} obj * @param {Object} data * @return {Object|null} * @api private */ function metrics(obj, data){ var dimensions = data.dimensions; var metrics = data.metrics; var names = keys(metrics).concat(keys(dimensions)); var ret = {}; for (var i = 0; i < names.length; ++i) { var name = names[i]; var key = metrics[name] || dimensions[name]; var value = dot(obj, name) || obj[name]; if (null == value) continue; ret[key] = value; } return ret; } /** * Loads ec.js (unless already loaded) */ GA.prototype.loadEnhancedEcommerce = function(track){ if (!this.enhancedEcommerceLoaded) { window.ga('require', 'ec'); this.enhancedEcommerceLoaded = true; } // Ensure we set currency for every hit window.ga('set', '&cu', track.currency()); }; /** * Pushes an event and all previously set EE data to GA. */ GA.prototype.pushEnhancedEcommerce = function(track){ // Send a custom non-interaction event to ensure all EE data is pushed. // Without doing this we'd need to require page display after setting EE data. ga('send', 'event', track.category() || 'EnhancedEcommerce', track.event(), { nonInteraction: 1 }); }; /** * Started order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps * * @param {Track} track */ GA.prototype.startedOrderEnhanced = function(track){ // same as viewed checkout step #1 this.viewedCheckoutStep(track); }; /** * Updated order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps * * @param {Track} track */ GA.prototype.updatedOrderEnhanced = function(track){ // Same event as started order - will override this.startedOrderEnhanced(track); }; /** * Viewed checkout step - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps * * @param {Track} track */ GA.prototype.viewedCheckoutStepEnhanced = function(track){ var products = track.products(); var props = track.properties(); var options = extractCheckoutOptions(props); this.loadEnhancedEcommerce(track); each(products, function(product){ var productTrack = createProductTrack(track, product); enhancedEcommerceTrackProduct(productTrack); }); window.ga('ec:setAction','checkout', { step: props.step || 1, option: options || undefined }); this.pushEnhancedEcommerce(track); }; /** * Completed checkout step - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-options * * @param {Track} track */ GA.prototype.completedCheckoutStepEnhanced = function(track){ var props = track.properties(); var options = extractCheckoutOptions(props); // Only send an event if we have step and options to update if (!props.step || !options) return; this.loadEnhancedEcommerce(track); window.ga('ec:setAction', 'checkout_option', { step: props.step || 1, option: options }); window.ga('send', 'event', 'Checkout', 'Option'); }; /** * Completed order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions * * @param {Track} track */ GA.prototype.completedOrderEnhanced = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; this.loadEnhancedEcommerce(track); each(products, function(product){ var productTrack = createProductTrack(track, product); enhancedEcommerceTrackProduct(productTrack); }); window.ga('ec:setAction', 'purchase', { id: orderId, affiliation: props.affiliation, revenue: total, tax: track.tax(), shipping: track.shipping(), coupon: track.coupon() }); this.pushEnhancedEcommerce(track); }; /** * Refunded order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-refunds * * @param {Track} track */ GA.prototype.refundedOrderEnhanced = function(track){ var orderId = track.orderId(); var products = track.products(); // orderId is required. if (!orderId) return; this.loadEnhancedEcommerce(track); // Without any products it's a full refund each(products, function(product){ var track = new Track({ properties: product }); window.ga('ec:addProduct', { id: track.id() || track.sku(), quantity: track.quantity() }); }); window.ga('ec:setAction', 'refund', { id: orderId }); this.pushEnhancedEcommerce(track); }; /** * Added product - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#add-remove-cart * * @param {Track} track */ GA.prototype.addedProductEnhanced = function(track){ this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'add'); this.pushEnhancedEcommerce(track); }; /** * Removed product - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#add-remove-cart * * @param {Track} track */ GA.prototype.removedProductEnhanced = function(track){ this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'remove'); this.pushEnhancedEcommerce(track); }; /** * Viewed product details - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-detail-view * * @param {Track} track */ GA.prototype.viewedProductEnhanced = function(track){ this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'detail'); this.pushEnhancedEcommerce(track); }; /** * Clicked product - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-actions * * @param {Track} track */ GA.prototype.clickedProductEnhanced = function(track){ var props = track.properties(); this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'click', { list: props.list }); this.pushEnhancedEcommerce(track); }; /** * Viewed promotion - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-promo-impressions * * @param {Track} track */ GA.prototype.viewedPromotionEnhanced = function(track){ var props = track.properties(); this.loadEnhancedEcommerce(track); window.ga('ec:addPromo', { id: track.id(), name: track.name(), creative: props.creative, position: props.position }); this.pushEnhancedEcommerce(track); }; /** * Clicked promotion - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-promo-clicks * * @param {Track} track */ GA.prototype.clickedPromotionEnhanced = function(track){ var props = track.properties(); this.loadEnhancedEcommerce(track); window.ga('ec:addPromo', { id: track.id(), name: track.name(), creative: props.creative, position: props.position }); ga('ec:setAction', 'promo_click', {}); this.pushEnhancedEcommerce(track); }; /** * Enhanced ecommerce track product. * * Simple helper so that we don't repeat `ec:addProduct` everywhere. * * @param {Track} track */ function enhancedEcommerceTrackProduct(track){ var props = track.properties(); window.ga('ec:addProduct', { id: track.id() || track.sku(), name: track.name(), category: track.category(), quantity: track.quantity(), price: track.price(), brand: props.brand, variant: props.variant, currency: track.currency() }); } /** * Set `action` on `track` with `data`. * * @param {Track} track * @param {String} action * @param {Object} data */ function enhancedEcommerceProductAction(track, action, data){ enhancedEcommerceTrackProduct(track); window.ga('ec:setAction', action, data || {}); } /** * Extracts checkout options. * * @param {Object} props * @return {Null|String} */ function extractCheckoutOptions(props){ var options = [ props.paymentMethod, props.shippingMethod ]; // Remove all nulls, empty strings, zeroes, and join with commas. var valid = select(options, function(e){return e; }); return valid.length > 0 ? valid.join(', ') : null; } /** * Creates a track out of product properties. * * @param {Track} track * @param {Object} properties * @return {Track} */ function createProductTrack(track, properties) { properties.currency = properties.currency || track.currency(); return new Track({ properties: properties }); } }, {"analytics.js-integration":90,"global-queue":166,"object":175,"canonical":176,"use-https":92,"facade":139,"callback":138,"defaults":164,"load-script":134,"select":177,"obj-case":94,"each":4,"type":117,"url":178,"is":93}], 175: [function(require, module, exports) { /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; }, {}], 176: [function(require, module, exports) { 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'); } }; }, {}], 177: [function(require, module, exports) { /** * Module dependencies. */ var toFunction = require('to-function'); /** * Filter the given `arr` with callback `fn(val, i)`, * when a truthy value is return then `val` is included * in the array returned. * * @param {Array} arr * @param {Function} fn * @return {Array} * @api public */ module.exports = function(arr, fn){ var ret = []; fn = toFunction(fn); for (var i = 0; i < arr.length; ++i) { if (fn(arr[i], i)) { ret.push(arr[i]); } } return ret; }; }, {"to-function":179}], 179: [function(require, module, exports) { /** * Module Dependencies */ var expr; try { expr = require('props'); } catch(e) { expr = require('component-props'); } /** * Expose `toFunction()`. */ module.exports = toFunction; /** * Convert `obj` to a `Function`. * * @param {Mixed} obj * @return {Function} * @api private */ function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } } /** * Default to strict equality. * * @param {Mixed} val * @return {Function} * @api private */ function defaultToFunction(val) { return function(obj){ return val === obj; }; } /** * Convert `re` to a function. * * @param {RegExp} re * @return {Function} * @api private */ function regexpToFunction(re) { return function(obj){ return re.test(obj); }; } /** * Convert property `str` to a function. * * @param {String} str * @return {Function} * @api private */ function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" or "age > 18 && age < 36" return new Function('_', 'return ' + get(str)); } /** * Convert `object` to a function. * * @param {Object} object * @return {Function} * @api private */ function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; } /** * Built the getter function. Supports getter style functions * * @param {String} str * @return {String} * @api private */ function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; } /** * Mimic negative lookbehind to avoid problems with nested properties. * * See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript * * @param {String} prop * @param {String} str * @param {String} val * @return {String} * @api private */ function stripNested (prop, str, val) { return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) { return $1 ? $0 : val; }); } }, {"props":120,"component-props":120}], 178: [function(require, module, exports) { /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ 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) } }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ if (0 == url.indexOf('//')) return true; if (~url.indexOf('://')) return true; return false; }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return ! exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); return url.hostname != location.hostname || url.port != location.port || url.protocol != location.protocol; }; }, {}], 40: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('dataLayer', { wrap: false }); var integration = require('analytics.js-integration'); /** * Expose `GTM`. */ var GTM = module.exports = integration('Google Tag Manager') .assumesPageview() .global('dataLayer') .global('google_tag_manager') .option('containerId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">'); /** * Initialize. * * https://developers.google.com/tag-manager * * @param {Object} page */ GTM.prototype.initialize = function(){ push({ 'gtm.start': +new Date, event: 'gtm.js' }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ GTM.prototype.loaded = function(){ return !! (window.dataLayer && [].push != window.dataLayer.push); }; /** * Page. * * @param {Page} page * @api public */ GTM.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var track; // all if (opts.trackAllPages) { this.track(page.track()); } // categorized if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * https://developers.google.com/tag-manager/devguide#events * * @param {Track} track * @api public */ GTM.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); push(props); }; }, {"global-queue":166,"analytics.js-integration":90}], 41: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var onBody = require('on-body'); var each = require('each'); var is = require('is'); var pick = require('pick'); var omit = require('omit'); /** * Expose `GoSquared` integration. */ var GoSquared = module.exports = integration('GoSquared') .assumesPageview() .global('_gs') .option('apiSecret', '') .option('anonymizeIP', false) .option('cookieDomain', null) .option('useCookies', true) .option('trackHash', false) .option('trackLocal', false) .option('trackParams', true) .tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">'); /** * Initialize. * * https://www.gosquared.com/developer/tracker * Options: https://www.gosquared.com/developer/tracker/configuration * * @param {Object} page */ GoSquared.prototype.initialize = function(page){ var self = this; var options = this.options; var user = this.analytics.user(); push(options.apiSecret); each(options, function(name, value){ if ('apiSecret' == name) return; if (null == value) return; push('set', name, value); }); self.identify(new Identify({ traits: user.traits(), userId: user.id() })); self.load(this.ready); }; /** * Loaded? (checks if the tracker version is set) * * @return {Boolean} */ GoSquared.prototype.loaded = function(){ return !! (window._gs && window._gs.v); }; /** * Page. * * https://www.gosquared.com/docs/tracking/api/#pageviews * * @param {Page} page */ GoSquared.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); push('track', props.path, name || props.title) }; /** * Identify. * * https://www.gosquared.com/docs/tracking/identify * * @param {Identify} identify */ GoSquared.prototype.identify = function(identify){ var traits = identify.traits({ createdAt: 'created_at', firstName: 'first_name', lastName: 'last_name', title: 'company_position', industry: 'company_industry' }); // https://www.gosquared.com/docs/tracking/api/#properties var specialKeys = [ 'id', 'email', 'name', 'first_name', 'last_name', 'username', 'description', 'avatar', 'phone', 'created_at', 'company_name', 'company_size', 'company_position', 'company_industry' ]; // Segment allows traits to all be in a flat object // GoSquared requires all custom properties to be in a `custom` object, // select all special keys var props = pick.apply(null, [traits].concat(specialKeys)); props.custom = omit(specialKeys, traits); var id = identify.userId(); if (id) { push('identify', id, props); } else { push('properties', props); } var email = identify.email(); var username = identify.username(); var name = email || username || id; if (name) push('set', 'visitorName', name); }; /** * Track. * * https://www.gosquared.com/docs/tracking/events * * @param {Track} track */ GoSquared.prototype.track = function(track){ push('event', track.event(), track.properties()); }; /** * Checked out. * * https://www.gosquared.com/docs/tracking/ecommerce * * @param {Track} track * @api private */ 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); }; /** * Push to `_gs.q`. * * @param {...} args * @api private */ function push(){ var _gs = window._gs = window._gs || function(){ (_gs.q = _gs.q || []).push(arguments); }; _gs.apply(null, arguments); } }, {"analytics.js-integration":90,"facade":139,"callback":138,"load-script":134,"on-body":135,"each":4,"is":93,"pick":180,"omit":181}], 180: [function(require, module, exports) { /** * Expose `pick`. */ module.exports = pick; /** * Pick keys from an `obj`. * * @param {Object} obj * @param {Strings} keys... * @return {Object} */ function pick(obj){ var keys = [].slice.call(arguments, 1); var ret = {}; for (var i = 0, key; key = keys[i]; i++) { if (key in obj) ret[key] = obj[key]; } return ret; } }, {}], 181: [function(require, module, exports) { /** * Expose `omit`. */ module.exports = omit; /** * Return a copy of the object without the specified keys. * * @param {Array} keys * @param {Object} object * @return {Object} */ function omit(keys, object){ var ret = {}; for (var item in object) { ret[item] = object[item]; } for (var i = 0; i < keys.length; i++) { delete ret[keys[i]]; } return ret; } }, {}], 42: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Heap` integration. */ var Heap = module.exports = integration('Heap') .global('heap') .option('appId', '') .tag('<script src="//cdn.heapanalytics.com/js/heap-{{ appId }}.js">'); /** * Initialize. * * https://heapanalytics.com/docs/installation#web * * @param {Object} page */ Heap.prototype.initialize = function(page){ window.heap = window.heap || []; window.heap.load = function(appid, config){ window.heap.appid = appid; window.heap.config = config; var methodFactory = function(type){ return function(){ heap.push([type].concat(Array.prototype.slice.call(arguments, 0))); }; }; var methods = ['clearEventProperties', 'identify', 'setEventProperties', 'track', 'unsetEventProperty']; for (var i = 0; i < methods.length; i++) { heap[methods[i]] = methodFactory(methods[i]); } }; window.heap.load(this.options.appId); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Heap.prototype.loaded = function(){ return (window.heap && window.heap.appid); }; /** * Identify. * * https://heapanalytics.com/docs#identify * * @param {Identify} identify */ Heap.prototype.identify = function(identify){ var traits = identify.traits({ email: '_email' }); var id = identify.userId(); if (id) traits.handle = id; window.heap.identify(traits); }; /** * Track. * * https://heapanalytics.com/docs#track * * @param {Track} track */ Heap.prototype.track = function(track){ window.heap.track(track.event(), track.properties()); }; }, {"analytics.js-integration":90,"alias":169}], 43: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `hellobar.com` integration. */ var Hellobar = module.exports = integration('Hello Bar') .assumesPageview() .global('_hbq') .option('apiKey', '') .tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">'); /** * Initialize. * * https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js * * @param {Object} page */ Hellobar.prototype.initialize = function(page){ window._hbq = window._hbq || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Hellobar.prototype.loaded = function(){ return !! (window._hbq && window._hbq.push !== Array.prototype.push); }; }, {"analytics.js-integration":90}], 44: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `HitTail` integration. */ var HitTail = module.exports = integration('HitTail') .assumesPageview() .global('htk') .option('siteId', '') .tag('<script src="//{{ siteId }}.hittail.com/mlt.js">'); /** * Initialize. * * @param {Object} page */ HitTail.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ HitTail.prototype.loaded = function(){ return is.fn(window.htk); }; }, {"analytics.js-integration":90,"is":93}], 45: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_hsq'); var convert = require('convert-dates'); /** * Expose `HubSpot` integration. */ var HubSpot = module.exports = integration('HubSpot') .assumesPageview() .global('_hsq') .option('portalId', null) .tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">'); /** * Initialize. * * @param {Object} page */ HubSpot.prototype.initialize = function(page){ window._hsq = []; var cache = Math.ceil(new Date() / 300000) * 300000; this.load({ cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ HubSpot.prototype.loaded = function(){ return !! (window._hsq && window._hsq.push !== Array.prototype.push); }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ HubSpot.prototype.page = function(page){ push('trackPageView'); }; /** * Identify. * * @param {Identify} identify */ HubSpot.prototype.identify = function(identify){ if (!identify.email()) return; var traits = identify.traits(); traits = convertDates(traits); push('identify', traits); }; /** * Track. * * @param {Track} track */ HubSpot.prototype.track = function(track){ var props = track.properties(); props = convertDates(props); push('trackEvent', track.event(), props); }; /** * Convert all the dates in the HubSpot properties to millisecond times * * @param {Object} properties */ function convertDates(properties){ return convert(properties, function(date){ return date.getTime(); }); } }, {"analytics.js-integration":90,"global-queue":166,"convert-dates":170}], 46: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Improvely` integration. */ var Improvely = module.exports = integration('Improvely') .assumesPageview() .global('_improvely') .global('improvely') .option('domain', '') .option('projectId', null) .tag('<script src="//{{ domain }}.iljmp.com/improvely.js">'); /** * Initialize. * * http://www.improvely.com/docs/landing-page-code * * @param {Object} page */ 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(this.ready); }; /** * Loaded? * * @return {Boolean} */ Improvely.prototype.loaded = function(){ return !! (window.improvely && window.improvely.identify); }; /** * Identify. * * http://www.improvely.com/docs/labeling-visitors * * @param {Identify} identify */ Improvely.prototype.identify = function(identify){ var id = identify.userId(); if (id) window.improvely.label(id); }; /** * Track. * * http://www.improvely.com/docs/conversion-code * * @param {Track} track */ Improvely.prototype.track = function(track){ var props = track.properties({ revenue: 'amount' }); props.type = track.event(); window.improvely.goal(props); }; }, {"analytics.js-integration":90,"alias":169}], 47: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_iva'); var Track = require('facade').Track; var each = require('each'); var is = require('is'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `InsideVault` integration. */ var InsideVault = module.exports = integration('InsideVault') .global('_iva') .option('clientId', '') .option('domain', '') .tag('<script src="//analytics.staticiv.com/iva.js">') .mapping('events'); /** * Initialize. * * @param page */ InsideVault.prototype.initialize = function(page){ var domain = this.options.domain; window._iva = window._iva || []; push('setClientId', this.options.clientId); var userId = this.analytics.user().anonymousId(); if (userId) push('setUserId', userId); if (domain) push('setDomain', domain); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ InsideVault.prototype.loaded = function(){ return !! (window._iva && window._iva.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ InsideVault.prototype.identify = function(identify){ push('setUserId', identify.anonymousId()); }; /** * Page. * * @param {Page} page */ InsideVault.prototype.page = function(page){ // they want every landing page to send a "click" event. push('trackEvent', 'click'); }; /** * Track. * * Tracks everything except 'sale' events. * * @param {Track} track */ InsideVault.prototype.track = function(track){ var user = this.analytics.user(); var events = this.events(track.event()); var value = track.revenue() || track.value() || 0; var eventId = track.orderId() || user.anonymousId() || ''; each(events, function(event){ // 'sale' is a special event that will be routed to a table that is deprecated on InsideVault's end. // They don't want a generic 'sale' event to go to their deprecated table. if (event != 'sale') { push('trackEvent', event, value, eventId); } }); }; }, {"analytics.js-integration":90,"global-queue":166,"facade":139,"each":4,"is":93}], 48: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('__insp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Inspectlet` integration. */ var Inspectlet = module.exports = integration('Inspectlet') .assumesPageview() .global('__insp') .global('__insp_') .option('wid', '') .tag('<script src="//cdn.inspectlet.com/inspectlet.js">'); /** * Initialize. * * https://www.inspectlet.com/dashboard/embedcode/1492461759/initial * * @param {Object} page */ Inspectlet.prototype.initialize = function(page){ push('wid', this.options.wid); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Inspectlet.prototype.loaded = function(){ return !! (window.__insp_ && window.__insp); }; /** * Identify. * * http://www.inspectlet.com/docs#tagging * * @param {Identify} identify */ Inspectlet.prototype.identify = function(identify){ var traits = identify.traits({ id: 'userid' }); var email = identify.email(); if (email) push('identify', email); push('tagSession', traits); }; /** * Track. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.track = function(track){ push('tagSession', track.event()); }; /** * Page. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.page = function(){ push('virtualPage'); }; }, {"analytics.js-integration":90,"global-queue":166,"alias":169,"clone":96}], 49: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var convertDates = require('convert-dates'); var defaults = require('defaults'); var del = require('obj-case').del; var isEmail = require('is-email'); var load = require('load-script'); var empty = require('is-empty'); var alias = require('alias'); var each = require('each'); var is = require('is'); /** * Expose `Intercom` integration. */ var Intercom = module.exports = integration('Intercom') .global('Intercom') .option('activator', '#IntercomDefaultWidget') .option('appId', '') .tag('<script src="https://widget.intercom.io/widget/{{ appId }}">'); /** * Initialize. * * http://docs.intercom.io/ * http://docs.intercom.io/#IntercomJS * * @param {Object} page */ Intercom.prototype.initialize = function(page){ initialize(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Intercom.prototype.loaded = function(){ return is.fn(window.Intercom); }; /** * Page. * * @param {Page} page */ Intercom.prototype.page = function(){ this.bootOrUpdate(); }; /** * Identify. * * http://docs.intercom.io/#IntercomJS * * @param {Identify} identify */ 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(); var group = this.analytics.group(); if (!id && !traits.email) { return; } // intercom requires `company` to be an object. default it with group traits // so that we guarantee an `id` is there, since they require it if (traits.company !== null && !is.object(traits.company)) { delete traits.company; } if (traits.company) { defaults(traits.company, group.traits()); } // name if (name) traits.name = name; // handle dates if (created) { del(traits, 'created'); del(traits, 'createdAt'); traits.created_at = created; } if (companyCreated) { del(traits.company, 'created'); del(traits.company, 'createdAt'); traits.company.created_at = companyCreated; } // convert dates traits = convertDates(traits, formatDate); // handle options 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; this.bootOrUpdate(traits); }; /** * Group. * * @param {Group} group */ Intercom.prototype.group = function(group){ var props = group.properties(); props = alias(props, { createdAt: 'created' }); props = alias(props, { created: 'created_at' }); var id = group.groupId(); if (id) props.id = id; api('update', { company: props }); }; /** * Track. * * @param {Track} track */ Intercom.prototype.track = function(track){ api('trackEvent', track.event(), track.properties()); }; /** * Boots or updates, as appropriate. * * @param {Object} options */ Intercom.prototype.bootOrUpdate = function(options){ options = options || {}; var method = this.booted === true ? 'update' : 'boot'; var activator = this.options.activator; options.app_id = this.options.appId; // Intercom, will force the widget to appear // if the selector is #IntercomDefaultWidget // so no need to check inbox, just need to check // that the selector isn't #IntercomDefaultWidget. if (activator !== '#IntercomDefaultWidget') { options.widget = { activator: activator }; } api(method, options); this.booted = true; }; /** * Format a date to Intercom's liking. * * @param {Date} date * @return {Number} */ function formatDate(date){ return Math.floor(date / 1000); } /** * Initialize the Intercom call queue. */ function initialize(){ window.Intercom = function(){ window.Intercom.q.push(arguments); }; window.Intercom.q = []; } /** * Push a call onto the queue. */ function api(){ window.Intercom.apply(window.Intercom, arguments); } }, {"analytics.js-integration":90,"convert-dates":170,"defaults":164,"obj-case":94,"is-email":161,"load-script":134,"is-empty":128,"alias":169,"each":4,"is":93}], 50: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var clone = require('clone'); /** * Expose `Keen IO` integration. */ var Keen = module.exports = integration('Keen IO') .global('Keen') .option('projectId', '') .option('readKey', '') .option('writeKey', '') .option('ipAddon', false) .option('uaAddon', false) .option('urlAddon', false) .option('referrerAddon', false) .option('trackNamedPages', true) .option('trackAllPages', false) .option('trackCategorizedPages', true) .tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">'); /** * Initialize. * * https://keen.io/docs/ */ Keen.prototype.initialize = function(){ var options = this.options; !(function(a,b){ if (void 0===b[a]){ b["_"+a]={}, b[a]=function(c){ b["_"+a].clients=b["_"+a].clients||{}, b["_"+a].clients[c.projectId]=this, this._config=c }, b[a].ready=function(c){ b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c) }; for (var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){ var e=c[d], f=function(a){ return function(){ return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this } }; b[a].prototype[e]=f(e) } } })("Keen",window); this.client = new window.Keen({ projectId: options.projectId, writeKey: options.writeKey, readKey: options.readKey }); // if you have a read-key, then load the full keen library var lib = this.options.readKey ? 'keen' : 'keen-tracker'; this.load({ lib: lib }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Keen.prototype.loaded = function(){ return !!(window.Keen && window.Keen.prototype.configure); }; /** * Page. * * @param {Page} page */ Keen.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * TODO: migrate from old `userId` to simpler `id` * https://keen.io/docs/data-collection/data-enrichment/#add-ons * * Set up the Keen addons object. These must be specifically * enabled by the settings in order to include the plugins, or else * Keen will reject the request. * * @param {Identify} identify */ 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; var props = { user: user }; this.addons(props, identify); this.client.setGlobalProperties(function(){ return clone(props); }); }; /** * Track. * * @param {Track} track */ Keen.prototype.track = function(track){ var props = track.properties(); this.addons(props, track); this.client.addEvent(track.event(), props); }; /** * Attach addons to `obj` with `msg`. * * @param {Object} obj * @param {Facade} msg */ Keen.prototype.addons = function(obj, msg){ var options = this.options; var addons = []; if (options.ipAddon) { addons.push({ name: 'keen:ip_to_geo', input: { ip: 'ip_address' }, output: 'ip_geo_info' }); obj.ip_address = '${keen.ip}'; } if (options.uaAddon) { addons.push({ name: 'keen:ua_parser', input: { ua_string: 'user_agent' }, output: 'parsed_user_agent' }); obj.user_agent = '${keen.user_agent}'; } if (options.urlAddon) { addons.push({ name: 'keen:url_parser', input: { url: 'page_url' }, output: 'parsed_page_url' }); obj.page_url = document.location.href; } if (options.referrerAddon) { addons.push({ name: 'keen:referrer_parser', input: { referrer_url: 'referrer_url', page_url: 'page_url' }, output: 'referrer_info' }); obj.referrer_url = document.referrer; obj.page_url = document.location.href; } obj.keen = { timestamp: msg.timestamp(), addons: addons }; }; }, {"analytics.js-integration":90,"clone":96}], 51: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var indexof = require('indexof'); var is = require('is'); /** * Expose `Kenshoo` integration. */ var Kenshoo = module.exports = integration('Kenshoo') .global('k_trackevent') .option('cid', '') .option('subdomain', '') .option('events', []) .tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">'); /** * Initialize. * * See https://gist.github.com/justinboyle/7875832 * * @param {Object} page */ Kenshoo.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? (checks if the tracking function is set) * * @return {Boolean} */ Kenshoo.prototype.loaded = function(){ return is.fn(window.k_trackevent); }; /** * Track. * * Only tracks events if they are listed in the events array option. * We've asked for docs a few times but no go :/ * * https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb * * @param {Track} event */ Kenshoo.prototype.track = function(track){ var events = this.options.events; var traits = track.traits(); var event = track.event(); var revenue = track.revenue() || 0; if (!~indexof(events, event)) return; var params = [ 'id=' + this.options.cid, 'type=conv', 'val=' + revenue, 'orderId=' + track.orderId(), 'promoCode=' + track.coupon(), 'valueCurrency=' + track.currency(), // Live tracking fields. Ignored for now (until we get documentation). 'GCID=', 'kw=', 'product=' ]; window.k_trackevent(params, this.options.subdomain); }; }, {"analytics.js-integration":90,"indexof":118,"is":93}], 52: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_kmq'); var Track = require('facade').Track; var alias = require('alias'); var each = require('each'); var is = require('is'); /** * Expose `KISSmetrics` integration. */ var KISSmetrics = module.exports = integration('KISSmetrics') .assumesPageview() .global('_kmq') .global('KM') .global('_kmil') .option('apiKey', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('prefixProperties', true) .tag('library', '<script src="//scripts.kissmetrics.com/{{ apiKey }}.2.js">'); /** * Check if browser is mobile, for kissmetrics. * * http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile */ exports.isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPod/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i); /** * Initialize. * * http://support.kissmetrics.com/apis/javascript * * @param {Object} page */ KISSmetrics.prototype.initialize = function(page){ var self = this; window._kmq = []; if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' }); this.load('library', function(){ self.trackPage(page); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ KISSmetrics.prototype.loaded = function(){ return is.object(window.KM); }; /** * Page. * * @param {Page} page */ KISSmetrics.prototype.page = function(page){ if (!window.KM_SKIP_PAGE_VIEW) window.KM.pageView(); this.trackPage(page); }; /** * Track page. * * @param {Page} page */ KISSmetrics.prototype.trackPage = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * @param {Identify} identify */ KISSmetrics.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {Track} track */ KISSmetrics.prototype.track = function(track){ var mapping = { revenue: 'Billing Amount' }; var event = track.event(); var properties = track.properties(mapping); if (this.options.prefixProperties) properties = prefix(event, properties); push('record', event, properties); }; /** * Alias. * * @param {Alias} to */ KISSmetrics.prototype.alias = function(alias){ push('alias', alias.to(), alias.from()); }; /** * Completed order. * * @param {Track} track * @api private */ KISSmetrics.prototype.completedOrder = function(track){ var products = track.products(); var event = track.event(); // transaction push('record', event, prefix(event, track.properties())); // items window._kmq.push(function(){ var km = window.KM; each(products, function(product, i){ var item = prefix(event, product); item._t = km.ts() + i; item._d = 1; km.set(item); }); }); }; /** * Prefix properties with the event name. * * @param {String} event * @param {Object} properties * @return {Object} prefixed * @api private */ function prefix(event, properties){ var prefixed = {}; each(properties, function(key, val){ if (key === 'Billing Amount') { prefixed[key] = val; } else { prefixed[event + ' - ' + key] = val; } }); return prefixed; } }, {"analytics.js-integration":90,"global-queue":166,"facade":139,"alias":169,"each":4,"is":93}], 53: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_learnq'); var tick = require('next-tick'); var alias = require('alias'); /** * Trait aliases. */ var aliases = { id: '$id', email: '$email', firstName: '$first_name', lastName: '$last_name', phone: '$phone_number', title: '$title' }; /** * Expose `Klaviyo` integration. */ var Klaviyo = module.exports = integration('Klaviyo') .assumesPageview() .global('_learnq') .option('apiKey', '') .tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">'); /** * Initialize. * * https://www.klaviyo.com/docs/getting-started * * @param {Object} page */ Klaviyo.prototype.initialize = function(page){ var self = this; push('account', this.options.apiKey); this.load(function(){ tick(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Klaviyo.prototype.loaded = function(){ return !! (window._learnq && window._learnq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Klaviyo.prototype.identify = function(identify){ var traits = identify.traits(aliases); if (!traits.$id && !traits.$email) return; push('identify', traits); }; /** * Group. * * @param {Group} group */ Klaviyo.prototype.group = function(group){ var props = group.properties(); if (!props.name) return; push('identify', { $organization: props.name }); }; /** * Track. * * @param {Track} track */ Klaviyo.prototype.track = function(track){ push('track', track.event(), track.properties({ revenue: '$value' })); }; }, {"analytics.js-integration":90,"global-queue":166,"next-tick":116,"alias":169}], 54: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var clone = require('clone'); var each = require('each'); var Identify = require('facade').Identify; var when = require('when'); var tick = require('next-tick'); /** * Expose `LiveChat` integration. */ var LiveChat = module.exports = integration('LiveChat') .assumesPageview() .global('__lc') .global('__lc_inited') .global('LC_API') .global('LC_Invite') .option('group', 0) .option('license', '') .option('listen', false) .tag('<script src="//cdn.livechatinc.com/tracking.js">'); /** * The context for this integration. */ var integration = { name: 'livechat', version: '1.0.0' }; /** * Initialize. * * http://www.livechatinc.com/api/javascript-api * * @param {Object} page */ LiveChat.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var identify = new Identify({ userId: user.id(), traits: user.traits() }); window.__lc = clone(this.options); window.__lc.visitor = { name: identify.name(), email: identify.email() }; // listen is not an option we need from clone delete window.__lc.listen; this.load(function(){ when(function(){ return self.loaded(); }, function(){ if (self.options.listen) self.attachListeners(); tick(self.ready); }); }); }; /** * Loaded? * * @return {Boolean} */ LiveChat.prototype.loaded = function(){ return !!(window.LC_API && window.LC_Invite); }; /** * Listen for chat events. */ LiveChat.prototype.attachListeners = function(){ var self = this; window.LC_API = window.LC_API || {}; window.LC_API.on_chat_started = function(data){ self.analytics.track( 'Live Chat Conversation Started', { agentName: data.agent_name }, { context: { integration: integration } }); }; window.LC_API.on_message = function(data){ if (data.user_type === 'visitor') { self.analytics.track( 'Live Chat Message Sent', {}, { context: { integration: integration } }); } else { self.analytics.track( 'Live Chat Message Received', { agentName: data.agent_name, agentUsername: data.agent_login }, { context: { integration: integration } }); } }; window.LC_API.on_chat_ended = function(){ self.analytics.track('Live Chat Conversation Ended'); }; }; /** * Identify. * * @param {Identify} identify */ LiveChat.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'User ID' }); window.LC_API.set_custom_variables(convert(traits)); }; /** * Convert a traits object into the format LiveChat requires. * * @param {Object} traits * @return {Array} */ function convert(traits){ var arr = []; each(traits, function(key, value){ arr.push({ name: key, value: value }); }); return arr; } }, {"analytics.js-integration":90,"clone":96,"each":4,"facade":139,"when":137,"next-tick":116}], 55: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var useHttps = require('use-https'); /** * Expose `LuckyOrange` integration. */ var LuckyOrange = module.exports = integration('Lucky Orange') .assumesPageview() .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) .tag('http', '<script src="http://www.luckyorange.com/w.js?{{ cache }}">') .tag('https', '<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ LuckyOrange.prototype.initialize = function(page){ var user = this.analytics.user(); window._loq || (window._loq = []); window.__wtw_lucky_site_id = this.options.siteId; this.identify(new Identify({ traits: user.traits(), userId: user.id() })); var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ LuckyOrange.prototype.loaded = function(){ return !! window.__wtw_watcher_added; }; /** * Identify. * * @param {Identify} identify */ LuckyOrange.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var name = identify.name(); if (name) traits.name = name; if (email) traits.email = email; window.__wtw_custom_user_data = traits; }; }, {"analytics.js-integration":90,"facade":139,"use-https":92}], 56: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Lytics` integration. */ var Lytics = module.exports = integration('Lytics') .global('jstag') .option('cid', '') .option('cookie', 'seerid') .option('delay', 2000) .option('sessionTimeout', 1800) .option('url', '//c.lytics.io') .tag('<script src="//c.lytics.io/static/io.min.js">'); /** * Options aliases. */ var aliases = { sessionTimeout: 'sessecs' }; /** * Initialize. * * http://admin.lytics.io/doc#jstag * * @param {Object} page */ 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(this.ready); }; /** * Loaded? * * @return {Boolean} */ Lytics.prototype.loaded = function(){ return !! (window.jstag && window.jstag.bind); }; /** * Page. * * @param {Page} page */ Lytics.prototype.page = function(page){ window.jstag.send(page.properties()); }; /** * Idenfity. * * @param {Identify} identify */ Lytics.prototype.identify = function(identify){ var traits = identify.traits({ userId: '_uid' }); window.jstag.send(traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Lytics.prototype.track = function(track){ var props = track.properties(); props._e = track.event(); window.jstag.send(props); }; }, {"analytics.js-integration":90,"alias":169}], 57: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var clone = require('clone'); var dates = require('convert-dates'); var integration = require('analytics.js-integration'); var is = require('is'); var iso = require('to-iso-string'); var indexof = require('indexof'); var del = require('obj-case').del; var some = require('some'); /** * Expose `Mixpanel` integration. */ var Mixpanel = module.exports = integration('Mixpanel') .global('mixpanel') .option('increments', []) .option('cookieName', '') .option('crossSubdomainCookie', false) .option('secureCookie', false) .option('nameTag', true) .option('pageview', false) .option('people', false) .option('token', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js">'); /** * Options aliases. */ var optionsAliases = { cookieName: 'cookie_name', crossSubdomainCookie: 'cross_subdomain_cookie', secureCookie: 'secure_cookie' }; /** * Initialize. * * https://mixpanel.com/help/reference/javascript#installing * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init */ 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 || []); this.options.increments = lowercase(this.options.increments); var options = alias(this.options, optionsAliases); window.mixpanel.init(options.token, options); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mixpanel.prototype.loaded = function(){ return !! (window.mixpanel && window.mixpanel.config); }; /** * Page. * * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ Mixpanel.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Trait aliases. */ var traitAliases = { created: '$created', email: '$email', firstName: '$first_name', lastName: '$last_name', lastSeen: '$last_seen', name: '$name', username: '$username', phone: '$phone' }; /** * Identify. * * https://mixpanel.com/help/reference/javascript#super-properties * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript#storing-user-profiles * * @param {Identify} identify */ Mixpanel.prototype.identify = function(identify){ var username = identify.username(); var email = identify.email(); var id = identify.userId(); // id if (id) window.mixpanel.identify(id); // name tag var nametag = email || username || id; if (nametag) window.mixpanel.name_tag(nametag); // traits var traits = identify.traits(traitAliases); if (traits.$created) del(traits, 'createdAt'); window.mixpanel.register(dates(traits, iso)); if (this.options.people) window.mixpanel.people.set(traits); }; /** * Track. * * https://mixpanel.com/help/reference/javascript#sending-events * https://mixpanel.com/help/reference/javascript#tracking-revenue * * @param {Track} track */ Mixpanel.prototype.track = function(track){ var increments = this.options.increments; var increment = track.event().toLowerCase(); var people = this.options.people; var props = track.properties(); var revenue = track.revenue(); // delete mixpanel's reserved properties, so they don't conflict delete props.distinct_id; delete props.ip; delete props.mp_name_tag; delete props.mp_note; delete props.token; // convert arrays of objects to length, since mixpanel doesn't support object arrays for (var key in props) { var val = props[key]; if (is.array(val) && some(val, is.object)) props[key] = val.length; } // increment properties in mixpanel people if (people && ~indexof(increments, increment)) { window.mixpanel.people.increment(track.event()); window.mixpanel.people.set('Last ' + track.event(), new Date); } // track the event props = dates(props, iso); window.mixpanel.track(track.event(), props); // track revenue specifically if (revenue && people) { window.mixpanel.people.track_charge(revenue); } }; /** * Alias. * * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias * * @param {Alias} alias */ Mixpanel.prototype.alias = function(alias){ var mp = window.mixpanel; var to = alias.to(); if (mp.get_distinct_id && mp.get_distinct_id() === to) return; // HACK: internal mixpanel API to ensure we don't overwrite if (mp.get_property && mp.get_property('$people_distinct_id') === to) return; // although undocumented, mixpanel takes an optional original id mp.alias(to, alias.from()); }; /** * Lowercase the given `arr`. * * @param {Array} arr * @return {Array} * @api private */ function lowercase(arr){ var ret = new Array(arr.length); for (var i = 0; i < arr.length; ++i) { ret[i] = String(arr[i]).toLowerCase(); } return ret; } }, {"alias":169,"clone":96,"convert-dates":170,"analytics.js-integration":90,"is":93,"to-iso-string":168,"indexof":118,"obj-case":94,"some":182}], 182: [function(require, module, exports) { /** * some */ var some = [].some; /** * test whether some elements in * the array pass the test implemented * by `fn`. * * example: * * some([1, 'foo', 'bar'], function (el, i) { * return 'string' == typeof el; * }); * // > true * * @param {Array} arr * @param {Function} fn * @return {bool} */ module.exports = function (arr, fn) { if (some) return some.call(arr, fn); for (var i = 0, l = arr.length; i < l; ++i) { if (fn(arr[i], i)) return true; } return false; }; }, {}], 58: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Mojn` */ var Mojn = module.exports = integration('Mojn') .option('customerCode', '') .global('_mojnTrack') .tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">'); /** * Initialize. * * @param {Object} page */ Mojn.prototype.initialize = function(){ window._mojnTrack = window._mojnTrack || []; window._mojnTrack.push({ cid: this.options.customerCode }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Mojn.prototype.loaded = function(){ return is.object(window._mojnTrack); }; /** * Identify. * * @param {Identify} identify */ Mojn.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; var img = new Image(); img.src = '//matcher.idtargeting.com/identify.gif?cid=' + this.options.customerCode + '&_mjnctid='+email; img.width = 1; img.height = 1; return img; }; /** * Track. * * @param {Track} event */ 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._mojnTrack.push({ conv: conv }); return conv; }; }, {"analytics.js-integration":90,"bind":103,"when":137,"is":93}], 59: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_mfq'); var integration = require('analytics.js-integration'); var each = require('each'); /** * Expose `Mouseflow`. */ var Mouseflow = module.exports = integration('Mouseflow') .assumesPageview() .global('mouseflow') .global('_mfq') .option('apiKey', '') .option('mouseflowHtmlDelay', 0) .tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">'); /** * Initalize. * * @param {Object} page */ Mouseflow.prototype.initialize = function(page){ window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mouseflow.prototype.loaded = function(){ return !! window.mouseflow; }; /** * Page. * * http://mouseflow.zendesk.com/entries/22528817-Single-page-websites * * @param {Page} page */ Mouseflow.prototype.page = function(page){ if (!window.mouseflow) return; if ('function' != typeof mouseflow.newPageView) return; mouseflow.newPageView(); }; /** * Identify. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Identify} identify */ Mouseflow.prototype.identify = function(identify){ set(identify.traits()); }; /** * Track. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Track} track */ Mouseflow.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); set(props); }; /** * Push each key and value in the given `obj` onto the queue. * * @param {Object} obj */ function set(obj){ each(obj, function(key, value){ push('setVariable', key, value); }); } }, {"global-queue":166,"analytics.js-integration":90,"each":4}], 60: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); /** * Expose `MouseStats` integration. */ var MouseStats = module.exports = integration('MouseStats') .assumesPageview() .global('msaa') .global('MouseStatsVisitorPlaybacks') .option('accountNumber', '') .tag('http', '<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">') .tag('https', '<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * http://www.mousestats.com/docs/pages/allpages * * @param {Object} page */ MouseStats.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number; var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ MouseStats.prototype.loaded = function(){ return is.array(window.MouseStatsVisitorPlaybacks); }; /** * Identify. * * http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks * * @param {Identify} identify */ MouseStats.prototype.identify = function(identify){ each(identify.traits(), function(key, value){ window.MouseStatsVisitorPlaybacks.customVariable(key, value); }); }; }, {"analytics.js-integration":90,"use-https":92,"each":4,"is":93}], 61: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('__nls'); /** * Expose `Navilytics` integration. */ var Navilytics = module.exports = integration('Navilytics') .assumesPageview() .global('__nls') .option('memberId', '') .option('projectId', '') .tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">'); /** * Initialize. * * https://www.navilytics.com/member/code_settings * * @param {Object} page */ Navilytics.prototype.initialize = function(page){ window.__nls = window.__nls || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Navilytics.prototype.loaded = function(){ return !! (window.__nls && [].push != window.__nls.push); }; /** * Track. * * https://www.navilytics.com/docs#tags * * @param {Track} track */ Navilytics.prototype.track = function(track){ push('tagRecording', track.event()); }; }, {"analytics.js-integration":90,"global-queue":166}], 62: [function(require, module, exports) { var integration = require('analytics.js-integration'); var alias = require('alias'); var Identify = require('facade').Identify; /** * Expose `plugin`. */ /*module.exports = exports = function(analytics){ analytics.addIntegration(Nudgespot); };*/ /** * Expose `Nudgespot` integration. */ var Nudgespot = module.exports = integration('Nudgespot') .assumesPageview() .option('clientApiKey', '') .global('nudgespot') .tag('<script id="nudgespot" src="//cdn.nudgespot.com/nudgespot.js">'); /** * Initialize Nudgespot. */ Nudgespot.prototype.initialize = function(page){ window.nudgespot = window.nudgespot || []; window.nudgespot.init = function(n, t){function f(n,m){var a=m.split('.');2==a.length&&(n=n[a[0]],m=a[1]);n[m]=function(){n.push([m].concat(Array.prototype.slice.call(arguments,0)))}}n._version=0.1;n._globals=[t];n.people=n.people||[];n.params=n.params||[];m="track register unregister identify set_config people.delete people.create people.update people.create_property people.tag people.remove_Tag".split(" ");for (var i=0;i<m.length;i++)f(n,m[i])}; window.nudgespot.init(window.nudgespot, this.options.clientApiKey); this.load(this.ready); }; /** * Has the Nudgespot library been loaded yet? */ Nudgespot.prototype.loaded = function(){ return (!! window.nudgespot) && (window.nudgespot.push !== Array.prototype.push); }; /** * Identify a user. */ Nudgespot.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ createdAt: 'created' }); traits = alias(traits, { created: 'created_at' }); window.nudgespot.identify(identify.userId(), traits); }; /** * Track an event. */ Nudgespot.prototype.track = function(track){ var properties = track.properties(); window.nudgespot.track(track.event(), properties); }; }, {"analytics.js-integration":90,"alias":169,"facade":139}], 63: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var https = require('use-https'); var tick = require('next-tick'); /** * Expose `Olark` integration. */ var Olark = module.exports = integration('Olark') .assumesPageview() .global('olark') .option('identify', true) .option('page', true) .option('siteId', '') .option('groupId', '') .option('listen', false) .option('track', false); /** * The context for this integration. */ var integration = { name: 'olark', version: '1.0.0' }; /** * Initialize. * * http://www.olark.com/documentation * https://www.olark.com/documentation/javascript/api.chat.setOperatorGroup * * @param {Facade} page */ Olark.prototype.initialize = function(page){ var self = this; this.load(function(){ tick(self.ready); }); // assign chat to a specific site var groupId = this.options.groupId; if (groupId) api('chat.setOperatorGroup', { group: groupId }); // keep track of the widget's open state api('box.onExpand', function(){ self._open = true; }); api('box.onShrink', function(){ self._open = false; }); // record events if (this.options.listen) this.attachListeners(); }; /** * Loaded? * * @return {Boolean} */ Olark.prototype.loaded = function(){ return !! window.olark; }; /** * Listen for events. */ Olark.prototype.attachListeners = function(){ var self = this; api('chat.onBeginConversation', function(){ self.analytics.track( 'Live Chat Conversation Started', {}, { context: { integration: integration }} ); }); api('chat.onMessageToOperator', function(event){ self.analytics.track( 'Live Chat Message Sent', {}, { context: { integration: integration }} ); }); api('chat.onMessageToVisitor', function(event){ self.analytics.track( 'Live Chat Message Received', {}, { context: { integration: integration }} ); }); }; /** * Load. * * @param {Function} callback */ Olark.prototype.load = function(callback){ var el = document.getElementById('olark'); 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); callback(); }; /** * Page. * * @param {Facade} page */ Olark.prototype.page = function(page){ if (!this.options.page) return; var props = page.properties(); var name = page.fullName(); if (!name && !props.url) return; name = name ? name + ' page' : props.url; this.notify('looking at ' + name); }; /** * Identify. * * @param {Facade} identify */ 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(); if (traits) api('visitor.updateCustomFields', traits); if (email) api('visitor.updateEmailAddress', { emailAddress: email }); if (phone) api('visitor.updatePhoneNumber', { phoneNumber: phone }); if (name) api('visitor.updateFullName', { fullName: name }); // figure out best nickname var nickname = name || email || username || id; if (name && email) nickname += ' (' + email + ')'; if (nickname) api('chat.updateVisitorNickname', { snippet: nickname }); }; /** * Track. * * @param {Facade} track */ Olark.prototype.track = function(track){ if (!this.options.track) return; this.notify('visitor triggered "' + track.event() + '"'); }; /** * Send a notification `message` to the operator, only when a chat is active and * when the chat is open. * * @param {String} message */ Olark.prototype.notify = function(message){ if (!this._open) return; // lowercase since olark does message = message.toLowerCase(); api('visitor.getDetails', function(data){ if (!data || !data.isConversing) return; api('chat.sendNotificationToOperator', { body: message }); }); }; /** * Helper for Olark API calls. * * @param {String} action * @param {Object} value */ function api(action, value) { window.olark('api.' + action, value); } }, {"analytics.js-integration":90,"use-https":92,"next-tick":116}], 64: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('optimizely'); var callback = require('callback'); var tick = require('next-tick'); var bind = require('bind'); var each = require('each'); var isEmpty = require('is-empty'); var foldl = require('foldl'); /** * Expose `Optimizely` integration. */ var Optimizely = module.exports = integration('Optimizely') .option('variations', true) .option('listen', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * The name and version for this integration. */ var integration = { name: 'optimizely', version: '1.0.0' }; /** * Initialize. * * https://www.optimizely.com/docs/api#function-calls */ Optimizely.prototype.initialize = function(){ var self = this; if (this.options.variations) { tick(function(){ self.replay(); }); } if (this.options.listen) { tick(function(){ self.roots(); }); } this.ready(); }; /** * Track. * * https://www.optimizely.com/docs/api#track-event * * @param {Track} track */ Optimizely.prototype.track = function(track){ var props = track.properties(); if (props.revenue) props.revenue *= 100; push('trackEvent', track.event(), props); }; /** * Page. * * https://www.optimizely.com/docs/api#track-event * * @param {Page} page */ Optimizely.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Send experiment data as track events to Segment * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.roots = function(){ if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data) return; var allExperiments = data.experiments; if (!data || !data.state || !allExperiments) return; var variationNamesMap = data.state.variationNamesMap; var variationIdsMap = data.state.variationIdsMap; var activeExperimentIds = data.state.activeExperiments; var activeExperiments = getExperiments(activeExperimentIds, variationNamesMap, variationIdsMap, allExperiments); var self = this; each(activeExperiments, function(props){ self.analytics.track( 'Experiment Viewed', props, { context: { integration: integration } } ); }); }; /** * Retrieves active experiments * * @param {Object} state * @param {Object} allExperiments */ function getExperiments(activeExperimentIds, variationNamesMap, variationIdsMap, allExperiments) { return foldl(function(results, experimentId){ var experiment = allExperiments[experimentId]; if (experiment) { results.push({ variationName: variationNamesMap[experimentId], variationId: variationIdsMap[experimentId], experimentId: experimentId, experimentName: experiment.name }); } return results; }, [], activeExperimentIds); }; /** * Replay experiment data as traits to other enabled providers. * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.replay = function(){ if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data || !data.experiments || !data.state) 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; }); this.analytics.identify(traits); }; }, {"analytics.js-integration":90,"global-queue":166,"callback":138,"next-tick":116,"bind":103,"each":4,"is-empty":128,"foldl":173}], 65: [function(require, module, exports) { var integration = require('analytics.js-integration'); var omit = require('omit'); var Outbound = module.exports = integration('Outbound') .global('outbound') .option('publicApiKey', '') .tag('<script src="//cdn.outbound.io/{{ publicApiKey }}.js">'); Outbound.prototype.initialize = function(page){ window.outbound = window.outbound || []; window.outbound.methods = ['identify', 'track', 'registerApnsToken', 'registerGcmToken', 'disableApnsToken', 'disableGcmToken']; window.outbound.factory = function(method){ return function(){ var args = Array.prototype.slice.call(arguments); args.unshift(method); window.outbound.push(args); return window.outbound; }; }; for (var i = 0; i < window.outbound.methods.length; i++) { var key = window.outbound.methods[i]; window.outbound[key] = window.outbound.factory(key); } this.load(this.ready); }; Outbound.prototype.loaded = function(){ return window.outbound; }; Outbound.prototype.identify = function(identify){ var traitsToOmit = [ 'id', 'userId', 'email', 'phone', 'firstName', 'lastName' ]; var userId = identify.userId() || identify.anonymousId(); var attributes = { attributes: omit(traitsToOmit, identify.traits()), email: identify.email(), phoneNumber: identify.phone(), firstName: identify.firstName(), lastName: identify.lastName() }; outbound.identify(userId, attributes); }; Outbound.prototype.track = function(track){ window.outbound.track(track.event(), track.properties(), track.timestamp()); }; Outbound.prototype.alias = function(alias){ window.outbound.identify(alias.userId(), { previousId: alias.previousId() }); }; }, {"analytics.js-integration":90,"omit":181}], 66: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_pq'); /** * Expose `PerfectAudience` integration. */ var PerfectAudience = module.exports = integration('Perfect Audience') .assumesPageview() .global('_pq') .option('siteId', '') .tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">'); /** * Initialize. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Object} page */ PerfectAudience.prototype.initialize = function(page){ window._pq = window._pq || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ PerfectAudience.prototype.loaded = function(){ return !! (window._pq && window._pq.push); }; /** * Track. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Track} event */ PerfectAudience.prototype.track = function(track){ var total = track.total() || track.revenue(); var orderId = track.orderId(); var props = {}; var sendProps = false; if (total) { props.revenue = total; sendProps = true; } if (orderId) { props.orderId = orderId; sendProps = true; } if (!sendProps) return push('track', track.event()); return push('track', track.event(), props); }; /** * Viewed Product. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Track} event */ PerfectAudience.prototype.viewedProduct = function(track){ var product = track.id() || track.sku(); push('track', track.event()); push('trackProduct', product); }; /** * Completed Purchase. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Track} event */ PerfectAudience.prototype.completedOrder = function(track){ var total = track.total() || track.revenue(); var orderId = track.orderId(); var props = {}; if (total) props.revenue = total; if (orderId) props.orderId = orderId; push('track', track.event(), props); }; }, {"analytics.js-integration":90,"global-queue":166}], 67: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_prum'); var date = require('load-date'); /** * Expose `Pingdom` integration. */ var Pingdom = module.exports = integration('Pingdom') .assumesPageview() .global('_prum') .global('PRUM_EPISODES') .option('id', '') .tag('<script src="//rum-static.pingdom.net/prum.min.js">'); /** * Initialize. * * @param {Object} page */ Pingdom.prototype.initialize = function(page){ window._prum = window._prum || []; push('id', this.options.id); push('mark', 'firstbyte', date.getTime()); var self = this; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Pingdom.prototype.loaded = function(){ return !! (window._prum && window._prum.push !== Array.prototype.push); }; }, {"analytics.js-integration":90,"global-queue":166,"load-date":165}], 68: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_paq'); var each = require('each'); var is = require('is'); /** * Expose `Piwik` integration. */ var Piwik = module.exports = integration('Piwik') .global('_paq') .option('url', null) .option('siteId', '') .option('customVariableLimit', 5) .mapping('goals') .tag('<script src="{{ url }}/piwik.js">'); /** * Initialize. * * http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking */ Piwik.prototype.initialize = function(){ window._paq = window._paq || []; push('setSiteId', this.options.siteId); push('setTrackerUrl', this.options.url + '/piwik.php'); push('enableLinkTracking'); this.load(this.ready); }; /** * Check if Piwik is loaded */ Piwik.prototype.loaded = function(){ return !! (window._paq && window._paq.push != [].push); }; /** * Page * * @param {Page} page */ Piwik.prototype.page = function(page){ push('trackPageView'); }; /** * Track. * * @param {Track} track */ Piwik.prototype.track = function(track){ var goals = this.goals(track.event()); var revenue = track.revenue(); var category = track.category() || 'All'; var action = track.event(); var name = track.proxy('properties.name') || track.proxy('properties.label'); var value = track.value() || track.revenue(); var options = track.options('Piwik'); var customVariables = options.customVars || options.cvar; if (!is.object(customVariables)) { customVariables = {}; } for (var i = 1; i <= this.options.customVariableLimit; i += 1){ if (customVariables[i]) { push('setCustomVariable', i.toString(), customVariables[i][0], customVariables[i][1], 'page'); } } each(goals, function(goal){ push('trackGoal', goal, revenue); }); push('trackEvent', category, action, name, value); }; }, {"analytics.js-integration":90,"global-queue":166,"each":4,"is":93}], 69: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var convertDates = require('convert-dates'); var push = require('global-queue')('_preactq'); var alias = require('alias'); /** * Expose `Preact` integration. */ var Preact = module.exports = integration('Preact') .assumesPageview() .global('_preactq') .global('_lnq') .option('projectCode', '') .tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/preact-4.1.min.js">'); /** * Initialize. * * http://www.preact.io/api/javascript * * @param {Object} page */ Preact.prototype.initialize = function(page){ window._preactq = window._preactq || []; window._lnq = window._lnq || []; push('_setCode', this.options.projectCode); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Preact.prototype.loaded = function(){ return !! (window._preactq && window._preactq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ 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 }); }; /** * Group. * * @param {String} id * @param {Object} properties (optional) * @param {Object} options (optional) */ Preact.prototype.group = function(group){ if (!group.groupId()) return; push('_setAccount', group.traits()); }; /** * Track. * * @param {Track} track */ 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); }; /** * Convert a `date` to a format Preact supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date / 1000); } }, {"analytics.js-integration":90,"convert-dates":170,"global-queue":166,"alias":169}], 70: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_kiq'); var Facade = require('facade'); var Identify = Facade.Identify; var bind = require('bind'); var when = require('when'); /** * Expose `Qualaroo` integration. */ var Qualaroo = module.exports = integration('Qualaroo') .assumesPageview() .global('_kiq') .option('customerId', '') .option('siteToken', '') .option('track', false) .tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">'); /** * Initialize. * * @param {Object} page */ Qualaroo.prototype.initialize = function(page){ window._kiq = window._kiq || []; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Qualaroo.prototype.loaded = function(){ return !! (window._kiq && window._kiq.push !== Array.prototype.push); }; /** * Identify. * * http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers * http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties * * @param {Identify} identify */ 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); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ 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 })); }; }, {"analytics.js-integration":90,"global-queue":166,"facade":139,"bind":103,"when":137}], 71: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_qevents', { wrap: false }); var integration = require('analytics.js-integration'); var useHttps = require('use-https'); var is = require('is'); var reduce = require('reduce'); /** * Expose `Quantcast` integration. */ var Quantcast = module.exports = integration('Quantcast') .assumesPageview() .global('_qevents') .global('__qc') .option('pCode', null) .option('advertise', false) .tag('http', '<script src="http://edge.quantserve.com/quant.js">') .tag('https', '<script src="https://secure.quantserve.com/quant.js">'); /** * Initialize. * * https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/ * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {Page} page */ Quantcast.prototype.initialize = function(page){ window._qevents = window._qevents || []; var opts = this.options; var settings = { qacct: opts.pCode }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); if (page) { settings.labels = this._labels('page', page.category(), page.name()); } push(settings); var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Quantcast.prototype.loaded = function(){ return !! window.__qc; }; /** * Page. * * https://cloudup.com/cBRRFAfq6mf * * @param {Page} page */ Quantcast.prototype.page = function(page){ var category = page.category(); var name = page.name(); var customLabels = page.proxy('properties.label') var labels = this._labels('page', category, name, customLabels); var settings = { event: 'refresh', labels: labels, qacct: this.options.pCode, }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); push(settings); }; /** * Identify. * * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {String} id (optional) */ Quantcast.prototype.identify = function(identify){ // edit the initial quantcast settings // TODO: could be done in a cleaner way var id = identify.userId(); if (id) { window._qevents[0] = window._qevents[0] || {}; window._qevents[0].uid = id; } }; /** * Track. * * https://cloudup.com/cBRRFAfq6mf * * @param {Track} track */ Quantcast.prototype.track = function(track){ var name = track.event(); var revenue = track.revenue(); var orderId = track.orderId(); var customLabels = track.proxy('properties.label'); var labels = this._labels('event', name, customLabels); var settings = { event: 'click', labels: labels, qacct: this.options.pCode }; var user = this.analytics.user(); if (null != revenue) settings.revenue = (revenue+''); // convert to string if (orderId) settings.orderid = orderId; if (user.id()) settings.uid = user.id(); push(settings); }; /** * Completed Order. * * @param {Track} track * @api private */ Quantcast.prototype.completedOrder = function(track){ var name = track.event(); var revenue = track.total(); var customLabels = track.proxy('properties.label') var labels = this._labels('event', name, customLabels); var category = track.category(); var repeat = track.proxy('properties.repeat'); if (this.options.advertise && category) { labels += ',' + this._labels('pcat', category); } if ('boolean' == typeof repeat) { labels += ',_fp.customer.' + (repeat ? 'repeat' : 'new'); } var settings = { event: 'refresh', // the example Quantcast sent has completed order send refresh not click labels: labels, revenue: (revenue+''), // convert to string orderid: track.orderId(), qacct: this.options.pCode }; push(settings); }; /** * Generate quantcast labels. * * Example: * * options.advertise = false; * labels('event', 'my event'); * // => "event.my event" * * options.advertise = true; * labels('event', 'my event'); * // => "_fp.event.my event" * * @param {String} type * @param {String} ... * @return {String} * @api private */ Quantcast.prototype._labels = function(type){ var args = Array.prototype.slice.call(arguments, 1); var advertise = this.options.advertise; if (advertise && 'page' == type) type = 'event'; if (advertise) type = '_fp.' + type; var separator = advertise ? ' ' : '.'; var ret = reduce(args, function(ret, arg){ if (arg != null) { ret.push(String(arg).replace(/, /g, ',')); } return ret; }, []).join(separator); return [type, ret].join('.'); }; }, {"global-queue":166,"analytics.js-integration":90,"use-https":92,"is":93,"reduce":183}], 183: [function(require, module, exports) { /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; }, {}], 72: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var extend = require('extend'); var is = require('is'); /** * Expose `Rollbar` integration. */ var RollbarIntegration = module.exports = integration('Rollbar') .global('Rollbar') .option('identify', true) .option('accessToken', '') .option('environment', 'unknown') .option('captureUncaught', true); /** * Initialize. * * @param {Object} page */ RollbarIntegration.prototype.initialize = function(page){ var _rollbarConfig = this.config = { accessToken: this.options.accessToken, captureUncaught: this.options.captureUncaught, payload: { environment: this.options.environment } }; // jscs:disable (function(a,b){function c(b){this.shimId=++h,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function d(b,c,d){a._rollbarWrappedError&&(d[4]||(d[4]=a._rollbarWrappedError),d[5]||(d[5]=a._rollbarWrappedError._rollbarContext),a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function e(b){var d=c;return g(function(){if(this.notifier)return this.notifier[b].apply(this.notifier,arguments);var c=this,e="scope"===b;e&&(c=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:c,method:b,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?c:void 0})}function f(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b&&b._wrapped?b._wrapped:b,c)}}}function g(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var h=0;c.init=function(a,b){var e=b.globalAlias||"Rollbar";if("object"==typeof a[e])return a[e];a._rollbarShimQueue=[],a._rollbarWrappedError=null,b=b||{};var h=new c;return g(function(){if(h.configure(b),b.captureUncaught){var c=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);d(h,c,a)};var g,i,j="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".split(",");for(g=0;g<j.length;++g)i=j[g],a[i]&&a[i].prototype&&f(h,a[i].prototype)}return a[e]=h,h},h.logger)()},c.prototype.loadFull=function(a,b,c,d,e){var f=g(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=g(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}"function"==typeof e&&e(b)},this.logger);g(function(){c?f():a.addEventListener?a.addEventListener("load",f,!1):a.attachEvent("onload",f)},this.logger)()},c.prototype.wrap=function(b,c){try{var d;if(d="function"==typeof c?c:function(){return c||{}},"function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw c._rollbarContext=d(),c._rollbarContext._wrappedSource=b.toString(),a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var e in b)b.hasOwnProperty(e)&&(b._wrapped[e]=b[e])}return b._wrapped}catch(f){return b}};for(var i="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),j=0;j<i.length;++j)c.prototype[i[j]]=e(i[j]);var k="//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||k;var l=c.init(a,_rollbarConfig);})(window,document); // jscs:enable this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ RollbarIntegration.prototype.loaded = function(){ return is.object(window.Rollbar) && null == window.Rollbar.shimId; }; /** * Load. * * @param {Function} callback */ RollbarIntegration.prototype.load = function(callback){ window.Rollbar.loadFull(window, document, true, this.config, callback); }; /** * Identify. * * @param {Identify} identify */ RollbarIntegration.prototype.identify = function(identify){ // do stuff with `id` or `traits` if (!this.options.identify) return; // Don't allow identify without a user id var uid = identify.userId(); if (uid === null || uid === undefined) return; var rollbar = window.Rollbar; var person = { id: uid }; extend(person, identify.traits()); rollbar.configure({ payload: { person: person }}); }; }, {"analytics.js-integration":90,"extend":136,"is":93}], 73: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `SaaSquatch` integration. */ var SaaSquatch = module.exports = integration('SaaSquatch') .option('tenantAlias', '') .option('referralImage', '') .global('_sqh') .tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">'); /** * Initialize. * * @param {Page} page */ SaaSquatch.prototype.initialize = function(page){ window._sqh = window._sqh || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ SaaSquatch.prototype.loaded = function(){ return window._sqh && window._sqh.push != [].push; }; /** * Identify. * * @param {Facade} identify */ SaaSquatch.prototype.identify = function(identify){ var sqh = window._sqh; var accountId = identify.proxy('traits.accountId'); var paymentProviderId = identify.proxy('traits.paymentProviderId'); var accountStatus = identify.proxy('traits.accountStatus'); var referralCode = identify.proxy('traits.referralCode'); var image = identify.proxy('traits.referralImage') || this.options.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 (paymentProviderId) init.payment_provider_id = paymentProviderId; if (init.payment_provider_id == "null") init.payment_provider_id = null; if (accountStatus) init.account_status = accountStatus; if (referralCode) init.referral_code = referralCode; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; /** * Group. * * @param {Group} group */ SaaSquatch.prototype.group = function(group){ var sqh = window._sqh; var props = group.properties(); var id = group.groupId(); var image = group.proxy('traits.referralImage') || this.options.referralImage; var opts = group.options(this.name); // tenant_alias is required. if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, account_id: id }; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; }, {"analytics.js-integration":90}], 74: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var when = require('when'); /** * Expose `SatisMeter` integration. */ var SatisMeter = module.exports = integration('SatisMeter') .global('satismeter') .option('token', '') .tag('<script src="https://app.satismeter.com/satismeter.js">'); /** * Initialize. * * @param {Object} page */ SatisMeter.prototype.initialize = function(page){ var self = this; this.load(function(){ when(function(){ return self.loaded(); }, self.ready); }); }; /** * Loaded? * * @return {Boolean} */ SatisMeter.prototype.loaded = function(){ return !!window.satismeter; }; /** * Identify. * * @param {Identify} identify */ SatisMeter.prototype.identify = function(identify){ var traits = identify.traits(); traits.token = this.options.token; traits.user = { id: identify.userId() }; if (identify.name()) { traits.user.name = identify.name(); } if (identify.email()) { traits.user.email = identify.email(); } if (identify.created()) { traits.user.signUpDate = identify.created().toISOString(); } // Remove traits that are already passed in user object delete traits.id; delete traits.email; delete traits.name; delete traits.created; window.satismeter(traits); }; }, {"analytics.js-integration":90,"when":137}], 75: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var localstorage = require('store'); var protocol = require('protocol'); var utm = require('utm-params'); var ads = require('ad-params'); var send = require('send-json'); var cookie = require('cookie'); var clone = require('clone'); var uuid = require('uuid'); var top = require('top-domain'); var extend = require('extend'); var json = require('segmentio/[email protected]'); /** * Cookie options */ var options = { maxage: 31536000000, // 1y secure: false, path: '/' }; /** * Expose `Segment` integration. */ var Segment = exports = module.exports = integration('Segment.io') .option('apiKey', ''); /** * Get the store. * * @return {Function} */ exports.storage = function(){ return 'file:' == protocol() || 'chrome-extension:' == protocol() ? localstorage : cookie; }; /** * Expose global for testing. */ exports.global = window; /** * Initialize. * * https://github.com/segmentio/segmentio/blob/master/modules/segmentjs/segment.js/v1/segment.js * * @param {Object} page */ Segment.prototype.initialize = function(page){ var self = this; this.ready(); this.analytics.on('invoke', function(msg){ var action = msg.action(); var listener = 'on' + msg.action(); self.debug('%s %o', action, msg); if (self[listener]) self[listener](msg); self.ready(); }); }; /** * Loaded. * * @return {Boolean} */ Segment.prototype.loaded = function(){ return true; }; /** * Page. * * @param {Page} page */ Segment.prototype.onpage = function(page){ this.send('/p', page.json()); }; /** * Identify. * * @param {Identify} identify */ Segment.prototype.onidentify = function(identify){ this.send('/i', identify.json()); }; /** * Group. * * @param {Group} group */ Segment.prototype.ongroup = function(group){ this.send('/g', group.json()); }; /** * Track. * * @param {Track} track */ Segment.prototype.ontrack = function(track){ var json = track.json(); delete json.traits; // TODO: figure out why we need traits. this.send('/t', json); }; /** * Alias. * * @param {Alias} alias */ Segment.prototype.onalias = function(alias){ var json = alias.json(); var user = this.analytics.user(); json.previousId = json.previousId || json.from || user.id() || user.anonymousId(); json.userId = json.userId || json.to; delete json.from; delete json.to; this.send('/a', json); }; /** * Normalize the given `msg`. * * @param {Object} msg * @api private */ Segment.prototype.normalize = function(msg){ this.debug('normalize %o', msg); var user = this.analytics.user(); var global = exports.global; var query = global.location.search; var ctx = msg.context = msg.context || msg.options || {}; delete msg.options; msg.writeKey = this.options.apiKey; ctx.userAgent = navigator.userAgent; if (!ctx.library) ctx.library = { name: 'analytics.js', version: this.analytics.VERSION }; if (query) ctx.campaign = utm(query); this.referrerId(query, ctx); msg.userId = msg.userId || user.id(); msg.anonymousId = user.anonymousId(); msg.messageId = uuid(); msg.sentAt = new Date(); this.debug('normalized %o', msg); return msg; }; /** * Send `obj` to `path`. * * @param {String} path * @param {Object} obj * @param {Function} fn * @api private */ Segment.prototype.send = function(path, msg, fn){ var url = scheme() + '//api.segment.io/v1' + path; var headers = { 'Content-Type': 'text/plain' }; var fn = fn || noop; var self = this; // msg msg = this.normalize(msg); // send send(url, msg, headers, function(err, res){ self.debug('sent %O, received %O', msg, arguments); if (err) return fn(err); res.url = url; fn(null, res); }); }; /** * Gets/sets cookies on the appropriate domain. * * @param {String} name * @param {Mixed} val */ Segment.prototype.cookie = function(name, val){ var store = Segment.storage(); if (arguments.length === 1) return store(name); var global = exports.global; var href = global.location.href; var domain = '.' + top(href); if ('.' == domain) domain = ''; this.debug('store domain %s -> %s', href, domain); var opts = clone(options); opts.domain = domain; this.debug('store %s, %s, %o', name, val, opts); store(name, val, opts); if (store(name)) return; delete opts.domain; this.debug('fallback store %s, %s, %o', name, val, opts); store(name, val, opts); }; /** * Add referrerId to context. * * TODO: remove. * * @param {Object} query * @param {Object} ctx * @api private */ Segment.prototype.referrerId = function(query, ctx){ var stored = this.cookie('s:context.referrer'); var ad; if (stored) stored = json.parse(stored); if (query) ad = ads(query); ad = ad || stored; if (!ad) return; ctx.referrer = extend(ctx.referrer || {}, ad); this.cookie('s:context.referrer', json.stringify(ad)); } /** * Get the scheme. * * The function returns `http:` * if the protocol is `http:` and * `https:` for other protocols. * * @return {String} */ function scheme(){ return 'http:' == protocol() ? 'http:' : 'https:'; } /** * Noop */ function noop(){} }, {"analytics.js-integration":90,"store":184,"protocol":185,"utm-params":129,"ad-params":186,"send-json":187,"cookie":188,"clone":96,"uuid":189,"top-domain":130,"extend":136,"segmentio/[email protected]":171}], 184: [function(require, module, exports) { /** * dependencies. */ var unserialize = require('unserialize'); var each = require('each'); var storage; /** * Safari throws when a user * blocks access to cookies / localstorage. */ try { storage = window.localStorage; } catch (e) { storage = null; } /** * Expose `store` */ module.exports = store; /** * Store the given `key`, `val`. * * @param {String|Object} key * @param {Mixed} value * @return {Mixed} * @api public */ function store(key, value){ var length = arguments.length; if (0 == length) return all(); if (2 <= length) return set(key, value); if (1 != length) return; if (null == key) return storage.clear(); if ('string' == typeof key) return get(key); if ('object' == typeof key) return each(key, set); } /** * supported flag. */ store.supported = !! storage; /** * Set `key` to `val`. * * @param {String} key * @param {Mixed} val */ function set(key, val){ return null == val ? storage.removeItem(key) : storage.setItem(key, JSON.stringify(val)); } /** * Get `key`. * * @param {String} key * @return {Mixed} */ function get(key){ return unserialize(storage.getItem(key)); } /** * Get all. * * @return {Object} */ function all(){ var len = storage.length; var ret = {}; var key; while (0 <= --len) { key = storage.key(len); ret[key] = get(key); } return ret; } }, {"unserialize":190,"each":109}], 190: [function(require, module, exports) { /** * Unserialize the given "stringified" javascript. * * @param {String} val * @return {Mixed} */ module.exports = function(val){ try { return JSON.parse(val); } catch (e) { return val || undefined; } }; }, {}], 185: [function(require, module, exports) { /** * Convenience alias */ var define = Object.defineProperty; /** * The base protocol */ var initialProtocol = window.location.protocol; /** * Fallback mocked protocol in case Object.defineProperty doesn't exist. */ var mockedProtocol; module.exports = function (protocol) { if (arguments.length === 0) return get(); else return set(protocol); }; /** * Sets the protocol to be http: */ module.exports.http = function () { set('http:'); }; /** * Sets the protocol to be https: */ module.exports.https = function () { set('https:'); }; /** * Reset to the initial protocol. */ module.exports.reset = function () { set(initialProtocol); }; /** * Gets the current protocol, using the fallback and then the native protocol. * * @return {String} protocol */ function get () { return mockedProtocol || window.location.protocol; } /** * Sets the protocol * * @param {String} protocol */ function set (protocol) { try { define(window.location, 'protocol', { get: function () { return protocol; } }); } catch (err) { mockedProtocol = protocol; } } }, {}], 186: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('querystring').parse; /** * Expose `ads` */ module.exports = ads; /** * All the ad query params we look for. */ var QUERYIDS = { 'btid' : 'dataxu', 'urid' : 'millennial-media' }; /** * Get all ads info from the given `querystring` * * @param {String} query * @return {Object} * @api private */ function ads(query){ var params = parse(query); for (var key in params) { for (var id in QUERYIDS) { if (key === id) { return { id : params[key], type : QUERYIDS[id] }; } } } } }, {"querystring":131}], 187: [function(require, module, exports) { /** * Module dependencies. */ var encode = require('base64-encode'); var cors = require('has-cors'); var jsonp = require('jsonp'); var JSON = require('json'); /** * Expose `send` */ exports = module.exports = cors ? json : base64; /** * Expose `callback` */ exports.callback = 'callback'; /** * Expose `prefix` */ exports.prefix = 'data'; /** * Expose `json`. */ exports.json = json; /** * Expose `base64`. */ exports.base64 = base64; /** * Expose `type` */ exports.type = cors ? 'xhr' : 'jsonp'; /** * Send the given `obj` to `url` with `fn(err, req)`. * * @param {String} url * @param {Object} obj * @param {Object} headers * @param {Function} fn * @api private */ function json(url, obj, headers, fn){ if (3 == arguments.length) fn = headers, headers = {}; var req = new XMLHttpRequest; req.onerror = fn; req.onreadystatechange = done; req.open('POST', url, true); for (var k in headers) req.setRequestHeader(k, headers[k]); req.send(JSON.stringify(obj)); function done(){ if (4 == req.readyState) return fn(null, req); } } /** * Send the given `obj` to `url` with `fn(err, req)`. * * @param {String} url * @param {Object} obj * @param {Function} fn * @api private */ function base64(url, obj, _, fn){ if (3 == arguments.length) fn = _; var prefix = exports.prefix; obj = encode(JSON.stringify(obj)); obj = encodeURIComponent(obj); url += '?' + prefix + '=' + obj; jsonp(url, { param: exports.callback }, function(err, obj){ if (err) return fn(err); fn(null, { url: url, body: obj }); }); } }, {"base64-encode":191,"has-cors":192,"jsonp":193,"json":171}], 191: [function(require, module, exports) { var utf8Encode = require('utf8-encode'); var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; module.exports = encode; function encode(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } }, {"utf8-encode":194}], 194: [function(require, module, exports) { module.exports = encode; function encode(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } }, {}], 192: [function(require, module, exports) { /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } }, {}], 193: [function(require, module, exports) { /** * Module dependencies */ var debug = require('debug')('jsonp'); /** * Module exports. */ module.exports = jsonp; /** * Callback index. */ var count = 0; /** * Noop function. */ function noop(){} /** * JSONP handler * * Options: * - param {String} qs parameter (`callback`) * - timeout {Number} how long after a timeout error is emitted (`60000`) * * @param {String} url * @param {Object|Function} optional options / callback * @param {Function} optional callback */ function jsonp(url, opts, fn){ if ('function' == typeof opts) { fn = opts; opts = {}; } if (!opts) opts = {}; var prefix = opts.prefix || '__jp'; var param = opts.param || 'callback'; var timeout = null != opts.timeout ? opts.timeout : 60000; var enc = encodeURIComponent; var target = document.getElementsByTagName('script')[0] || document.head; var script; var timer; // generate a unique id for this request var id = prefix + (count++); if (timeout) { timer = setTimeout(function(){ cleanup(); if (fn) fn(new Error('Timeout')); }, timeout); } function cleanup(){ script.parentNode.removeChild(script); window[id] = noop; } window[id] = function(data){ debug('jsonp got', data); if (timer) clearTimeout(timer); cleanup(); if (fn) fn(null, data); }; // add qs component url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id); url = url.replace('?&', '?'); debug('jsonp req "%s"', url); // create script script = document.createElement('script'); script.src = url; target.parentNode.insertBefore(script, target); } }, {"debug":195}], 195: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":196,"./debug":197}], 196: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , 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'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 197: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ 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); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ 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 + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , 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'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ 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; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 188: [function(require, module, exports) { /** * Module dependencies. */ var debug = require('debug')('cookie'); /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ 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(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ 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.toUTCString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { return parse(document.cookie); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ 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; } /** * Encode. */ function encode(value){ try { return encodeURIComponent(value); } catch (e) { debug('error `encode(%o)` - %o', value, e) } } /** * Decode. */ function decode(value) { try { return decodeURIComponent(value); } catch (e) { debug('error `decode(%o)` - %o', value, e) } } }, {"debug":195}], 189: [function(require, module, exports) { /** * Taken straight from jed's gist: https://gist.github.com/982883 * * Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, * where each x is replaced with a random hexadecimal digit from 0 to f, and * y is replaced with a random hexadecimal digit from 8 to b. */ module.exports = function uuid(a){ return a // if the placeholder was passed, return ? ( // a random number from 0 to 15 a ^ // unless b is 8, Math.random() // in which case * 16 // a random number from >> a/4 // 8 to 11 ).toString(16) // in hexadecimal : ( // or otherwise a concatenated string: [1e7] + // 10000000 + -1e3 + // -1000 + -4e3 + // -4000 + -8e3 + // -80000000 + -1e11 // -100000000000, ).replace( // replacing /[018]/g, // zeroes, ones, and eights with uuid // random hex digits ) }; }, {}], 76: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Sentry` integration. */ var Sentry = module.exports = integration('Sentry') .global('Raven') .option('config', '') .tag('<script src="//cdn.ravenjs.com/1.1.16/native/raven.min.js">'); /** * Initialize. * * http://raven-js.readthedocs.org/en/latest/config/index.html * https://github.com/getsentry/raven-js/blob/1.1.16/src/raven.js#L734-L741 */ Sentry.prototype.initialize = function(){ var dsn = this.options.config; window.RavenConfig = { dsn: dsn }; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Sentry.prototype.loaded = function(){ return is.object(window.Raven); }; /** * Identify. * * @param {Identify} identify */ Sentry.prototype.identify = function(identify){ window.Raven.setUser(identify.traits()); }; }, {"analytics.js-integration":90,"is":93}], 77: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); var tick = require('next-tick'); /** * Expose `SnapEngage` integration. */ var SnapEngage = module.exports = integration('SnapEngage') .assumesPageview() .global('SnapABug') .global('SnapEngage') .option('apiKey', '') .option('listen', false) .tag('<script src="//www.snapengage.com/cdn/js/{{ apiKey }}.js">'); /** * Integration object for root events. */ var integration = { name: 'snapengage', version: '1.0.0' }; /** * Initialize. * * http://help.snapengage.com/installation-guide-getting-started-in-a-snap/ * * @param {Object} page */ SnapEngage.prototype.initialize = function(page){ var self = this; this.load(function(){ if (self.options.listen) self.attachListeners(); tick(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ SnapEngage.prototype.loaded = function(){ return is.object(window.SnapABug) && is.object(window.SnapEngage); }; /** * Listen for events. */ SnapEngage.prototype.attachListeners = function(){ var self = this; window.SnapEngage.setCallback('StartChat', function(email, message, type){ self.analytics.track('Live Chat Conversation Started', {}, { context: { integration: integration } }); }); window.SnapEngage.setCallback('ChatMessageReceived', function(agent, message){ self.analytics.track('Live Chat Message Received', { agentUsername: agent }, { context: { integration: integration } }); }); window.SnapEngage.setCallback('ChatMessageSent', function(message){ self.analytics.track('Live Chat Message Sent', {}, { context: { integration: integration }}); }); window.SnapEngage.setCallback('Close', function(type, status){ self.analytics.track('Live Chat Conversation Ended', {}, { context: { integration: integration }}); }); }; /** * Identify. * * @param {Identify} identify */ SnapEngage.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; window.SnapABug.setUserEmail(email); }; }, {"analytics.js-integration":90,"is":93,"next-tick":116}], 78: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); /** * Expose `Spinnakr` integration. */ var Spinnakr = module.exports = integration('Spinnakr') .assumesPageview() .global('_spinnakr_site_id') .global('_spinnakr') .option('siteId', '') .tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">'); /** * Initialize. * * @param {Object} page */ Spinnakr.prototype.initialize = function(page){ window._spinnakr_site_id = this.options.siteId; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Spinnakr.prototype.loaded = function(){ return !! window._spinnakr; }; }, {"analytics.js-integration":90,"bind":103,"when":137}], 79: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `SupportHero` integration. */ var SupportHero = module.exports = integration('SupportHero') .assumesPageview() .global('supportHeroWidget') .option('token', '') .option('track', false) .tag('<script src="https://d29l98y0pmei9d.cloudfront.net/js/widget.min.js?k={{ token }}">'); /** * Initialize Support Hero. * * @param {Facade} page */ SupportHero.prototype.initialize = function(page){ window.supportHeroWidget = {}; window.supportHeroWidget.setUserId = window.supportHeroWidget.setUserId || function(){}; window.supportHeroWidget.setUserTraits = window.supportHeroWidget.setUserTraits || function(){}; this.load(this.ready); }; /** * Has the Support Hero library been loaded yet? * * @return {Boolean} */ SupportHero.prototype.loaded = function(){ return !! window.supportHeroWidget; }; /** * Identify a user. * * @param {Facade} identify */ SupportHero.prototype.identify = function(identify){ var id = identify.userId(); var traits = identify.traits(); if (id) { window.supportHeroWidget.setUserId(id); } if (traits) { window.supportHeroWidget.setUserTraits(traits); } }; }, {"analytics.js-integration":90}], 80: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var slug = require('slug'); var push = require('global-queue')('_tsq'); /** * Expose `Tapstream` integration. */ var Tapstream = module.exports = integration('Tapstream') .assumesPageview() .global('_tsq') .option('accountName', '') .option('trackAllPages', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">'); /** * Initialize. * * @param {Object} page */ Tapstream.prototype.initialize = function(page){ window._tsq = window._tsq || []; push('setAccountName', this.options.accountName); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Tapstream.prototype.loaded = function(){ return !! (window._tsq && window._tsq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Tapstream.prototype.page = function(page){ var category = page.category(); var opts = this.options; var name = page.fullName(); // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Track. * * @param {Track} track */ Tapstream.prototype.track = function(track){ var props = track.properties(); push('fireHit', slug(track.event()), [props.url]); // needs events as slugs }; }, {"analytics.js-integration":90,"slug":100,"global-queue":166}], 81: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Trakio` integration. */ var Trakio = module.exports = integration('trak.io') .assumesPageview() .global('trak') .option('token', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">'); /** * Options aliases. */ var optionsAliases = { initialPageview: 'auto_track_page_view' }; /** * Initialize. * * https://docs.trak.io * * @param {Object} page */ Trakio.prototype.initialize = function(page){ var options = this.options; window.trak = window.trak || []; window.trak.io = window.trak.io || {}; window.trak.push = window.trak.push || function(){}; window.trak.io.load = window.trak.io.load || function(e){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(this.ready); }; /** * Loaded? * * @return {Boolean} */ Trakio.prototype.loaded = function(){ return !! (window.trak && window.trak.loaded); }; /** * Page. * * @param {Page} page */ 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 (category) window.trak.io.channel('category'); // named pages if (name && this.options.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && this.options.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Trait aliases. * * http://docs.trak.io/properties.html#special */ var traitAliases = { avatar: 'avatar_url', firstName: 'first_name', lastName: 'last_name' }; /** * Identify. * * @param {Identify} identify */ 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); } }; /** * Group. * * @param {String} id (optional) * @param {Object} properties (optional) * @param {Object} options (optional) * * TODO: add group * TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special */ /** * Track. * * @param {Track} track */ Trakio.prototype.track = function(track){ var properties = track.properties(); var channel = track.proxy('properties.channel'); if (channel) { delete properties.channel; window.trak.io.track(track.event(), channel, properties); } else { window.trak.io.track(track.event(), properties); } }; /** * Alias. * * @param {Alias} alias */ 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); } }; }, {"analytics.js-integration":90,"alias":169,"clone":96}], 82: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `TwitterAds`. */ var TwitterAds = module.exports = integration('Twitter Ads') .option('page', '') .tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>') .mapping('events'); /** * Initialize. * * @param {Object} page */ TwitterAds.prototype.initialize = function(){ this.ready(); }; /** * Page. * * @param {Page} page */ TwitterAds.prototype.page = function(page){ if (this.options.page) { this.load({ pixelId: this.options.page }); } }; /** * Track. * * @param {Track} track */ TwitterAds.prototype.track = function(track){ var events = this.events(track.event()); var self = this; each(events, function(pixelId){ self.load({ pixelId: pixelId }); }); }; }, {"analytics.js-integration":90,"each":4}], 83: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var clone = require('clone'); /** * Expose Userlike integration. */ var Userlike = module.exports = integration('Userlike') .assumesPageview() .global('userlikeConfig') .global('userlikeData') .option('secretKey', '') .option('listen', false) .tag('<script src="//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/{{ secretKey }}.js">'); /** * The context for this integration. */ var integration = { name: 'userlike', version: '1.0.0' }; /** * Initialize. * * @param {Object} page */ Userlike.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var identify = new Identify({ userId: user.id(), traits: user.traits() }); segment_base_info = clone(this.options); segment_base_info.visitor = { name: identify.name(), email: identify.email() }; if (!window.userlikeData) window.userlikeData = { custom: {} }; window.userlikeData.custom.segmentio = segment_base_info; this.load(function(){ if (self.options.listen) self.attachListeners(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Userlike.prototype.loaded = function(){ return !! (window.userlikeConfig && window.userlikeData); }; /** * Listen for chat events. * * TODO: As of 4/17/2015, Userlike doesn't give access to the message body in events. * Revisit this/send it when they do. * */ Userlike.prototype.attachListeners = function(){ var self = this; window.userlikeTrackingEvent = function(eventName, globalCtx, sessionCtx){ if (eventName === 'chat_started') { self.analytics.track( 'Live Chat Conversation Started', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } if (eventName === 'message_operator_terminating') { self.analytics.track( 'Live Chat Message Sent', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } if (eventName === 'message_client_terminating') { self.analytics.track( 'Live Chat Message Received', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } if (eventName === 'chat_quit') { self.analytics.track( 'Live Chat Conversation Ended', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } }; }; }, {"analytics.js-integration":90,"facade":139,"clone":96}], 84: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('UserVoice'); var convertDates = require('convert-dates'); var unix = require('to-unix-timestamp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `UserVoice` integration. */ var UserVoice = module.exports = integration('UserVoice') .assumesPageview() .global('UserVoice') .global('showClassicWidget') .option('apiKey', '') .option('classic', false) .option('forumId', null) .option('showWidget', true) .option('mode', 'contact') .option('accentColor', '#448dd6') .option('screenshotEnabled', true) .option('smartvote', true) .option('trigger', null) .option('triggerPosition', 'bottom-right') .option('triggerColor', '#ffffff') .option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)') // BACKWARDS COMPATIBILITY: classic options .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) .option('customTicketFields', {}) .tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">'); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ UserVoice.on('construct', function(integration){ if (!integration.options.classic) return; integration.group = undefined; integration.identify = integration.identifyClassic; integration.initialize = integration.initializeClassic; }); /** * Initialize. * * @param {Object} page */ 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(this.ready); }; /** * Loaded? * * @return {Boolean} */ UserVoice.prototype.loaded = function(){ return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ UserVoice.prototype.identify = function(identify){ var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', traits); }; /** * Group. * * @param {Group} group */ UserVoice.prototype.group = function(group){ var traits = group.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', { account: traits }); }; /** * Initialize (classic). * * @param {Object} options * @param {Function} ready */ UserVoice.prototype.initializeClassic = function(){ var options = this.options; window.showClassicWidget = showClassicWidget; // part of public api if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options)); this.load(this.ready); }; /** * Identify (classic). * * @param {Identify} identify */ UserVoice.prototype.identifyClassic = function(identify){ push('setCustomFields', identify.traits()); }; /** * Format the options for UserVoice. * * @param {Object} options * @return {Object} */ 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', screenshotEnabled: 'screenshot_enabled', customTicketFields: 'ticket_custom_fields' }); } /** * Format the classic options for UserVoice. * * @param {Object} options * @return {Object} */ 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' }); } /** * Show the classic version of the UserVoice widget. This method is usually part * of UserVoice classic's public API. * * @param {String} type ('showTab' or 'showLightbox') * @param {Object} options (optional) */ function showClassicWidget(type, options){ type = type || 'showLightbox'; push(type, 'classic_widget', options); } }, {"analytics.js-integration":90,"global-queue":166,"convert-dates":170,"to-unix-timestamp":198,"alias":169,"clone":96}], 198: [function(require, module, exports) { /** * Expose `toUnixTimestamp`. */ module.exports = toUnixTimestamp; /** * Convert a `date` into a Unix timestamp. * * @param {Date} * @return {Number} */ function toUnixTimestamp (date) { return Math.floor(date.getTime() / 1000); } }, {}], 85: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_veroq'); var cookie = require('component/cookie'); var objCase = require('obj-case'); /** * Expose `Vero` integration. */ var Vero = module.exports = integration('Vero') .global('_veroq') .option('apiKey', '') .tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">'); /** * Initialize. * * https://github.com/getvero/vero-api/blob/master/sections/js.md * * @param {Object} page */ Vero.prototype.initialize = function(page){ // clear default cookie so vero parses correctly. // this is for the tests. // basically, they have window.addEventListener('unload') // which then saves their "command_store", which is an array. // so we just want to create that initially so we can reload the tests. if (!cookie('__veroc4')) cookie('__veroc4', '[]'); push('init', { api_key: this.options.apiKey }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Vero.prototype.loaded = function(){ return !! (window._veroq && window._veroq.push !== Array.prototype.push); }; /** * Page. * * https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews * * @param {Page} page */ Vero.prototype.page = function(page){ push('trackPageview'); }; /** * Identify. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification * * @param {Identify} identify */ Vero.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var id = identify.userId(); if (!id || !email) return; // both required push('user', traits); }; /** * Track. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events * * @param {Track} track */ Vero.prototype.track = function(track){ var regex = /[uU]nsubscribe/; if (track.event().match(regex)) { push('unsubscribe', { id: track.properties().id }); } else { push('track', track.event(), track.properties()); } }; Vero.prototype.alias = function(alias){ var to = alias.to(); if (alias.from()) { push('reidentify', to, alias.from()); } else { push('reidentify', to); } }; }, {"analytics.js-integration":90,"global-queue":166,"component/cookie":188,"obj-case":94}], 86: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); var each = require('each'); /** * Expose `VWO` integration. */ var VWO = module.exports = integration('Visual Website Optimizer') .option('replay', true) .option('listen', false); /** * The context for this integration. */ var integration = { name: 'visual-website-optimizer', version: '1.0.0' }; /** * Initialize. * * http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php */ VWO.prototype.initialize = function(){ var self = this; if (this.options.replay) { tick(function(){ self.replay(); }); } if (this.options.listen) { tick(function(){ self.roots(); }); } this.ready(); }; /** * Completed Purchase. * * https://vwo.com/knowledge/vwo-revenue-tracking-goal */ VWO.prototype.completedOrder = function(track){ var total = track.total() || track.revenue() || 0; enqueue(function(){ _vis_opt_revenue_conversion(total); }); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.replay = function(){ var analytics = this.analytics; experiments(function(err, traits){ if (traits) analytics.identify(traits); }); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.roots = function(){ var analytics = this.analytics; rootExperiments(function(err, data){ each(data, function(experimentId, variationName){ analytics.track( 'Experiment Viewed', { experimentId: experimentId, variationName: variationName }, { context: { integration: integration }} ); }); }); }; /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} fn * @return {Object} */ function rootExperiments(fn){ enqueue(function(){ var data = {}; var experimentIds = window._vwo_exp_ids; if (!experimentIds) return fn(); each(experimentIds, function(experimentId){ var variationName = variation(experimentId); if (variationName) data[experimentId] = variationName; }); fn(null, data); }); } /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} fn * @return {Object} */ function experiments(fn){ enqueue(function(){ var data = {}; var ids = window._vwo_exp_ids; if (!ids) return fn(); each(ids, function(id){ var name = variation(id); if (name) data['Experiment: ' + id] = name; }); fn(null, data); }); } /** * Add a `fn` to the VWO queue, creating one if it doesn't exist. * * @param {Function} fn */ function enqueue(fn){ window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); } /** * Get the chosen variation's name from an experiment `id`. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {String} id * @return {String} */ 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; } }, {"analytics.js-integration":90,"next-tick":116,"each":4}], 87: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `WebEngage` integration. */ var WebEngage = module.exports = integration('WebEngage') .assumesPageview() .global('_weq') .global('webengage') .option('widgetVersion', '4.0') .option('licenseCode', '') .tag('http', '<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">') .tag('https', '<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">'); /** * Initialize. * * @param {Object} page */ WebEngage.prototype.initialize = function(page){ var _weq = window._weq = window._weq || {}; _weq['webengage.licenseCode'] = this.options.licenseCode; _weq['webengage.widgetVersion'] = this.options.widgetVersion; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ WebEngage.prototype.loaded = function(){ return !! window.webengage; }; }, {"analytics.js-integration":90,"use-https":92}], 88: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var snake = require('to-snake-case'); var isEmail = require('is-email'); var extend = require('extend'); var each = require('each'); var type = require('type'); /** * Expose `Woopra` integration. */ var Woopra = module.exports = integration('Woopra') .global('woopra') .option('domain', '') .option('cookieName', 'wooTracker') .option('cookieDomain', null) .option('cookiePath', '/') .option('ping', true) .option('pingInterval', 12000) .option('idleTimeout', 300000) .option('downloadTracking', true) .option('outgoingTracking', true) .option('outgoingIgnoreSubdomain', true) .option('downloadPause', 200) .option('outgoingPause', 400) .option('ignoreQueryUrl', true) .option('hideCampaign', false) .tag('<script src="//static.woopra.com/js/w.js">'); /** * Initialize. * * http://www.woopra.com/docs/setup/javascript-tracking/ * * @param {Object} page */ 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'); this.load(this.ready); each(this.options, function(key, value){ key = snake(key); if (null == value) return; if ('' === value) return; window.woopra.config(key, value); }); }; /** * Loaded? * * @return {Boolean} */ Woopra.prototype.loaded = function(){ return !! (window.woopra && window.woopra.loaded); }; /** * Page. * * @param {String} category (optional) */ Woopra.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); if (name) props.title = name; window.woopra.track('pv', props); }; /** * Identify. * * @param {Identify} identify */ Woopra.prototype.identify = function(identify){ var traits = identify.traits(); if (identify.name()) traits.name = identify.name(); window.woopra.identify(traits).push(); // `push` sends it off async }; /** * Track. * * @param {Track} track */ Woopra.prototype.track = function(track){ window.woopra.track(track.event(), track.properties()); }; }, {"analytics.js-integration":90,"to-snake-case":91,"is-email":161,"extend":136,"each":4,"type":117}], 89: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); var bind = require('bind'); var when = require('when'); /** * Expose `Yandex` integration. */ var Yandex = module.exports = integration('Yandex Metrica') .assumesPageview() .global('yandex_metrika_callbacks') .global('Ya') .option('counterId', null) .option('clickmap', false) .option('webvisor', false) .tag('<script src="//mc.yandex.ru/metrika/watch.js">'); /** * Initialize. * * http://api.yandex.com/metrika/ * https://metrica.yandex.com/22522351?step=2#tab=code * * @param {Object} page */ Yandex.prototype.initialize = function(page){ var id = this.options.counterId; var clickmap = this.options.clickmap; var webvisor = this.options.webvisor; push(function(){ window['yaCounter' + id] = new window.Ya.Metrika({ id: id, clickmap: clickmap, webvisor: webvisor }); }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, function(){ tick(ready); }); }); }; /** * Loaded? * * @return {Boolean} */ Yandex.prototype.loaded = function(){ return !! (window.Ya && window.Ya.Metrika); }; /** * Push a new callback on the global Yandex queue. * * @param {Function} callback */ function push(callback){ window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); } }, {"analytics.js-integration":90,"next-tick":116,"bind":103,"when":137}], 3: [function(require, module, exports) { var _analytics = window.analytics; var after = require('after'); var bind = require('bind'); var callback = require('callback'); 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 pageDefaults = require('./pageDefaults'); var pick = require('pick'); var prevent = require('prevent'); var querystring = require('querystring'); var normalize = require('./normalize'); var size = require('object').length; var keys = require('object').keys; var memory = require('./memory'); var store = require('./store'); 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; /** * Expose `Analytics`. */ exports = module.exports = Analytics; /** * Expose storage. */ exports.cookie = cookie; exports.store = store; exports.memory = memory; /** * Initialize a new `Analytics` instance. */ function Analytics () { this._options({}); this.Integrations = {}; this._integrations = {}; this._readied = false; this._timeout = 300; this._user = user; // BACKWARDS COMPATIBILITY this.log = debug('analytics.js'); bind.all(this); var self = this; this.on('initialize', function(settings, options){ if (options.initialPageview) self.page(); self._parseQuery(); }); } /** * Event Emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function (plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ 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; }; /** * Initialize with the given integration `settings` and `options`. Aliased to * `init` for convenience. * * @param {Object} settings * @param {Object} options (optional) * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function (settings, options) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; // clean unknown integrations from settings var self = this; each(settings, function (name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }); // add integrations each(settings, function (name, opts) { var Integration = self.Integrations[name]; var integration = new Integration(clone(opts)); self.log('initialize %o - %o', name, opts); self.add(integration); }); var integrations = this._integrations; // load user now that options are set user.load(); group.load(); // make ready callback var ready = after(size(integrations), function () { self._readied = true; self.emit('ready'); }); // initialize integrations, passing ready each(integrations, function (name, integration) { if (options.initialPageview && integration.options.initialPageview === false) { integration.page = after(2, integration.page); } integration.analytics = self; integration.once('ready', ready); integration.initialize(); }); // backwards compat with angular plugin. // TODO: remove this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Set the user's `id`. * * @param {Mixed} id */ Analytics.prototype.setAnonymousId = function(id){ this.user().anonymousId(id); return this; }; /** * Add an integration. * * @param {Integration} integration */ Analytics.prototype.add = function(integration){ this._integrations[integration.name] = integration; return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ 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(); // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); var msg = this.normalize({ options: options, traits: user.traits(), userId: user.id(), }); this._invoke('identify', new Identify(msg)); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function () { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics or Object} */ 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(); // grab from group again to make sure we're taking from the source group.identify(id, traits); var msg = this.normalize({ options: options, traits: group.traits(), groupId: group.id() }); this._invoke('group', new Group(msg)); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ 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; // figure out if the event is archived. var plan = this.options.plan || {}; var events = plan.track || {}; // normalize var msg = this.normalize({ properties: properties, options: options, event: event }); // plan. if (plan = events[event]) { this.log('plan %o - %o', event, plan); if (false == plan.enabled) return this._callback(fn); defaults(msg.integrations, plan.integrations || {}); } this._invoke('track', new Track(msg)); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element or Array} links * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function (links, event, properties) { if (!links) return this; if (is.element(links)) links = [links]; // always arrays, handles jquery var self = this; each(links, function (el) { if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.'); on(el, 'click', function (e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; var href = el.getAttribute('href') || el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || el.getAttribute('xlink:href'); self.track(ev, props); if (href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function () { window.location.href = href; }); } }); }); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element or Array} forms * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function (forms, event, properties) { if (!forms) return this; if (is.element(forms)) forms = [forms]; // always arrays, handles jquery var self = this; each(forms, function (el) { if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.'); 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(); }); } // support the events happening through jQuery or Zepto instead of through // the normal DOM API, since `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object or String} properties (or path) (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ 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; properties = clone(properties) || {}; if (name) properties.name = name; if (category) properties.category = category; // Ensure properties has baseline spec properties. // TODO: Eventually move these entirely to `options.context.page` var defs = pageDefaults(); defaults(properties, defs); // Mirror user overrides to `options.context.page` (but exclude custom properties) // (Any page defaults get applied in `this.normalize` for consistency.) // Weird, yeah--moving special props to `context.page` will fix this in the long term. var overrides = pick(keys(defs), properties); if (!is.empty(overrides)) { options = options || {}; options.context = options.context || {}; options.context.page = overrides; } var msg = this.normalize({ properties: properties, category: category, options: options, name: name }); this._invoke('page', new Page(msg)); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {String} url (optional) * @param {Object} options (optional) * @return {Analytics} * @api private */ Analytics.prototype.pageview = function (url, options) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {String} to * @param {String} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ 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; var msg = this.normalize({ options: options, previousId: from, userId: to }); this._invoke('alias', new Alias(msg)); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function (fn) { if (!is.fn(fn)) return this; this._readied ? callback.async(fn) : this.once('ready', fn); return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function (timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {String or Boolean} str */ Analytics.prototype.debug = function(str){ if (0 == arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function (options) { options = options || {}; this.options = options; cookie.options(options.cookie); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function (fn) { callback.async(fn, this._timeout); return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {String} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function (method, facade) { var options = facade.options(); this.emit('invoke', facade); each(this._integrations, function (name, integration) { if (!facade.enabled(name)) return; integration.invoke.call(integration, method, facade); }); return this; }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args){ var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Reset group and user traits and id's. * * @api public */ Analytics.prototype.reset = function(){ this.user().logout(); this.group().logout(); }; /** * Parse the query string for callable methods. * * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function () { // Identify and track any `ajs_uid` and `ajs_event` parameters in the URL. 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); if (q.ajs_aid) user.anonymousId(q.ajs_aid); return this; }; /** * Normalize the given `msg`. * * @param {Object} msg * @return {Object} */ Analytics.prototype.normalize = function(msg){ msg = normalize(msg, keys(this._integrations)); if (msg.anonymousId) user.anonymousId(msg.anonymousId); msg.anonymousId = user.anonymousId(); // Ensure all outgoing requests include page data in their contexts. msg.context.page = defaults(msg.context.page || {}, pageDefaults()); return msg; }; /** * No conflict support. */ Analytics.prototype.noConflict = function(){ window.analytics = _analytics; return this; }; }, {"after":108,"bind":199,"callback":138,"clone":96,"./cookie":200,"debug":195,"defaults":98,"each":4,"emitter":107,"./group":201,"is":93,"is-email":161,"is-meta":202,"new-date":153,"event":203,"./pageDefaults":204,"pick":205,"prevent":206,"querystring":207,"./normalize":208,"object":175,"./memory":209,"./store":210,"./user":211,"facade":139}], 199: [function(require, module, exports) { try { var bind = require('bind'); } catch (e) { var bind = require('bind-component'); } var bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ 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; } }, {"bind":103,"bind-all":104}], 200: [function(require, module, exports) { var debug = require('debug')('analytics.js:cookie'); 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'); /** * Initialize a new `Cookie` with `options`. * * @param {Object} options */ function Cookie (options) { this.options(options); } /** * Get or set the cookie options. * * @param {Object} options * @field {Number} maxage (1 year) * @field {String} domain * @field {String} path * @field {Boolean} secure */ Cookie.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; var domain = '.' + topDomain(window.location.href); if ('.' == domain) domain = null; this._options = defaults(options, { maxage: 31536000000, // default to a year path: '/', domain: domain }); // http://curl.haxx.se/rfc/cookie_spec.html // https://publicsuffix.org/list/effective_tld_names.dat // // try setting a dummy cookie with the options // if the cookie isn't set, it probably means // that the domain is on the public suffix list // like myapp.herokuapp.com or localhost / ip. this.set('ajs:test', true); if (!this.get('ajs:test')) { debug('fallback to domain=null'); this._options.domain = null; } this.remove('ajs:test'); }; /** * Set a `key` and `value` in our cookie. * * @param {String} key * @param {Object} value * @return {Boolean} saved */ Cookie.prototype.set = function (key, value) { try { value = json.stringify(value); cookie(key, value, clone(this._options)); return true; } catch (e) { return false; } }; /** * Get a value from our cookie by `key`. * * @param {String} key * @return {Object} value */ Cookie.prototype.get = function (key) { try { var value = cookie(key); value = value ? json.parse(value) : null; return value; } catch (e) { return null; } }; /** * Remove a value from our cookie by `key`. * * @param {String} key * @return {Boolean} removed */ Cookie.prototype.remove = function (key) { try { cookie(key, null, clone(this._options)); return true; } catch (e) { return false; } }; /** * Expose the cookie singleton. */ module.exports = bind.all(new Cookie()); /** * Expose the `Cookie` constructor. */ module.exports.Cookie = Cookie; }, {"debug":195,"bind":199,"cookie":188,"clone":96,"defaults":98,"json":171,"top-domain":212}], 212: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('url').parse; var cookie = require('cookie'); /** * Expose `domain` */ exports = module.exports = domain; /** * Expose `cookie` for testing. */ exports.cookie = cookie; /** * Get the top domain. * * The function constructs the levels of domain * and attempts to set a global cookie on each one * when it succeeds it returns the top level domain. * * The method returns an empty string when the hostname * is an ip or `localhost`. * * Example levels: * * domain.levels('http://www.google.co.uk'); * // => ["co.uk", "google.co.uk", "www.google.co.uk"] * * Example: * * domain('http://localhost:3000/baz'); * // => '' * domain('http://dev:3000/baz'); * // => '' * domain('http://127.0.0.1:3000/baz'); * // => '' * domain('http://segment.io/baz'); * // => 'segment.io' * * @param {String} url * @return {String} * @api public */ function domain(url){ var cookie = exports.cookie; var levels = exports.levels(url); // Lookup the real top level one. for (var i = 0; i < levels.length; ++i) { var cname = '__tld__'; var domain = levels[i]; var opts = { domain: '.' + domain }; cookie(cname, 1, opts); if (cookie(cname)) { cookie(cname, null, opts); return domain } } return ''; }; /** * Levels returns all levels of the given url. * * @param {String} url * @return {Array} * @api public */ domain.levels = function(url){ var host = parse(url).hostname; var parts = host.split('.'); var last = parts[parts.length-1]; var levels = []; // Ip address. if (4 == parts.length && parseInt(last, 10) == last) { return levels; } // Localhost. if (1 >= parts.length) { return levels; } // Create levels. for (var i = parts.length-2; 0 <= i; --i) { levels.push(parts.slice(i).join('.')); } return levels; }; }, {"url":133,"cookie":213}], 213: [function(require, module, exports) { /** * Module dependencies. */ var debug = require('debug')('cookie'); /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ 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(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ 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.toUTCString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { var str; try { str = document.cookie; } catch (err) { if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(err.stack || err); } return {}; } return parse(str); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ 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; } /** * Encode. */ function encode(value){ try { return encodeURIComponent(value); } catch (e) { debug('error `encode(%o)` - %o', value, e) } } /** * Decode. */ function decode(value) { try { return decodeURIComponent(value); } catch (e) { debug('error `decode(%o)` - %o', value, e) } } }, {"debug":195}], 201: [function(require, module, exports) { var debug = require('debug')('analytics:group'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); /** * Group defaults */ Group.defaults = { persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }; /** * Initialize a new `Group` with `options`. * * @param {Object} options */ function Group (options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(Group, Entity); /** * Expose the group singleton. */ module.exports = bind.all(new Group()); /** * Expose the `Group` constructor. */ module.exports.Group = Group; }, {"debug":195,"./entity":214,"inherit":215,"bind":199}], 214: [function(require, module, exports) { var debug = require('debug')('analytics:entity'); var traverse = require('isodate-traverse'); var defaults = require('defaults'); var memory = require('./memory'); var cookie = require('./cookie'); var store = require('./store'); var extend = require('extend'); var clone = require('clone'); /** * Expose `Entity` */ module.exports = Entity; /** * Initialize new `Entity` with `options`. * * @param {Object} options */ function Entity(options){ this.options(options); this.initialize(); } /** * Initialize picks the storage. * * Checks to see if cookies can be set * otherwise fallsback to localStorage. */ Entity.prototype.initialize = function(){ cookie.set('ajs:cookies', true); // cookies are enabled. if (cookie.get('ajs:cookies')) { cookie.remove('ajs:cookies'); this._storage = cookie; return; } // localStorage is enabled. if (store.enabled) { this._storage = store; return; } // fallback to memory storage. debug('warning using memory store both cookies and localStorage are disabled'); this._storage = memory; }; /** * Get the storage. */ Entity.prototype.storage = function(){ return this._storage; }; /** * Get or set storage `options`. * * @param {Object} options * @property {Object} cookie * @property {Object} localStorage * @property {Boolean} persist (default: `true`) */ Entity.prototype.options = function (options) { if (arguments.length === 0) return this._options; options || (options = {}); defaults(options, this.defaults || {}); this._options = options; }; /** * Get or set the entity's `id`. * * @param {String} id */ Entity.prototype.id = function (id) { switch (arguments.length) { case 0: return this._getId(); case 1: return this._setId(id); } }; /** * Get the entity's id. * * @return {String} */ Entity.prototype._getId = function () { var ret = this._options.persist ? this.storage().get(this._options.cookie.key) : this._id; return ret === undefined ? null : ret; }; /** * Set the entity's `id`. * * @param {String} id */ Entity.prototype._setId = function (id) { if (this._options.persist) { this.storage().set(this._options.cookie.key, id); } else { this._id = id; } }; /** * Get or set the entity's `traits`. * * BACKWARDS COMPATIBILITY: aliased to `properties` * * @param {Object} traits */ Entity.prototype.properties = Entity.prototype.traits = function (traits) { switch (arguments.length) { case 0: return this._getTraits(); case 1: return this._setTraits(traits); } }; /** * Get the entity's traits. Always convert ISO date strings into real dates, * since they aren't parsed back from local storage. * * @return {Object} */ Entity.prototype._getTraits = function () { var ret = this._options.persist ? store.get(this._options.localStorage.key) : this._traits; return ret ? traverse(clone(ret)) : {}; }; /** * Set the entity's `traits`. * * @param {Object} traits */ Entity.prototype._setTraits = function (traits) { traits || (traits = {}); if (this._options.persist) { store.set(this._options.localStorage.key, traits); } else { this._traits = traits; } }; /** * Identify the entity with an `id` and `traits`. If we it's the same entity, * extend the existing `traits` instead of overwriting. * * @param {String} id * @param {Object} 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(); }; /** * Save the entity to local storage and the cookie. * * @return {Boolean} */ 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; }; /** * Log the entity out, reseting `id` and `traits` to defaults. */ Entity.prototype.logout = function () { this.id(null); this.traits({}); cookie.remove(this._options.cookie.key); store.remove(this._options.localStorage.key); }; /** * Reset all entity state, logging out and returning options to defaults. */ Entity.prototype.reset = function () { this.logout(); this.options({}); }; /** * Load saved entity `id` or `traits` from storage. */ Entity.prototype.load = function () { this.id(cookie.get(this._options.cookie.key)); this.traits(store.get(this._options.localStorage.key)); }; }, {"debug":195,"isodate-traverse":149,"defaults":98,"./memory":209,"./cookie":200,"./store":210,"extend":136,"clone":96}], 209: [function(require, module, exports) { /** * Module Dependencies. */ var clone = require('clone'); var bind = require('bind'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `Memory` */ module.exports = bind.all(new Memory); /** * Initialize `Memory` store */ function Memory(){ this.store = {}; } /** * Set a `key` and `value`. * * @param {String} key * @param {Mixed} value * @return {Boolean} */ Memory.prototype.set = function(key, value){ this.store[key] = clone(value); return true; }; /** * Get a `key`. * * @param {String} key */ Memory.prototype.get = function(key){ if (!has.call(this.store, key)) return; return clone(this.store[key]); }; /** * Remove a `key`. * * @param {String} key * @return {Boolean} */ Memory.prototype.remove = function(key){ delete this.store[key]; return true; }; }, {"clone":96,"bind":199}], 210: [function(require, module, exports) { var bind = require('bind'); var defaults = require('defaults'); var store = require('store.js'); /** * Initialize a new `Store` with `options`. * * @param {Object} options */ function Store (options) { this.options(options); } /** * Set the `options` for the store. * * @param {Object} options * @field {Boolean} enabled (true) */ 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; }; /** * Set a `key` and `value` in local storage. * * @param {String} key * @param {Object} value */ Store.prototype.set = function (key, value) { if (!this.enabled) return false; return store.set(key, value); }; /** * Get a value from local storage by `key`. * * @param {String} key * @return {Object} */ Store.prototype.get = function (key) { if (!this.enabled) return null; return store.get(key); }; /** * Remove a value from local storage by `key`. * * @param {String} key */ Store.prototype.remove = function (key) { if (!this.enabled) return false; return store.remove(key); }; /** * Expose the store singleton. */ module.exports = bind.all(new Store()); /** * Expose the `Store` constructor. */ module.exports.Store = Store; }, {"bind":199,"defaults":98,"store.js":216}], 216: [function(require, module, exports) { var json = require('json') , store = {} , win = window , 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 } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 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 // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. 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) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40 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 module.exports = store; }, {"json":171}], 215: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 202: [function(require, module, exports) { module.exports = function isMeta (e) { if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true; // Logic that handles checks for the middle mouse button, based // on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466). 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; }; }, {}], 203: [function(require, module, exports) { /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ if (el.addEventListener) { el.addEventListener(type, fn, capture || false); } else { el.attachEvent('on' + type, fn); } return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ if (el.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else { el.detachEvent('on' + type, fn); } return fn; }; }, {}], 204: [function(require, module, exports) { /** * Module dependencies. */ var canonical = require('canonical'); var url = require('url'); /** * Return a default `options.context.page` object. * * https://segment.com/docs/spec/page/#properties * * @return {Object} */ function pageDefaults() { return { path: canonicalPath(), referrer: document.referrer, search: location.search, title: document.title, url: canonicalUrl(location.search) }; } /** * Return the canonical path for the page. * * @return {String} */ function canonicalPath () { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; } /** * Return the canonical URL for the page concat the given `search` * and strip the hash. * * @param {String} search * @return {String} */ function canonicalUrl (search) { var canon = canonical(); if (canon) return ~canon.indexOf('?') ? canon : canon + search; var url = window.location.href; var i = url.indexOf('#'); return -1 === i ? url : url.slice(0, i); } /** * Exports. */ module.exports = pageDefaults; }, {"canonical":176,"url":178}], 205: [function(require, module, exports) { 'use strict'; var objToString = Object.prototype.toString; // TODO: Move to lib var existy = function(val) { return val != null; }; // TODO: Move to lib var isArray = function(val) { return objToString.call(val) === '[object Array]'; }; // TODO: Move to lib var isString = function(val) { return typeof val === 'string' || objToString.call(val) === '[object String]'; }; // TODO: Move to lib var isObject = function(val) { return val != null && typeof val === 'object'; }; /** * Returns a copy of the new `object` containing only the specified properties. * * @name pick * @api public * @category Object * @see {@link omit} * @param {Array.<string>|string} props The property or properties to keep. * @param {Object} object The object to iterate over. * @return {Object} A new object containing only the specified properties from `object`. * @example * var person = { name: 'Tim', occupation: 'enchanter', fears: 'rabbits' }; * * pick('name', person); * //=> { name: 'Tim' } * * pick(['name', 'fears'], person); * //=> { name: 'Tim', fears: 'rabbits' } */ var pick = function pick(props, object) { if (!existy(object) || !isObject(object)) { return {}; } if (isString(props)) { props = [props]; } if (!isArray(props)) { props = []; } var result = {}; for (var i = 0; i < props.length; i += 1) { if (isString(props[i]) && props[i] in object) { result[props[i]] = object[props[i]]; } } return result; }; /** * Exports. */ module.exports = pick; }, {}], 206: [function(require, module, exports) { /** * prevent default on the given `e`. * * examples: * * anchor.onclick = prevent; * anchor.onclick = function(e){ * if (something) return prevent(e); * }; * * @param {Event} e */ module.exports = function(e){ e = e || window.event return e.preventDefault ? e.preventDefault() : e.returnValue = false; }; }, {}], 207: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":132,"type":7}], 208: [function(require, module, exports) { /** * Module Dependencies. */ var debug = require('debug')('analytics.js:normalize'); var indexof = require('component/indexof'); var defaults = require('defaults'); var map = require('component/map'); var each = require('each'); var is = require('is'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `normalize` */ module.exports = normalize; /** * Toplevel properties. */ var toplevel = [ 'integrations', 'anonymousId', 'timestamp', 'context' ]; /** * Normalize `msg` based on integrations `list`. * * @param {Object} msg * @param {Array} list * @return {Function} */ function normalize(msg, list){ var lower = map(list, function(s){ return s.toLowerCase(); }); var opts = msg.options || {}; var integrations = opts.integrations || {}; var providers = opts.providers || {}; var context = opts.context || {}; var ret = {}; debug('<-', msg); // integrations. each(opts, function(key, value){ if (!integration(key)) return; if (!has.call(integrations, key)) integrations[key] = value; delete opts[key]; }); // providers. delete opts.providers; each(providers, function(key, value){ if (!integration(key)) return; if (is.object(integrations[key])) return; if (has.call(integrations, key) && 'boolean' == typeof providers[key]) return; integrations[key] = value; }); // move all toplevel options to msg // and the rest to context. each(opts, function(key){ if (~indexof(toplevel, key)) { ret[key] = opts[key]; } else { context[key] = opts[key]; } }); // cleanup delete msg.options; ret.integrations = integrations; ret.context = context; ret = defaults(ret, msg); debug('->', ret); return ret; function integration(name){ return !! (~indexof(list, name) || 'all' == name.toLowerCase() || ~indexof(lower, name.toLowerCase())); } } }, {"debug":195,"component/indexof":118,"defaults":98,"component/map":217,"each":4,"is":93}], 217: [function(require, module, exports) { /** * Module dependencies. */ var toFunction = require('to-function'); /** * Map the given `arr` with callback `fn(val, i)`. * * @param {Array} arr * @param {Function} fn * @return {Array} * @api public */ module.exports = function(arr, fn){ var ret = []; fn = toFunction(fn); for (var i = 0; i < arr.length; ++i) { ret.push(fn(arr[i], i)); } return ret; }; }, {"to-function":179}], 211: [function(require, module, exports) { var debug = require('debug')('analytics:user'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); var cookie = require('./cookie'); var uuid = require('uuid'); var rawCookie = require('cookie'); /** * User defaults */ User.defaults = { persist: true, cookie: { key: 'ajs_user_id', oldKey: 'ajs_user' }, localStorage: { key: 'ajs_user_traits' } }; /** * Initialize a new `User` with `options`. * * @param {Object} options */ function User (options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(User, Entity); /** * Set / get the user id. * * When the user id changes, the method will * reset his anonymousId to a new one. * * Example: * * // didn't change because the user didn't have previous id. * anonId = user.anonymousId(); * user.id('foo'); * assert.equal(anonId, user.anonymousId()); * * // didn't change because the user id changed to null. * anonId = user.anonymousId(); * user.id('foo'); * user.id(null); * assert.equal(anonId, user.anonymousId()); * * // change because the user had previous id. * anonId = user.anonymousId(); * user.id('foo'); * user.id('baz'); // triggers change * user.id('baz'); // no change * assert.notEqual(anonId, user.anonymousId()); * * @param {String} id * @return {Mixed} */ User.prototype.id = function(id){ var prev = this._getId(); var ret = Entity.prototype.id.apply(this, arguments); if (null == prev) return ret; if (prev != id && id) this.anonymousId(null); return ret; }; /** * Set / get / remove anonymousId. * * @param {String} anonId * @return {String|User} */ User.prototype.anonymousId = function(anonId){ var store = this.storage(); // set / remove if (arguments.length) { store.set('ajs_anonymous_id', anonId); return this; } // new if (anonId = store.get('ajs_anonymous_id')) { return anonId; } // old - it is not stringified so we use the raw cookie. if (anonId = rawCookie('_sio')) { anonId = anonId.split('----')[0]; store.set('ajs_anonymous_id', anonId); store.remove('_sio'); return anonId; } // empty anonId = uuid(); store.set('ajs_anonymous_id', anonId); return store.get('ajs_anonymous_id'); }; /** * Remove anonymous id on logout too. */ User.prototype.logout = function(){ Entity.prototype.logout.call(this); this.anonymousId(null); }; /** * Load saved user `id` or `traits` from storage. */ User.prototype.load = function () { if (this._loadOldCookie()) return; Entity.prototype.load.call(this); }; /** * BACKWARDS COMPATIBILITY: Load the old user from the cookie. * * @return {Boolean} * @api private */ 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; }; /** * Expose the user singleton. */ module.exports = bind.all(new User()); /** * Expose the `User` constructor. */ module.exports.User = User; }, {"debug":195,"./entity":214,"inherit":215,"bind":199,"./cookie":200,"uuid":189,"cookie":188}], 5: [function(require, module, exports) { module.exports = { "name": "analytics", "version": "2.8.21", "main": "analytics.js", "dependencies": {}, "devDependencies": {} } ; }, {}]}, {}, {"1":""}) );
admin/client/App/screens/Item/components/RelatedItemsList/RelatedItemsList.js
ratecity/keystone
import React from 'react'; import { Link } from 'react-router'; import { Alert, BlankState, Center, Spinner, GlyphButton, ResponsiveText } from '../../../../elemental'; import DragDrop from './RelatedItemsListDragDrop'; import ListRow from './RelatedItemsListRow'; import CreateForm from '../../../../shared/CreateForm'; import { loadRelationshipItemData } from '../../actions'; import { TABLE_CONTROL_COLUMN_WIDTH } from '../../../../../constants'; const RelatedItemsList = React.createClass({ propTypes: { dispatch: React.PropTypes.func.isRequired, dragNewSortOrder: React.PropTypes.number, items: React.PropTypes.array, list: React.PropTypes.object.isRequired, refList: React.PropTypes.object.isRequired, relatedItemId: React.PropTypes.string.isRequired, relationship: React.PropTypes.object.isRequired, }, contextTypes: { router: React.PropTypes.object.isRequired, }, getInitialState () { return { columns: this.getColumns(), err: null, items: null, createIsOpen: false, }; }, componentDidMount () { this.__isMounted = true; this.loadItems(); }, componentWillUnmount () { this.__isMounted = false; }, isSortable () { // Check if the related items should be sortable. The referenced list has to // be sortable and it has to set the current list as it's sortContext. const { refList, list, relationship } = this.props; const sortContext = refList.sortContext; if (refList.sortable && sortContext) { const parts = sortContext.split(':'); if (parts[0] === list.key && parts[1] === relationship.path) { return true; } } return false; }, getColumns () { const { relationship, refList } = this.props; const columns = refList.expandColumns(refList.defaultColumns); return columns.filter(i => i.path !== relationship.refPath); }, loadItems () { const { refList, relatedItemId, relationship } = this.props; const { columns } = this.state; // TODO: Move error to redux store if (!refList.fields[relationship.refPath]) { const err = ( <Alert color="danger"> <strong>Error:</strong> Related List <strong>{refList.label}</strong> has no field <strong>{relationship.refPath}</strong> </Alert> ); return this.setState({ err }); } this.props.dispatch(loadRelationshipItemData({ columns, refList, relatedItemId, relationship })); }, renderItems () { const tableBody = (this.isSortable()) ? ( <DragDrop columns={this.state.columns} items={this.props.items} {...this.props} /> ) : ( <tbody> {this.props.items.results.map((item) => { return (<ListRow key={item.id} columns={this.state.columns} item={item} refList={this.props.refList} />); })} </tbody> ); return this.props.items.results.length ? ( <div className="ItemList-wrapper"> <table cellPadding="0" cellSpacing="0" className="Table ItemList"> {this.renderTableCols()} {this.renderTableHeaders()} {tableBody} </table> </div> ) : ( <BlankState heading={`No related ${this.props.refList.plural.toLowerCase()}...`} style={{ marginBottom: '3em' }} /> ); }, renderTableCols () { const cols = this.state.columns.map((col) => <col width={col.width} key={col.path} />); return <colgroup>{cols}</colgroup>; }, renderTableHeaders () { const cells = this.state.columns.map((col) => { return <th key={col.path}>{col.label}</th>; }); // add sort col when available if (this.isSortable()) { cells.unshift( <th width={TABLE_CONTROL_COLUMN_WIDTH} key="sortable" /> ); } return <thead><tr>{cells}</tr></thead>; }, showCreateForm () { this.setState({createIsOpen: true}) }, hideCreateForm() { this.setState({createIsOpen: false}) }, onCreate (item) { this.setState({createIsOpen: false}) this.loadItems(); }, getCreateValues() { var ret = {} if (this.props.data) { if (this.props.data.fields.company) { Object.assign(ret, {company: this.props.data.fields.company}) } Object.assign(ret, {product: this.props.data.id}) } return ret }, render () { if (this.state.err) { return <div className="Relationship">{this.state.err}</div>; } const listHref = `${Keystone.adminPath}/${this.props.refList.path}`; const loadingElement = ( <Center height={100}> <Spinner /> </Center> ); return ( <div className="Relationship"> <CreateForm list={this.props.refList} isOpen={this.state.createIsOpen} onCancel={this.hideCreateForm} onCreate={this.onCreate} values={this.getCreateValues()} /> <h3 className="Relationship__link"><Link to={listHref}>{this.props.refList.label}</Link></h3> <GlyphButton data-e2e-item-create-button="true" color="success" glyph="plus" position="left" onClick={this.showCreateForm}> <ResponsiveText hiddenXS="Create" visibleXS="Create" /> </GlyphButton> {this.props.items ? this.renderItems() : loadingElement} </div> ); }, }); module.exports = RelatedItemsList;
src/react/appContext.js
luxui/lux-core
/** * @module react/appContext * @memberof react */ import React from 'react'; // `React` must be in scope when using JSX class AppContextContainer extends React.Component { getChildContext() { /** * @typedef {Object} Context * * Application components can optionally recieve a `context` object, as an * instance parameter, for interacting with or manipulating the application * at the top-level in a consistent through the provided methods. The * "context" feature of React is a way to provide this object implicitly to * child components without the need to explicitly "passing down" the * object through all of the layers of components. * * @property {Function} request - perform a root-relative API request; * where the root is prefilled by the value provided at application init. * @property {Function} setState - pass the new state object to change the * current state of the application; state change will incur a re-render. * @property {Object} state - the current state of the application; a copy * of the actual state instead of a reference to the actual state object. * @property {Function} visit - pass an application path to naviate to the * corresponding page; an API request will be made if necessary. * * @example * // define a new application component * function MessageBoard(props, context) { * // ... * } * // "opt-in" to recieve context properties; * // otherwise they will not be provided by React * MessageBoard.contextTypes = { * setState: React.PropTypes.func, * }; */ const context = { request: this.props.app.request, setState: this.props.setState, state: this.props.app.state, visit: this.props.app.visit, }; return context; } render() { return (this.props.children); } } AppContextContainer.childContextTypes = { request: React.PropTypes.func, setState: React.PropTypes.func, state: React.PropTypes.object, visit: React.PropTypes.func, }; AppContextContainer.propTypes = { app: React.PropTypes.shape({ request: React.PropTypes.func, state: React.PropTypes.object, visit: React.PropTypes.func, }).isRequired, children: React.PropTypes.element.isRequired, setState: React.PropTypes.func.isRequired, }; export default AppContextContainer;
ajax/libs/yasqe/2.3.3/yasqe.bundled.min.js
aashish24/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=i[s]={exports:{}};e[s][0].call(p.exports,function(t){var i=e[s][1][t];return n(i?i:t)},p,p.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":30}],2:[function(e){"use strict";var t=e("jquery");t.deparam=function(e,i){var r={},n={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);i&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==n[s]?n[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=i?void 0:"")});return r}},{jquery:15}],3:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,i="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",n=r+"|_",o="("+n+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+n+"|[0-9])("+n+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",f="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+f+")";if("sparql11"==u){e="("+n+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?";t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var E="("+p+")?:",m=E+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",T="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",L="\\+"+x,I="\\+"+N,y="\\+"+T,A="-"+x,S="-"+N,C="-"+T,R="\\\\[tbnrfu\\\\\"']",b="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+")*'",O='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+')*"',P="'''(('|'')?([^'\\\\]|"+R+"))*'''",D='"""(("|"")?([^"\\\\]|'+R+'))*"""',w="[\\x20\\x09\\x0D\\x0A]",_="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",M="("+w+"|("+_+"))*",k="\\("+M+"\\)",G="\\["+M+"\\]",B={terminal:[{name:"WS",regex:new RegExp("^"+w+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+_),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+i),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+g),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+T),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+N),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+y),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+L),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+D),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+b),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+O),style:"string"},{name:"NIL",regex:new RegExp("^"+k),style:"punc"},{name:"ANON",regex:new RegExp("^"+G),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+E),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return B}function i(e){var t=[],i=o[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,i=0;i<f.length;++i){t=e.match(f[i].regex,!0,!1);if(t)return{cat:f[i].name,style:f[i].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function n(){var i=e.column();t.errorStartPos=i;t.errorEndPos=i+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;n()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,h=!1,E=c.cat;t.stack.length>0&&E&&t.OK&&!h;){d=t.stack.pop();if(o[d]){var m=o[d][E];if(void 0!=m&&p(d)){for(var g=m.length-1;g>=0;--g)t.stack.push(m[g]);u(d)}else{t.OK=!1;t.complete=!1;n();t.stack.push(d)}}else if(d==E){h=!0;l(d);for(var v=!0,x=t.stack.length;x>0;--x){var N=o[t.stack[x-1]];N&&N.$||(v=!1)}t.complete=v;if(t.storeProperty&&"punc"!=E.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;n()}}if(!h&&t.OK){t.OK=!1;t.complete=!1;n()}t.possibleCurrent=t.possibleNext;t.possibleNext=i(t.stack[t.stack.length-1]);return c.style}function n(t,i){var r=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=h[t.stack[n]];if(s){r+=s;--n}}for(;n>=0;--n){var s=E[t.stack[n]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),f=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},E={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1}; return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:i(p),possibleNext:i(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:14}],4:[function(e,t){var i=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};i.prototype={insert:function(e,t){if(0!=e.length){var r,n,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new i);n=o.children[r];n.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var i,r,n=this;void 0===t&&(t=0);if(void 0!==n)if(t!==e.length){n.prefixes--;i=e[t];r=n.children[i];r.remove(e,t+1)}else n.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.words;i=e[t];r=n.children[i];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.prefixes;var i=e[t];r=n.children[i];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&n.push(e);for(t in r.children){i=r.children[t];n=n.concat(i.getAllWords(e+t))}return n},autoComplete:function(e,t){var i,r,n=this;if(0==e.length)return void 0===t?n.getAllWords(e):[];void 0===t&&(t=0);i=e[t];r=n.children[i];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],5:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function i(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var i=e.state.fullScreenRestore;t.style.width=i.width;t.style.height=i.height;window.scrollTo(i.scrollLeft,i.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,n,o){o==e.Init&&(o=!1);!o!=!n&&(n?t(r):i(r))})})},{"../../lib/codemirror":14}],6:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var f=e.getLine(d);if(f){var h=i>0?0:f.length-1,E=i>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>i?1:0));for(;h!=E;h+=i){var m=f.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n);if(i){t.state.matchBrackets="object"==typeof i?i:{};t.on("cursorActivity",n)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)});e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":14}],7:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,i){function r(r){for(var n=i.ch,l=0;;){var u=0>=n?-1:a.lastIndexOf(r,n-1);if(-1!=u){if(1==l&&u<i.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;n=u-1}else{if(1==l)break;l=1;n=a.length}}}var n,o,s=i.line,a=t.getLine(s),l="{",u="}",n=r("{");if(null==n){l="[",u="]";n=r("[")}if(null!=n){var p,c,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var E=t.getLine(h),m=h==s?n:0;;){var g=E.indexOf(l,m),v=E.indexOf(u,m);0>g&&(g=E.length);0>v&&(v=E.length);m=Math.min(g,v);if(m==E.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==g)++d;else if(!--d){p=h;c=m;break e}++m}if(null!=p&&(s!=p||c!=n))return{from:e.Pos(s,n),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var n=i,o=Math.min(t.lastLine(),i+10);o>=n;++n){var s=t.getLine(n),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(n,a)}}}var n,i=i.line,o=r(i);if(!o||r(i-1)||(n=r(i-2))&&n.end.line==i-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(i,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var i=i.line,n=r(i);if(null==n||null!=r(i-1))return null;for(var o=i;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(i,n+1),to:t.clipPos(e.Pos(o))}})})},{"../../lib/codemirror":14}],8:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(t,n,o,s){function a(e){var i=l(t,n);if(!i||i.to.line-i.from.line<u)return null;for(var r=t.findMarksAt(i.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;i.cleared=!0;r[o].clear()}return i}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof n&&(n=e.Pos(n,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&n.line>t.firstLine();){n=e.Pos(n.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=i(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(i,r){e.signal(t,"unfold",t,i,r)});e.signal(t,"fold",t,p.from,p.to)}}function i(e,t){var i=r(e,t,"widget");if("string"==typeof i){var n=document.createTextNode(i);i=document.createElement("span");i.appendChild(n);i.className="CodeMirror-foldmarker"}return i}function r(e,t,i){if(t&&void 0!==t[i])return t[i];var r=e.options.foldOptions;return r&&void 0!==r[i]?r[i]:n[i]}e.newFoldFunction=function(e,i){return function(r,n){t(r,n,{rangeFinder:e,widget:i})}};e.defineExtension("foldCode",function(e,i,r){t(this,e,i,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),i=0;i<t.length;++i)if(t[i].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,i){for(var r=0;r<e.length;++r){var n=e[r](t,i);if(n)return n}}});e.registerHelper("fold","auto",function(e,t){for(var i=e.getHelpers(t,"fold"),r=0;r<i.length;r++){var n=i[r](e,t);if(n)return n}});var n={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{"../../lib/codemirror":14}],9:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror"),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],n):n(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function i(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var i=e.findMarksAt(c(t)),r=0;r<i.length;++r)if(i[r].__isFold&&i[r].find().from.line==t)return!0}function n(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,i){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,i,function(t){var i=null;if(r(e,s))i=n(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(i=n(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,i);++s})}function s(e){var t=e.getViewport(),i=e.state.foldGutter;if(i){e.operation(function(){o(e,t.from,t.to)});i.from=t.from;i.to=t.to}}function a(e,t,i){var r=e.state.foldGutter.options;i==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},i.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var i=e.getViewport();t.from==t.to||i.from-t.to>20||t.from-i.to>20?s(e):e.operation(function(){if(i.from<t.from){o(e,i.from,t.from);t.from=i.from}if(i.to>t.to){o(e,t.to,i.to);t.to=i.to}})},i.updateViewportTimeSpan||400)}function p(e,t){var i=e.state.foldGutter,r=t.line;r>=i.from&&r<i.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,n,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(n){r.state.foldGutter=new t(i(n));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"../../lib/codemirror":14,"./foldcode":8}],10:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function i(e,t,i,r){this.line=t;this.ch=i;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var i=e.cm.getTokenTypeAt(d(e.line,t));return i&&/\btag\b/.test(i)}function n(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(n(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),o=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){E.lastIndex=t;e.ch=t;var i=E.exec(e.text);if(i&&i.index==t)return i}else e.ch=t}}function l(e){for(;;){E.lastIndex=e.ch;var t=E.exec(e.text);if(!t){if(n(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),n=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return n?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var i=[];;){var r,n=l(e),o=e.line,a=e.ch-(n?n[0].length:0);if(!n||!(r=s(e)))return;if("selfClose"!=r)if(n[1]){for(var u=i.length-1;u>=0;--u)if(i[u]==n[2]){i.length=u;break}if(0>u&&(!t||t==n[2]))return{tag:n[2],from:d(o,a),to:d(e.line,e.ch)}}else i.push(n[2])}}function c(e,t){for(var i=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var n=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])i.push(s[2]);else{for(var l=i.length-1;l>=0;--l)if(i[l]==s[2]){i.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(n,o)}}}else a(e)}}var d=e.Pos,f="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",E=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new i(e,t.line,0);;){var n,o=l(r);if(!o||r.line!=t.line||!(n=s(r)))return;if(!o[1]&&"selfClose"!=n){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,n){var o=new i(e,r.line,r.ch,n);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:c(o,f[2]),close:h,at:"close"};o=new i(e,u.line,u.ch,n);return{open:h,close:p(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var n=new i(e,t.line,t.ch,r);;){var o=c(n);if(!o)break;var s=new i(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,n){var o=new i(e,t.line,t.ch,n?{from:0,to:n}:null);return p(o,r)}})},{"../../lib/codemirror":14}],11:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i;o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var f=p.appendChild(document.createElement("li")),h=c[d],E=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(E=h.className+" "+E);f.className=E;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||i(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px";p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),T=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var L=p.getBoundingClientRect(),I=L.bottom-T;if(I>0){var y=L.bottom-L.top,A=m.top-(m.bottom-L.top);if(A-y>0){p.style.top=(v=m.top-y)+"px";x=!1}else if(y>T){p.style.height=T-5+"px";p.style.top=(v=m.bottom-L.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(g=m.left)+"px";L=p.getBoundingClientRect()}}}var C=L.right-N;if(C>0){if(L.right-L.left>N){p.style.width=N-5+"px";C-=L.right-L.left-N}p.style.left=(g=m.left-C)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(n+=p.offsetHeight);if(n<=i.top||n>=i.bottom)return t.close();p.style.top=r+"px";p.style.left=g+b.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);if(i&&null!=i.hintId){l.changeActive(i.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)};e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n){e.signal(this,"startCompletion",this);if(!n.async)return r.showHints(n(this,r.options));n(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete");e.signal(t,"pick",n);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function i(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){t=e;if(!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){E(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=h(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},E=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)});e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":14}],12:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r);p+=e.length-r;break}p+=n-r;i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),f=0,h=c.length;h>f;++f){f&&r("\n");var E=new e.StringStream(c[f]);!E.string&&o.blankLine&&o.blankLine(d);for(;!E.eol();){var m=o.token(E,d);r(E.current(),m,f,E.start,d);E.start=E.pos}}}})},{"../../lib/codemirror":14}],13:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t,n,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);n=n?e.clipPos(n):r(0,0);this.pos={from:n,to:n};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=i(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=i(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var f=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[n].length))==l[n])return{from:f,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);i.pos={from:t,to:t};i.atOccurrence=!1;return!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)});e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)});e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":14}],14:[function(t,i,r){(function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}})(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r?yo(r):{};yo(Us,r,!1);f(r);var n=r.value;"string"==typeof n&&(n=new ua(n,r.mode));this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this;u(this);a(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!Es&&Oi(this);g(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new go,keySeq:null};ns&&11>os&&setTimeout(Ao(bi,this,!0),20);wi(this);Go();ni(this);this.curOp.forceUpdate=!0;Gn(this,n);r.autofocus&&!Es||wo()==o.input?setTimeout(Ao(rr,this),20):nr(this);for(var s in Vs)Vs.hasOwnProperty(s)&&Vs[s](this,r[s],Fs);L(this);for(var l=0;l<qs.length;++l)qs[l](this);si(this);ss&&r.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}function t(e,t){var i=this,r=i.input=bo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ss?r.style.width="1000px":r.setAttribute("wrap","off");hs&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");i.inputDiv=bo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");i.scrollbarFiller=bo("div",null,"CodeMirror-scrollbar-filler");i.scrollbarFiller.setAttribute("not-content","true");i.gutterFiller=bo("div",null,"CodeMirror-gutter-filler");i.gutterFiller.setAttribute("not-content","true");i.lineDiv=bo("div",null,"CodeMirror-code");i.selectionDiv=bo("div",null,null,"position: relative; z-index: 1");i.cursorDiv=bo("div",null,"CodeMirror-cursors");i.measure=bo("div",null,"CodeMirror-measure");i.lineMeasure=bo("div",null,"CodeMirror-measure");i.lineSpace=bo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");i.mover=bo("div",[bo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative");i.sizer=bo("div",[i.mover],"CodeMirror-sizer");i.sizerWidth=null;i.heightForcer=bo("div",null,null,"position: absolute; height: "+xa+"px; width: 1px;");i.gutters=bo("div",null,"CodeMirror-gutters");i.lineGutter=null;i.scroller=bo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll");i.scroller.setAttribute("tabIndex","-1");i.wrapper=bo("div",[i.inputDiv,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror");if(ns&&8>os){i.gutters.style.zIndex=-1;i.scroller.style.paddingRight=0}hs&&(r.style.width="0px");ss||(i.scroller.draggable=!0);if(cs){i.inputDiv.style.height="1px";i.inputDiv.style.position="absolute"}e&&(e.appendChild?e.appendChild(i.wrapper):e(i.wrapper));i.viewFrom=i.viewTo=t.first;i.reportedViewFrom=i.reportedViewTo=t.first;i.view=[];i.renderedView=null;i.externalMeasured=null;i.viewOffset=0;i.lastWrapHeight=i.lastWrapWidth=0;i.updateLineNumbers=null;i.nativeBarWidth=i.barHeight=i.barWidth=0;i.scrollbarsClipped=!1;i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null;i.prevInput="";i.alignWidgets=!1;i.pollingFast=!1;i.poll=new go;i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null;i.inaccurateSelection=!1;i.maxLine=null;i.maxLineLength=0;i.maxLineChanged=!1;i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null;i.shift=!1;i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption);r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null)});e.doc.frontier=e.doc.first;yt(e,100);e.state.modeGen++;e.curOp&&xi(e)}function n(e){if(e.options.lineWrapping){_a(e.display.wrapper,"CodeMirror-wrap");e.display.sizer.style.minWidth="";e.display.sizerWidth=null}else{wa(e.display.wrapper,"CodeMirror-wrap");d(e)}s(e);xi(e);qt(e);setTimeout(function(){v(e)},100)}function o(e){var t=ii(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/ri(e.display)-3);return function(n){if(un(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&Fn(e,t)})}function a(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-");qt(e)}function l(e){u(e);xi(e);setTimeout(function(){T(e) },20)}function u(e){var t=e.display.gutters,i=e.options.gutters;Oo(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(bo("div",null,"CodeMirror-gutter "+n));if("CodeMirror-linenumbers"==n){e.display.lineGutter=o;o.style.width=(e.display.lineNumWidth||1)+"px"}}t.style.display=r?"":"none";p(e)}function p(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function c(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=tn(r);){var n=t.find(0,!0);r=n.from.line;i+=n.from.ch-n.to.ch}r=e;for(;t=rn(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch;r=n.to.line;i+=r.text.length-n.to.ch}return i}function d(e){var t=e.display,i=e.doc;t.maxLine=Bn(i,i.first);t.maxLineLength=c(t.maxLine);t.maxLineChanged=!0;i.iter(function(e){var i=c(e);if(i>t.maxLineLength){t.maxLineLength=i;t.maxLine=e}})}function f(e){var t=To(e.gutters,"CodeMirror-linenumbers");if(-1==t&&e.lineNumbers)e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]);else if(t>-1&&!e.lineNumbers){e.gutters=e.gutters.slice(0);e.gutters.splice(t,1)}}function h(e){var t=e.display,i=t.gutters.offsetWidth,r=Math.round(e.doc.height+bt(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?i:0,docHeight:r,scrollHeight:r+Pt(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:i}}function E(e,t,i){this.cm=i;var r=this.vert=bo("div",[bo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n=this.horiz=bo("div",[bo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(r);e(n);Ea(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")});Ea(n,"scroll",function(){n.clientWidth&&t(n.scrollLeft,"horizontal")});this.checkedOverlay=!1;ns&&8>os&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function m(){}function g(t){if(t.display.scrollbars){t.display.scrollbars.clear();t.display.scrollbars.addClass&&wa(t.display.wrapper,t.display.scrollbars.addClass)}t.display.scrollbars=new e.scrollbarModel[t.options.scrollbarStyle](function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller);Ea(e,"mousedown",function(){t.state.focused&&setTimeout(Ao(Oi,t),0)});e.setAttribute("not-content","true")},function(e,i){"horizontal"==i?zi(t,e):qi(t,e)},t);t.display.scrollbars.addClass&&_a(t.display.wrapper,t.display.scrollbars.addClass)}function v(e,t){t||(t=h(e));var i=e.display.barWidth,r=e.display.barHeight;x(e,t);for(var n=0;4>n&&i!=e.display.barWidth||r!=e.display.barHeight;n++){i!=e.display.barWidth&&e.options.lineWrapping&&P(e);x(e,h(e));i=e.display.barWidth;r=e.display.barHeight}}function x(e,t){var i=e.display,r=i.scrollbars.update(t);i.sizer.style.paddingRight=(i.barWidth=r.right)+"px";i.sizer.style.paddingBottom=(i.barHeight=r.bottom)+"px";if(r.right&&r.bottom){i.scrollbarFiller.style.display="block";i.scrollbarFiller.style.height=r.bottom+"px";i.scrollbarFiller.style.width=r.right+"px"}else i.scrollbarFiller.style.display="";if(r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter){i.gutterFiller.style.display="block";i.gutterFiller.style.height=r.bottom+"px";i.gutterFiller.style.width=t.gutterWidth+"px"}else i.gutterFiller.style.display=""}function N(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-Rt(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=jn(t,r),s=jn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a){o=a;s=jn(t,Wn(Bn(t,a))+e.wrapper.clientHeight)}else if(Math.min(l,t.lastLine())>=s){o=jn(t,Wn(Bn(t,l))-e.wrapper.clientHeight);s=l}}return{from:o,to:Math.max(s,o+1)}}function T(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=y(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function L(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=I(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(bo("div",[bo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s);r.lineNumWidth=r.lineNumInnerWidth+s;r.lineNumChars=r.lineNumInnerWidth?i.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";p(e);return!0}return!1}function I(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function y(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function A(e,t,i){var r=e.display;this.viewport=t;this.visible=N(r,e.doc,t);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldDisplayWidth=Dt(e);this.force=i;this.dims=w(e)}function S(e){var t=e.display;if(!t.scrollbarsClipped&&t.scroller.offsetWidth){t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth;t.heightForcer.style.height=Pt(e)+"px";t.sizer.style.marginBottom=-t.nativeBarWidth+"px";t.sizer.style.borderRightWidth=Pt(e)+"px";t.scrollbarsClipped=!0}}function C(e,t){var i=e.display,r=e.doc;if(t.editorIsHidden){Ti(e);return!1}if(!t.force&&t.visible.from>=i.viewFrom&&t.visible.to<=i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo)&&i.renderedView==i.view&&0==Ai(e))return!1;if(L(e)){Ti(e);t.dims=w(e)}var n=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),s=Math.min(n,t.visible.to+e.options.viewportMargin);i.viewFrom<o&&o-i.viewFrom<20&&(o=Math.max(r.first,i.viewFrom));i.viewTo>s&&i.viewTo-s<20&&(s=Math.min(n,i.viewTo));if(Ls){o=an(e.doc,o);s=ln(e.doc,s)}var a=o!=i.viewFrom||s!=i.viewTo||i.lastWrapHeight!=t.wrapperHeight||i.lastWrapWidth!=t.wrapperWidth;yi(e,o,s);i.viewOffset=Wn(Bn(e.doc,i.viewFrom));e.display.mover.style.top=i.viewOffset+"px";var l=Ai(e);if(!a&&0==l&&!t.force&&i.renderedView==i.view&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo))return!1;var u=wo();l>4&&(i.lineDiv.style.display="none");_(e,i.updateLineNumbers,t.dims);l>4&&(i.lineDiv.style.display="");i.renderedView=i.view;u&&wo()!=u&&u.offsetHeight&&u.focus();Oo(i.cursorDiv);Oo(i.selectionDiv);i.gutters.style.height=0;if(a){i.lastWrapHeight=t.wrapperHeight;i.lastWrapWidth=t.wrapperWidth;yt(e,400)}i.updateLineNumbers=null;return!0}function R(e,t){for(var i=t.force,r=t.viewport,n=!0;;n=!1){if(n&&e.options.lineWrapping&&t.oldDisplayWidth!=Dt(e))i=!0;else{i=!1;r&&null!=r.top&&(r={top:Math.min(e.doc.height+bt(e.display)-wt(e),r.top)});t.visible=N(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!C(e,t))break;P(e);var o=h(e);Nt(e);O(e,o);v(e,o)}po(e,"update",e);if(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo){po(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo);e.display.reportedViewFrom=e.display.viewFrom;e.display.reportedViewTo=e.display.viewTo}}function b(e,t){var i=new A(e,t);if(C(e,i)){P(e);R(e,i);var r=h(e);Nt(e);O(e,r);v(e,r)}}function O(e,t){e.display.sizer.style.minHeight=t.docHeight+"px";var i=t.docHeight+e.display.barHeight;e.display.heightForcer.style.top=i+"px";e.display.gutters.style.height=Math.max(i+Pt(e),t.clientHeight)+"px"}function P(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(ns&&8>os){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i;i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;2>n&&(n=ii(t));if(l>.001||-.001>l){Fn(o.line,n);D(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)D(o.rest[u])}}}}function D(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function w(e){for(var t=e.display,i={},r={},n=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s){i[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+n;r[e.options.gutters[s]]=o.clientWidth}return{fixedPos:y(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function _(e,t,i){function r(t){var i=t.nextSibling;ss&&ms&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t);return i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;if(c.changes){To(c.changes,"gutter")>-1&&(d=!1);M(e,c,u,i)}if(d){Oo(c.lineNumber);c.lineNumber.appendChild(document.createTextNode(I(e.options,u)))}a=c.node.nextSibling}else{var f=j(e,c,u,i);s.insertBefore(f,a)}u+=c.size}for(;a;)a=r(a)}function M(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?U(e,t):"gutter"==o?F(e,t,i,r):"class"==o?V(t):"widget"==o&&H(t,r)}t.changes=null}function k(e){if(e.node==e.text){e.node=bo("div",null,null,"position: relative");e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text);e.node.appendChild(e.text);ns&&8>os&&(e.node.style.zIndex=2)}return e.node}function G(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;t&&(t+=" CodeMirror-linebackground");if(e.background)if(t)e.background.className=t;else{e.background.parentNode.removeChild(e.background);e.background=null}else if(t){var i=k(e);e.background=i.insertBefore(bo("div",null,t),i.firstChild)}}function B(e,t){var i=e.display.externalMeasured;if(i&&i.line==t.line){e.display.externalMeasured=null;t.measure=i.measure;return i.built}return An(e,t)}function U(e,t){var i=t.text.className,r=B(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text);t.text=r.pre;if(r.bgClass!=t.bgClass||r.textClass!=t.textClass){t.bgClass=r.bgClass;t.textClass=r.textClass;V(t)}else i&&(t.text.className=i)}function V(e){G(e);e.line.wrapClass?k(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,i,r){if(t.gutter){t.node.removeChild(t.gutter);t.gutter=null}var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=k(t),s=t.gutter=o.insertBefore(bo("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),t.text);t.line.gutterClass&&(s.className+=" "+t.line.gutterClass);!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(bo("div",I(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px")));if(n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(bo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function H(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}W(e,t)}function j(e,t,i,r){var n=B(e,t);t.text=t.node=n.pre;n.bgClass&&(t.bgClass=n.bgClass);n.textClass&&(t.textClass=n.textClass);V(t);F(e,t,i,r);W(t,r);return t.node}function W(e,t){q(e.line,e,t,!0);if(e.rest)for(var i=0;i<e.rest.length;i++)q(e.rest[i],e,t,!1)}function q(e,t,i,r){if(e.widgets)for(var n=k(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=bo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||l.setAttribute("cm-ignore-events","true");z(a,l,t,i);r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l);po(a,"redraw")}}function z(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px";if(!e.coverGutter){n-=r.gutterTotalWidth;t.style.paddingLeft=r.gutterTotalWidth+"px"}t.style.width=n+"px"}if(e.coverGutter){t.style.zIndex=5;t.style.position="relative";e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px")}}function X(e){return Is(e.line,e.ch)}function Y(e,t){return ys(e,t)<0?t:e}function K(e,t){return ys(e,t)<0?e:t}function $(e,t){this.ranges=e;this.primIndex=t}function Q(e,t){this.anchor=e;this.head=t}function Z(e,t){var i=e[t];e.sort(function(e,t){return ys(e.from(),t.from())});t=To(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ys(o.to(),n.from())>=0){var s=K(o.from(),n.from()),a=Y(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t;e.splice(--r,2,new Q(l?a:s,l?s:a))}}return new $(e,t)}function J(e,t){return new $([new Q(e,t||e)],0)}function et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function tt(e,t){if(t.line<e.first)return Is(e.first,0);var i=e.first+e.size-1;return t.line>i?Is(i,Bn(e,i).text.length):it(t,Bn(e,t.line).text.length)}function it(e,t){var i=e.ch;return null==i||i>t?Is(e.line,t):0>i?Is(e.line,0):e}function rt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=tt(e,t[r]);return i}function ot(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ys(i,n)<0;if(o!=ys(r,n)<0){n=i;i=r}else o!=ys(i,r)<0&&(i=r)}return new Q(n,i)}return new Q(r||i,i)}function st(e,t,i,r){dt(e,new $([ot(e,e.sel.primary(),t,i)],0),r)}function at(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=ot(e,e.sel.ranges[n],t[n],null);var o=Z(r,e.sel.primIndex);dt(e,o,i)}function lt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i;dt(e,Z(n,e.sel.primIndex),r)}function ut(e,t,i,r){dt(e,J(t,i),r)}function pt(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new Q(tt(e,t[i].anchor),tt(e,t[i].head))}};ga(e,"beforeSelectionChange",e,i);e.cm&&ga(e.cm,"beforeSelectionChange",e.cm,i);return i.ranges!=t.ranges?Z(i.ranges,i.ranges.length-1):t}function ct(e,t,i){var r=e.history.done,n=No(r);if(n&&n.ranges){r[r.length-1]=t;ft(e,t,i)}else dt(e,t,i)}function dt(e,t,i){ft(e,t,i);Zn(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ft(e,t,i){(Eo(e,"beforeSelectionChange")||e.cm&&Eo(e.cm,"beforeSelectionChange"))&&(t=pt(e,t));var r=i&&i.bias||(ys(t.primary().head,e.sel.primary().head)<0?-1:1);ht(e,mt(e,t,r,!0));i&&i.scroll===!1||!e.cm||yr(e.cm)}function ht(e,t){if(!t.equals(e.sel)){e.sel=t;if(e.cm){e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0;ho(e.cm)}po(e,"cursorActivity",e)}}function Et(e){ht(e,mt(e,e.sel,null,!1),Ta)}function mt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=gt(e,s.anchor,i,r),l=gt(e,s.head,i,r);if(n||a!=s.anchor||l!=s.head){n||(n=t.ranges.slice(0,o));n[o]=new Q(a,l)}}return n?Z(n,t.primIndex):t}function gt(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=Bn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){ga(p,"beforeCursorEnter");if(p.explicitlyCleared){if(a.markedSpans){--l;continue}break}}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ys(c,o)){c.ch+=s;c.ch<0?c=c.line>e.first?tt(e,Is(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?Is(c.line+1,0):null);if(!c){if(n){if(!r)return gt(e,t,i,!0);e.cantEdit=!0;return Is(e.first,0)}n=!0;c=t;s=-s}}o=c;continue e}}return o}}function vt(e){for(var t=e.display,i=e.doc,r={},n=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),s=0;s<i.sel.ranges.length;s++){var a=i.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&Tt(e,a,n);l||Lt(e,a,o)}if(e.options.moveInputWithCursor){var u=Qt(e,i.sel.primary().head,"div"),p=t.wrapper.getBoundingClientRect(),c=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+c.top-p.top));r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+c.left-p.left))}return r}function xt(e,t){Po(e.display.cursorDiv,t.cursors);Po(e.display.selectionDiv,t.selection);if(null!=t.teTop){e.display.inputDiv.style.top=t.teTop+"px";e.display.inputDiv.style.left=t.teLeft+"px"}}function Nt(e){xt(e,vt(e))}function Tt(e,t,i){var r=Qt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),n=i.appendChild(bo("div"," ","CodeMirror-cursor"));n.style.left=r.left+"px";n.style.top=r.top+"px";n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px";if(r.other){var o=i.appendChild(bo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function Lt(e,t,i){function r(e,t,i,r){0>t&&(t=0);t=Math.round(t);r=Math.round(r);a.appendChild(bo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return $t(e,Is(t,i),"div",c,r)}var a,l,c=Bn(s,t),d=c.text.length;Ho(qn(c),i||0,null==n?d:n,function(e,t,s){var c,f,h,E=o(e,"left");if(e==t){c=E;f=h=E.left}else{c=o(t-1,"right");if("rtl"==s){var m=E;E=c;c=m}f=E.left;h=c.right}null==i&&0==e&&(f=u);if(c.top-E.top>3){r(f,E.top,null,E.bottom);f=u;E.bottom<c.top&&r(f,E.bottom,null,c.top)}null==n&&t==d&&(h=p);(!a||E.top<a.top||E.top==a.top&&E.left<a.left)&&(a=E);(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c);u+1>f&&(f=u);r(f,c.top,h-f,c.bottom)});return{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Ot(e.display),u=l.left,p=Math.max(o.sizerWidth,Dt(e)-o.sizer.offsetLeft)-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var f=Bn(s,c.line),h=Bn(s,d.line),E=on(f)==on(h),m=n(c.line,c.ch,E?f.text.length+1:null).end,g=n(d.line,E?0:null,d.ch).start;if(E)if(m.top<g.top-2){r(m.right,m.top,null,m.bottom);r(u,g.top,g.left,g.bottom)}else r(m.right,m.top,g.left-m.right,m.bottom);m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function It(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="";e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function yt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,Ao(At,e))}function At(e){var t=e.doc;t.frontier<t.first&&(t.frontier=t.first);if(!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Xs(t.mode,Ct(e,t.frontier)),n=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var s=o.styles,a=Tn(e,o,r,!0);o.styles=a.styles;var l=o.styleClasses,u=a.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var p=!s||s.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),c=0;!p&&c<s.length;++c)p=s[c]!=o.styles[c];p&&n.push(t.frontier);o.stateAfter=Xs(t.mode,r)}else{In(e,o.text,r);o.stateAfter=t.frontier%5==0?Xs(t.mode,r):null}++t.frontier;if(+new Date>i){yt(e,e.options.workDelay);return!0}});n.length&&fi(e,function(){for(var t=0;t<n.length;t++)Ni(e,n[t],"text")})}}function St(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=Bn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=ya(l.text,null,e.options.tabSize);if(null==n||r>u){n=a-1;r=u}}return n}function Ct(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=St(e,t,i),s=o>r.first&&Bn(r,o-1).stateAfter;s=s?Xs(r.mode,s):Ys(r.mode);r.iter(o,t,function(i){In(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Xs(r.mode,s):null;++o});i&&(r.frontier=o);return s}function Rt(e){return e.lineSpace.offsetTop}function bt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Ot(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Po(e.measure,bo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r);return r}function Pt(e){return xa-e.display.nativeBarWidth}function Dt(e){return e.display.scroller.clientWidth-Pt(e)-e.display.barWidth}function wt(e){return e.display.scroller.clientHeight-Pt(e)-e.display.barHeight}function _t(e,t,i){var r=e.options.lineWrapping,n=r&&Dt(e);if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function Mt(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Hn(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function kt(e,t){t=on(t);var i=Hn(t),r=e.display.externalMeasured=new gi(e.doc,t,i);r.lineN=i;var n=r.built=An(e,r);r.text=n.pre;Po(e.display.lineMeasure,n.pre);return r}function Gt(e,t,i,r){return Vt(e,Ut(e,t),i,r)}function Bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[Li(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ut(e,t){var i=Hn(t),r=Bt(e,i);r&&!r.text?r=null:r&&r.changes&&M(e,r,i,w(e));r||(r=kt(e,t));var n=Mt(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Vt(e,t,i,r,n){t.before&&(i=-1);var o,s=i+(r||"");if(t.cache.hasOwnProperty(s))o=t.cache[s];else{t.rect||(t.rect=t.view.text.getBoundingClientRect());if(!t.hasHeights){_t(e,t.view,t.rect);t.hasHeights=!0}o=Ft(e,t,i,r);o.bogus||(t.cache[s]=o)}return{left:o.left,right:o.right,top:n?o.rtop:o.top,bottom:n?o.rbottom:o.bottom}}function Ft(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i){o=0;s=1;a="left"}else if(c>i){o=i-p;s=o+1}else if(u==l.length-3||i==c&&l[u+3]>i){s=c-p;o=s-1;i>=c&&(a="right")}if(null!=o){n=l[u+2];p==c&&r==(n.insertLeft?"left":"right")&&(a=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){n=l[(u-=3)+2];a="left"}if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){n=l[(u+=3)+2];a="right"}break}}var d;if(3==n.nodeType){for(var u=0;4>u;u++){for(;o&&Ro(t.line.text.charAt(p+o));)--o;for(;c>p+s&&Ro(t.line.text.charAt(p+s));)++s;if(ns&&9>os&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(ns&&e.options.lineWrapping){var f=Ca(n,o,s).getClientRects();d=f.length?f["right"==r?f.length-1:0]:Rs}else d=Ca(n,o,s).getBoundingClientRect()||Rs;if(d.left||d.right||0==o)break;s=o;o-=1;a="right"}ns&&11>os&&(d=Ht(e.display.measure,d))}else{o>0&&(a=r="right");var f;d=e.options.lineWrapping&&(f=n.getClientRects()).length>1?f["right"==r?f.length-1:0]:n.getBoundingClientRect()}if(ns&&9>os&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+ri(e.display),top:h.top,bottom:h.bottom}:Rs}for(var E=d.top-t.rect.top,m=d.bottom-t.rect.top,g=(E+m)/2,v=t.view.measure.heights,u=0;u<v.length-1&&!(g<v[u]);u++);var x=u?v[u-1]:0,N=v[u],T={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:x,bottom:N};d.left||d.right||(T.bogus=!0);if(!e.options.singleCursorHeightPerLine){T.rtop=E;T.rbottom=m}return T}function Ht(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Fo(e))return t;var i=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*i,right:t.right*i,top:t.top*r,bottom:t.bottom*r}}function jt(e){if(e.measure){e.measure.cache={};e.measure.heights=null;if(e.rest)for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}}function Wt(e){e.display.externalMeasure=null;Oo(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)jt(e.display.view[t])}function qt(e){Wt(e);e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null;e.options.lineWrapping||(e.display.maxLineChanged=!0);e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Xt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Yt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=dn(t.widgets[n]);i.top+=o;i.bottom+=o}if("line"==r)return i;r||(r="local");var s=Wn(t);"local"==r?s+=Rt(e.display):s-=e.display.viewOffset;if("page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:Xt());var l=a.left+("window"==r?0:zt());i.left+=l;i.right+=l}i.top+=s;i.bottom+=s;return i}function Kt(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i){r-=zt();n-=Xt()}else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left;n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function $t(e,t,i,r,n){r||(r=Bn(e.doc,t.line));return Yt(e,r,Gt(e,r,t.ch,n),i)}function Qt(e,t,i,r,n,o){function s(t,s){var a=Vt(e,n,t,s?"right":"left",o);s?a.left=a.right:a.right=a.left;return Yt(e,r,a,i)}function a(e,t){var i=l[t],r=i.level%2;if(e==jo(i)&&t&&i.level<l[t-1].level){i=l[--t];e=Wo(i)-(i.level%2?0:1);r=!0}else if(e==Wo(i)&&t<l.length-1&&i.level<l[t+1].level){i=l[++t];e=jo(i)-i.level%2;r=!1}return r&&e==i.to&&e>i.from?s(e-1):s(e,r)}r=r||Bn(e.doc,t.line);n||(n=Ut(e,r));var l=qn(r),u=t.ch;if(!l)return s(u);var p=Qo(l,u),c=a(u,p);null!=Ha&&(c.other=a(u,Ha));return c}function Zt(e,t){var i=0,t=tt(e.doc,t);e.options.lineWrapping||(i=ri(e.display)*t.ch);var r=Bn(e.doc,t.line),n=Wn(r)+Rt(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function Jt(e,t,i,r){var n=Is(e,t);n.xRel=r;i&&(n.outside=!0);return n}function ei(e,t,i){var r=e.doc;i+=e.display.viewOffset;if(0>i)return Jt(r.first,0,!0,-1);var n=jn(r,i),o=r.first+r.size-1;if(n>o)return Jt(r.first+r.size-1,Bn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=Bn(r,n);;){var a=ti(e,s,n,t,i),l=rn(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=Hn(s=u.to.line)}}function ti(e,t,i,r,n){function o(r){var n=Qt(e,Is(i,r),"line",t,u);a=!0;if(s>n.bottom)return n.left-l;if(s<n.top)return n.left+l;a=!1;return n.left}var s=n-Wn(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ut(e,t),p=qn(t),c=t.text.length,d=qo(t),f=zo(t),h=o(d),E=a,m=o(f),g=a;if(r>m)return Jt(i,f,g,1);for(;;){if(p?f==d||f==Jo(t,d,1):1>=f-d){for(var v=h>r||m-r>=r-h?d:f,x=r-(v==d?h:m);Ro(t.text.charAt(v));)++v;var N=Jt(i,v,v==d?E:g,-1>x?-1:x>1?1:0);return N}var T=Math.ceil(c/2),L=d+T;if(p){L=d;for(var I=0;T>I;++I)L=Jo(t,L,1)}var y=o(L);if(y>r){f=L;m=y;(g=a)&&(m+=1e3);c=T}else{d=L;h=y;E=a;c-=T}}}function ii(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==As){As=bo("pre");for(var t=0;49>t;++t){As.appendChild(document.createTextNode("x"));As.appendChild(bo("br"))}As.appendChild(document.createTextNode("x"))}Po(e.measure,As);var i=As.offsetHeight/50;i>3&&(e.cachedTextHeight=i);Oo(e.measure);return i||1}function ri(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=bo("span","xxxxxxxxxx"),i=bo("pre",[t]);Po(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;n>2&&(e.cachedCharWidth=n);return n||10}function ni(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Os};bs?bs.ops.push(e.curOp):e.curOp.ownsGroup=bs={ops:[e.curOp],delayedCallbacks:[]}}function oi(e){var t=e.delayedCallbacks,i=0;do{for(;i<t.length;i++)t[i]();for(var r=0;r<e.ops.length;r++){var n=e.ops[r];if(n.cursorActivityHandlers)for(;n.cursorActivityCalled<n.cursorActivityHandlers.length;)n.cursorActivityHandlers[n.cursorActivityCalled++](n.cm)}}while(i<t.length)}function si(e){var t=e.curOp,i=t.ownsGroup;if(i)try{oi(i)}finally{bs=null;for(var r=0;r<i.ops.length;r++)i.ops[r].cm.curOp=null;ai(i)}}function ai(e){for(var t=e.ops,i=0;i<t.length;i++)li(t[i]);for(var i=0;i<t.length;i++)ui(t[i]);for(var i=0;i<t.length;i++)pi(t[i]);for(var i=0;i<t.length;i++)ci(t[i]);for(var i=0;i<t.length;i++)di(t[i])}function li(e){var t=e.cm,i=t.display;S(t);e.updateMaxLine&&d(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<i.viewFrom||e.scrollToPos.to.line>=i.viewTo)||i.maxLineChanged&&t.options.lineWrapping;e.update=e.mustUpdate&&new A(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function ui(e){e.updatedDisplay=e.mustUpdate&&C(e.cm,e.update)}function pi(e){var t=e.cm,i=t.display;e.updatedDisplay&&P(t);e.barMeasure=h(t);if(i.maxLineChanged&&!t.options.lineWrapping){e.adjustWidthTo=Gt(t,i.maxLine,i.maxLine.text.length).left+3;t.display.sizerWidth=e.adjustWidthTo;e.barMeasure.scrollWidth=Math.max(i.scroller.clientWidth,i.sizer.offsetLeft+e.adjustWidthTo+Pt(t)+t.display.barWidth);e.maxScrollLeft=Math.max(0,i.sizer.offsetLeft+e.adjustWidthTo-Dt(t))}(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=vt(t))}function ci(e){var t=e.cm;if(null!=e.adjustWidthTo){t.display.sizer.style.minWidth=e.adjustWidthTo+"px";e.maxScrollLeft<t.doc.scrollLeft&&zi(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0);t.display.maxLineChanged=!1}e.newSelectionNodes&&xt(t,e.newSelectionNodes);e.updatedDisplay&&O(t,e.barMeasure);(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure);e.selectionChanged&&It(t);t.state.focused&&e.updateInput&&bi(t,e.typing)}function di(e){var t=e.cm,i=t.display,r=t.doc;e.updatedDisplay&&R(t,e.update);null==i.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(i.wheelStartX=i.wheelStartY=null);if(null!=e.scrollTop&&(i.scroller.scrollTop!=e.scrollTop||e.forceScroll)){r.scrollTop=Math.max(0,Math.min(i.scroller.scrollHeight-i.scroller.clientHeight,e.scrollTop));i.scrollbars.setScrollTop(r.scrollTop);i.scroller.scrollTop=r.scrollTop}if(null!=e.scrollLeft&&(i.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){r.scrollLeft=Math.max(0,Math.min(i.scroller.scrollWidth-Dt(t),e.scrollLeft));i.scrollbars.setScrollLeft(r.scrollLeft);i.scroller.scrollLeft=r.scrollLeft;T(t)}if(e.scrollToPos){var n=Nr(t,tt(r,e.scrollToPos.from),tt(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&xr(t,n)}var o=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(o)for(var a=0;a<o.length;++a)o[a].lines.length||ga(o[a],"hide");if(s)for(var a=0;a<s.length;++a)s[a].lines.length&&ga(s[a],"unhide");i.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&ga(t,"changes",t,e.changeObjs)}function fi(e,t){if(e.curOp)return t();ni(e);try{return t()}finally{si(e)}}function hi(e,t){return function(){if(e.curOp)return t.apply(e,arguments);ni(e);try{return t.apply(e,arguments)}finally{si(e)}}}function Ei(e){return function(){if(this.curOp)return e.apply(this,arguments);ni(this);try{return e.apply(this,arguments)}finally{si(this)}}}function mi(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);ni(t);try{return e.apply(this,arguments)}finally{si(t)}}}function gi(e,t,i){this.line=t;this.rest=sn(t);this.size=this.rest?Hn(No(this.rest))-i+1:1;this.node=this.text=null;this.hidden=un(e,t)}function vi(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new gi(e.doc,Bn(e.doc,o),o);r=o+s.size;n.push(s)}return n}function xi(e,t,i,r){null==t&&(t=e.doc.first);null==i&&(i=e.doc.first+e.doc.size);r||(r=0);var n=e.display;r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t);e.curOp.viewChanged=!0;if(t>=n.viewTo)Ls&&an(e.doc,t)<n.viewTo&&Ti(e);else if(i<=n.viewFrom)if(Ls&&ln(e.doc,i+r)>n.viewFrom)Ti(e); else{n.viewFrom+=r;n.viewTo+=r}else if(t<=n.viewFrom&&i>=n.viewTo)Ti(e);else if(t<=n.viewFrom){var o=Ii(e,i,i+r,1);if(o){n.view=n.view.slice(o.index);n.viewFrom=o.lineN;n.viewTo+=r}else Ti(e)}else if(i>=n.viewTo){var o=Ii(e,t,t,-1);if(o){n.view=n.view.slice(0,o.index);n.viewTo=o.lineN}else Ti(e)}else{var s=Ii(e,t,t,-1),a=Ii(e,i,i+r,1);if(s&&a){n.view=n.view.slice(0,s.index).concat(vi(e,s.lineN,a.lineN)).concat(n.view.slice(a.index));n.viewTo+=r}else Ti(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function Ni(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null);if(!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[Li(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==To(s,i)&&s.push(i)}}}function Ti(e){e.display.viewFrom=e.display.viewTo=e.doc.first;e.display.view=[];e.display.viewOffset=0}function Li(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++){t-=i[r].size;if(0>t)return r}}function Ii(e,t,i,r){var n,o=Li(e,t),s=e.display.view;if(!Ls||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t;o++}else n=l-t;t+=n;i+=n}for(;an(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:i}}function yi(e,t,i){var r=e.display,n=r.view;if(0==n.length||t>=r.viewTo||i<=r.viewFrom){r.view=vi(e,t,i);r.viewFrom=t}else{r.viewFrom>t?r.view=vi(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(Li(e,t)));r.viewFrom=t;r.viewTo<i?r.view=r.view.concat(vi(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,Li(e,i)))}r.viewTo=i}function Ai(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function Si(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Ri(e);e.state.focused&&Si(e)})}function Ci(e){function t(){var r=Ri(e);if(r||i){e.display.pollingFast=!1;Si(e)}else{i=!0;e.display.poll.set(60,t)}}var i=!1;e.display.pollingFast=!0;e.display.poll.set(20,t)}function Ri(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||Ba(t)&&!i||Di(e)||e.options.disableInput||e.state.keySeq)return!1;if(e.state.pasteIncoming&&e.state.fakedLastChar){t.value=t.value.substring(0,t.value.length-1);e.state.fakedLastChar=!1}var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(ns&&os>=9&&e.display.inputHasSelection===n||ms&&/[\uf700-\uf7ff]/.test(n)){bi(e);return!1}var o=!e.curOp;o&&ni(e);e.display.shift=!1;8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="​");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;var l=n.slice(s),u=Ga(l),p=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(Ps&&Ps.join("\n")==l?p=r.sel.ranges.length%Ps.length==0&&Lo(Ps,Ga):u.length==r.sel.ranges.length&&(p=Lo(u,function(e){return[e]})));for(var c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],f=d.from(),h=d.to();s<i.length?f=Is(f.line,f.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=Is(h.line,Math.min(Bn(r,h.line).text.length,h.ch+No(u).length)));var E=e.curOp.updateInput,m={from:f,to:h,text:p?p[c%p.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};dr(e.doc,m);po(e,"inputRead",e,m);if(l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head),v=Bs(m);if(g.electricChars){for(var x=0;x<g.electricChars.length;x++)if(l.indexOf(g.electricChars.charAt(x))>-1){Sr(e,v.line,"smart");break}}else g.electricInput&&g.electricInput.test(Bn(r,v.line).text.slice(0,v.ch))&&Sr(e,v.line,"smart")}}yr(e);e.curOp.updateInput=E;e.curOp.typing=!0;n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n;o&&si(e);e.state.pasteIncoming=e.state.cutIncoming=!1;return!0}function bi(e,t){if(!e.display.contextMenuPending){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Ua&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s;e.state.focused&&Sa(e.display.input);ns&&os>=9&&(e.display.inputHasSelection=s)}else if(!t){e.display.prevInput=e.display.input.value="";ns&&os>=9&&(e.display.inputHasSelection=null)}e.display.inaccurateSelection=i}}function Oi(e){"nocursor"==e.options.readOnly||Es&&wo()==e.display.input||e.display.input.focus()}function Pi(e){if(!e.state.focused){Oi(e);rr(e)}}function Di(e){return e.options.readOnly||e.doc.cantEdit}function wi(e){function t(t){fo(e,t)||ha(t)}function i(t){if(e.somethingSelected()){Ps=e.getSelections();if(r.inaccurateSelection){r.prevInput="";r.inaccurateSelection=!1;r.input.value=Ps.join("\n");Sa(r.input)}}else{for(var i=[],n=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:Is(s,0),head:Is(s+1,0)};n.push(a);i.push(e.getRange(a.anchor,a.head))}if("cut"==t.type)e.setSelections(n,null,Ta);else{r.prevInput="";r.input.value=i.join("\n");Sa(r.input)}Ps=i}"cut"==t.type&&(e.state.cutIncoming=!0)}var r=e.display;Ea(r.scroller,"mousedown",hi(e,Gi));ns&&11>os?Ea(r.scroller,"dblclick",hi(e,function(t){if(!fo(e,t)){var i=ki(e,t);if(i&&!Hi(e,t)&&!Mi(e.display,t)){da(t);var r=e.findWordAt(i);st(e.doc,r.anchor,r.head)}}})):Ea(r.scroller,"dblclick",function(t){fo(e,t)||da(t)});Ea(r.lineSpace,"selectstart",function(e){Mi(r,e)||da(e)});Ns||Ea(r.scroller,"contextmenu",function(t){or(e,t)});Ea(r.scroller,"scroll",function(){if(r.scroller.clientHeight){qi(e,r.scroller.scrollTop);zi(e,r.scroller.scrollLeft,!0);ga(e,"scroll",e)}});Ea(r.scroller,"mousewheel",function(t){Xi(e,t)});Ea(r.scroller,"DOMMouseScroll",function(t){Xi(e,t)});Ea(r.wrapper,"scroll",function(){r.wrapper.scrollTop=r.wrapper.scrollLeft=0});Ea(r.input,"keyup",function(t){tr.call(e,t)});Ea(r.input,"input",function(){ns&&os>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null);Ri(e)});Ea(r.input,"keydown",hi(e,Ji));Ea(r.input,"keypress",hi(e,ir));Ea(r.input,"focus",Ao(rr,e));Ea(r.input,"blur",Ao(nr,e));if(e.options.dragDrop){Ea(r.scroller,"dragstart",function(t){Wi(e,t)});Ea(r.scroller,"dragenter",t);Ea(r.scroller,"dragover",t);Ea(r.scroller,"drop",hi(e,ji))}Ea(r.scroller,"paste",function(t){if(!Mi(r,t)){e.state.pasteIncoming=!0;Oi(e);Ci(e)}});Ea(r.input,"paste",function(){if(ss&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=r.input.selectionStart,i=r.input.selectionEnd;r.input.value+="$";r.input.selectionEnd=i;r.input.selectionStart=t;e.state.fakedLastChar=!0}e.state.pasteIncoming=!0;Ci(e)});Ea(r.input,"cut",i);Ea(r.input,"copy",i);cs&&Ea(r.sizer,"mouseup",function(){wo()==r.input&&r.input.blur();Oi(e)})}function _i(e){var t=e.display;if(t.lastWrapHeight!=t.wrapper.clientHeight||t.lastWrapWidth!=t.wrapper.clientWidth){t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null;t.scrollbarsClipped=!1;e.setSize()}}function Mi(e,t){for(var i=lo(t);i!=e.wrapper;i=i.parentNode)if(!i||1==i.nodeType&&"true"==i.getAttribute("cm-ignore-events")||i.parentNode==e.sizer&&i!=e.mover)return!0}function ki(e,t,i,r){var n=e.display;if(!i&&"true"==lo(t).getAttribute("not-content"))return null;var o,s,a=n.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left;s=t.clientY-a.top}catch(t){return null}var l,u=ei(e,o,s);if(r&&1==u.xRel&&(l=Bn(e.doc,u.line).text).length==u.ch){var p=ya(l,l.length,e.options.tabSize)-l.length;u=Is(u.line,Math.max(0,Math.round((o-Ot(e.display).left)/ri(e.display))-p))}return u}function Gi(e){if(!fo(this,e)){var t=this,i=t.display;i.shift=e.shiftKey;if(Mi(i,e)){if(!ss){i.scroller.draggable=!1;setTimeout(function(){i.scroller.draggable=!0},100)}}else if(!Hi(t,e)){var r=ki(t,e);window.focus();switch(uo(e)){case 1:r?Bi(t,e,r):lo(e)==i.scroller&&da(e);break;case 2:ss&&(t.state.lastMiddleDown=+new Date);r&&st(t.doc,r);setTimeout(Ao(Oi,t),20);da(e);break;case 3:Ns&&or(t,e)}}}}function Bi(e,t,i){setTimeout(Ao(Pi,e),0);var r,n=+new Date;if(Cs&&Cs.time>n-400&&0==ys(Cs.pos,i))r="triple";else if(Ss&&Ss.time>n-400&&0==ys(Ss.pos,i)){r="double";Cs={time:n,pos:i}}else{r="single";Ss={time:n,pos:i}}var o,s=e.doc.sel,a=ms?t.metaKey:t.ctrlKey;e.options.dragDrop&&ka&&!Di(e)&&"single"==r&&(o=s.contains(i))>-1&&!s.ranges[o].empty()?Ui(e,t,i,a):Vi(e,t,i,r,a)}function Ui(e,t,i,r){var n=e.display,o=hi(e,function(s){ss&&(n.scroller.draggable=!1);e.state.draggingText=!1;ma(document,"mouseup",o);ma(n.scroller,"drop",o);if(Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10){da(s);r||st(e.doc,i);Oi(e);ns&&9==os&&setTimeout(function(){document.body.focus();Oi(e)},20)}});ss&&(n.scroller.draggable=!0);e.state.draggingText=o;n.scroller.dragDrop&&n.scroller.dragDrop();Ea(document,"mouseup",o);Ea(n.scroller,"drop",o)}function Vi(e,t,i,r,n){function o(t){if(0!=ys(m,t)){m=t;if("rect"==r){for(var n=[],o=e.options.tabSize,s=ya(Bn(u,i.line).text,i.ch,o),a=ya(Bn(u,t.line).text,t.ch,o),l=Math.min(s,a),f=Math.max(s,a),h=Math.min(i.line,t.line),E=Math.min(e.lastLine(),Math.max(i.line,t.line));E>=h;h++){var g=Bn(u,h).text,v=vo(g,l,o);l==f?n.push(new Q(Is(h,v),Is(h,v))):g.length>v&&n.push(new Q(Is(h,v),Is(h,vo(g,f,o))))}n.length||n.push(new Q(i,i));dt(u,Z(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1});e.scrollIntoView(t)}else{var x=p,N=x.anchor,T=t;if("single"!=r){if("double"==r)var L=e.findWordAt(t);else var L=new Q(Is(t.line,0),tt(u,Is(t.line+1,0)));if(ys(L.anchor,N)>0){T=L.head;N=K(x.from(),L.anchor)}else{T=L.anchor;N=Y(x.to(),L.head)}}var n=d.ranges.slice(0);n[c]=new Q(tt(u,N),T);dt(u,Z(n,c),La)}}}function s(t){var i=++v,n=ki(e,t,!0,"rect"==r);if(n)if(0!=ys(n,m)){Pi(e);o(n);var a=N(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(hi(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<g.top?-20:t.clientY>g.bottom?20:0;p&&setTimeout(hi(e,function(){if(v==i){l.scroller.scrollTop+=p;s(t)}}),50)}}function a(t){v=1/0;da(t);Oi(e);ma(document,"mousemove",x);ma(document,"mouseup",T);u.history.lastSelOrigin=null}var l=e.display,u=e.doc;da(t);var p,c,d=u.sel,f=d.ranges;if(n&&!t.shiftKey){c=u.sel.contains(i);p=c>-1?f[c]:new Q(i,i)}else p=u.sel.primary();if(t.altKey){r="rect";n||(p=new Q(i,i));i=ki(e,t,!0,!0);c=-1}else if("double"==r){var h=e.findWordAt(i);p=e.display.shift||u.extend?ot(u,p,h.anchor,h.head):h}else if("triple"==r){var E=new Q(Is(i.line,0),tt(u,Is(i.line+1,0)));p=e.display.shift||u.extend?ot(u,p,E.anchor,E.head):E}else p=ot(u,p,i);if(n)if(-1==c){c=f.length;dt(u,Z(f.concat([p]),c),{scroll:!1,origin:"*mouse"})}else if(f.length>1&&f[c].empty()&&"single"==r){dt(u,Z(f.slice(0,c).concat(f.slice(c+1)),0));d=u.sel}else lt(u,c,p,La);else{c=0;dt(u,new $([p],0),La);d=u.sel}var m=i,g=l.wrapper.getBoundingClientRect(),v=0,x=hi(e,function(e){uo(e)?s(e):a(e)}),T=hi(e,a);Ea(document,"mousemove",x);Ea(document,"mouseup",T)}function Fi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&da(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Eo(e,i))return ao(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=jn(e.doc,s),d=e.options.gutters[u];n(e,i,e,c,d,t);return ao(t)}}}function Hi(e,t){return Fi(e,t,"gutterClick",!0,po)}function ji(e){var t=this;if(!fo(t,e)&&!Mi(t.display,e)){da(e);ns&&(Ds=+new Date);var i=ki(t,e,!0),r=e.dataTransfer.files;if(i&&!Di(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=hi(t,function(){o[r]=a.result;if(++s==n){i=tt(t.doc,i);var e={from:i,to:i,text:Ga(o.join("\n")),origin:"paste"};dr(t.doc,e);ct(t.doc,J(i,Bs(e)))}});a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1){t.state.draggingText(e);setTimeout(Ao(Oi,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(ms?e.metaKey:e.ctrlKey))var u=t.listSelections();ft(t.doc,J(i,i));if(u)for(var l=0;l<u.length;++l)vr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste");Oi(t)}}catch(e){}}}}function Wi(e,t){if(ns&&(!e.state.draggingText||+new Date-Ds<100))ha(t);else if(!fo(e,t)&&!Mi(e.display,t)){t.dataTransfer.setData("Text",e.getSelection());if(t.dataTransfer.setDragImage&&!ps){var i=bo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(us){i.width=i.height=1;e.display.wrapper.appendChild(i);i._top=i.offsetTop}t.dataTransfer.setDragImage(i,0,0);us&&i.parentNode.removeChild(i)}}}function qi(e,t){if(!(Math.abs(e.doc.scrollTop-t)<2)){e.doc.scrollTop=t;ts||b(e,{top:t});e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t);e.display.scrollbars.setScrollTop(t);ts&&b(e);yt(e,100)}}function zi(e,t,i){if(!(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth);e.doc.scrollLeft=t;T(e);e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t);e.display.scrollbars.setScrollLeft(t)}}function Xi(e,t){var i=Ms(t),r=i.x,n=i.y,o=e.display,s=o.scroller;if(r&&s.scrollWidth>s.clientWidth||n&&s.scrollHeight>s.clientHeight){if(n&&ms&&ss)e:for(var a=t.target,l=o.view;a!=s;a=a.parentNode)for(var u=0;u<l.length;u++)if(l[u].node==a){e.display.currentWheelTarget=a;break e}if(!r||ts||us||null==_s){if(n&&null!=_s){var p=n*_s,c=e.doc.scrollTop,d=c+o.wrapper.clientHeight;0>p?c=Math.max(0,c+p-50):d=Math.min(e.doc.height,d+p+50);b(e,{top:c,bottom:d})}if(20>ws)if(null==o.wheelStartX){o.wheelStartX=s.scrollLeft;o.wheelStartY=s.scrollTop;o.wheelDX=r;o.wheelDY=n;setTimeout(function(){if(null!=o.wheelStartX){var e=s.scrollLeft-o.wheelStartX,t=s.scrollTop-o.wheelStartY,i=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null;if(i){_s=(_s*ws+i)/(ws+1);++ws}}},200)}else{o.wheelDX+=r;o.wheelDY+=n}}else{n&&qi(e,Math.max(0,Math.min(s.scrollTop+n*_s,s.scrollHeight-s.clientHeight)));zi(e,Math.max(0,Math.min(s.scrollLeft+r*_s,s.scrollWidth-s.clientWidth)));da(t);o.wheelStartX=null}}}function Yi(e,t,i){if("string"==typeof t){t=Ks[t];if(!t)return!1}e.display.pollingFast&&Ri(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{Di(e)&&(e.state.suppressEdits=!0);i&&(e.display.shift=!1);n=t(e)!=Na}finally{e.display.shift=r;e.state.suppressEdits=!1}return n}function Ki(e,t,i){for(var r=0;r<e.state.keyMaps.length;r++){var n=Qs(t,e.state.keyMaps[r],i,e);if(n)return n}return e.options.extraKeys&&Qs(t,e.options.extraKeys,i,e)||Qs(t,e.options.keyMap,i,e)}function $i(e,t,i,r){var n=e.state.keySeq;if(n){if(Zs(t))return"handled";ks.set(50,function(){if(e.state.keySeq==n){e.state.keySeq=null;bi(e)}});t=n+" "+t}var o=Ki(e,t,r);"multi"==o&&(e.state.keySeq=t);"handled"==o&&po(e,"keyHandled",e,t,i);if("handled"==o||"multi"==o){da(i);It(e)}if(n&&!o&&/\'$/.test(t)){da(i);return!0}return!!o}function Qi(e,t){var i=Js(t,!0);return i?t.shiftKey&&!e.state.keySeq?$i(e,"Shift-"+i,t,function(t){return Yi(e,t,!0)})||$i(e,i,t,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Yi(e,t):void 0}):$i(e,i,t,function(t){return Yi(e,t)}):!1}function Zi(e,t,i){return $i(e,"'"+i+"'",t,function(t){return Yi(e,t,!0)})}function Ji(e){var t=this;Pi(t);if(!fo(t,e)){ns&&11>os&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=Qi(t,e);if(us){Gs=r?i:null;!r&&88==i&&!Ua&&(ms?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")}18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||er(t)}}function er(e){function t(e){if(18==e.keyCode||!e.altKey){wa(i,"CodeMirror-crosshair");ma(document,"keyup",t);ma(document,"mouseover",t)}}var i=e.display.lineDiv;_a(i,"CodeMirror-crosshair");Ea(document,"keyup",t);Ea(document,"mouseover",t)}function tr(e){16==e.keyCode&&(this.doc.sel.shift=!1);fo(this,e)}function ir(e){var t=this;if(!(fo(t,e)||e.ctrlKey&&!e.altKey||ms&&e.metaKey)){var i=e.keyCode,r=e.charCode;if(us&&i==Gs){Gs=null;da(e)}else if(!(us&&(!e.which||e.which<10)||cs)||!Qi(t,e)){var n=String.fromCharCode(null==r?i:r);if(!Zi(t,e,n)){ns&&os>=9&&(t.display.inputHasSelection=null);Ci(t)}}}}function rr(e){if("nocursor"!=e.options.readOnly){if(!e.state.focused){ga(e,"focus",e);e.state.focused=!0;_a(e.display.wrapper,"CodeMirror-focused");if(!e.curOp&&e.display.selForContextMenu!=e.doc.sel){bi(e);ss&&setTimeout(Ao(bi,e,!0),0)}}Si(e);It(e)}}function nr(e){if(e.state.focused){ga(e,"blur",e);e.state.focused=!1;wa(e.display.wrapper,"CodeMirror-focused")}clearInterval(e.display.blinker);setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function or(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value="​"+(t?n.input.value:"");n.prevInput=t?"":"​";n.input.selectionStart=1;n.input.selectionEnd=i.length;n.selForContextMenu=e.doc.sel}}function r(){n.contextMenuPending=!1;n.inputDiv.style.position="relative";n.input.style.cssText=l;ns&&9>os&&n.scrollbars.setScrollTop(n.scroller.scrollTop=s);Si(e);if(null!=n.input.selectionStart){(!ns||ns&&9>os)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?hi(e,Ks.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):bi(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!fo(e,t,"contextmenu")){var n=e.display;if(!Mi(n,t)&&!sr(e,t)){var o=ki(e,t),s=n.scroller.scrollTop;if(o&&!us){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&hi(e,dt)(e.doc,J(o),Ta);var l=n.input.style.cssText;n.inputDiv.style.position="absolute";n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(ns?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ss)var u=window.scrollY;Oi(e);ss&&window.scrollTo(null,u);bi(e);e.somethingSelected()||(n.input.value=n.prevInput=" ");n.contextMenuPending=!0;n.selForContextMenu=e.doc.sel;clearTimeout(n.detectingSelectAll);ns&&os>=9&&i();if(Ns){ha(t);var p=function(){ma(window,"mouseup",p);setTimeout(r,20)};Ea(window,"mouseup",p)}else setTimeout(r,50)}}}}function sr(e,t){return Eo(e,"gutterContextMenu")?Fi(e,t,"gutterContextMenu",!1,ga):!1}function ar(e,t){if(ys(e,t.from)<0)return e;if(ys(e,t.to)<=0)return Bs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;e.line==t.to.line&&(r+=Bs(t).ch-t.to.ch);return Is(i,r)}function lr(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new Q(ar(n.anchor,t),ar(n.head,t)))}return Z(i,e.sel.primIndex)}function ur(e,t,i){return e.line==t.line?Is(i.line,e.ch-t.ch+i.ch):Is(i.line+(e.line-t.line),e.ch)}function pr(e,t,i){for(var r=[],n=Is(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=ur(a.from,n,o),u=ur(Bs(a),n,o);n=a.to;o=u;if("around"==i){var p=e.sel.ranges[s],c=ys(p.head,p.anchor)<0;r[s]=new Q(c?u:l,c?l:u)}else r[s]=new Q(l,l)}return new $(r,e.sel.primIndex)}function cr(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};i&&(r.update=function(t,i,r,n){t&&(this.from=tt(e,t));i&&(this.to=tt(e,i));r&&(this.text=r);void 0!==n&&(this.origin=n)});ga(e,"beforeChange",e,r);e.cm&&ga(e.cm,"beforeChange",e.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function dr(e,t,i){if(e.cm){if(!e.cm.curOp)return hi(e.cm,dr)(e,t,i);if(e.cm.state.suppressEdits)return}if(Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange")){t=cr(e,t,!0);if(!t)return}var r=Ts&&!i&&Yr(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)fr(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else fr(e,t)}function fr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ys(t.from,t.to)){var i=lr(e,t);$n(e,t,i,e.cm?e.cm.curOp.id:0/0);mr(e,t,i,qr(e,t));var r=[];kn(e,function(e,i){if(!i&&-1==To(r,e.history)){so(e.history,t);r.push(e.history)}mr(e,t,null,qr(e,t))})}}function hr(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length;l++){r=s[l];if(i?r.ranges&&!r.equals(e.sel):!r.ranges)break}if(l!=s.length){n.lastOrigin=n.lastSelOrigin=null;for(;;){r=s.pop();if(!r.ranges)break;Jn(r,a);if(i&&!r.equals(e.sel)){dt(e,r,{clearRedo:!1});return}o=r}var u=[];Jn(o,a);a.push({changes:u,generation:n.generation});n.generation=r.generation||++n.maxGeneration;for(var p=Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];c.origin=t;if(p&&!cr(e,c,!1)){s.length=0;return}u.push(Xn(e,c));var d=l?lr(e,c):No(s);mr(e,c,d,Xr(e,c));!l&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Bs(c)});var f=[];kn(e,function(e,t){if(!t&&-1==To(f,e.history)){so(e.history,c);f.push(e.history)}mr(e,c,null,Xr(e,c))})}}}}function Er(e,t){if(0!=t){e.first+=t;e.sel=new $(Lo(e.sel.ranges,function(e){return new Q(Is(e.anchor.line+t,e.anchor.ch),Is(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){xi(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)Ni(e.cm,r,"gutter")}}}function mr(e,t,i,r){if(e.cm&&!e.cm.curOp)return hi(e.cm,mr)(e,t,i,r);if(t.to.line<e.first)Er(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Er(e,n);t={from:Is(e.first,0),to:Is(t.to.line+n,t.to.ch),text:[No(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:Is(o,Bn(e,o).text.length),text:[t.text[0]],origin:t.origin});t.removed=Un(e,t.from,t.to);i||(i=lr(e,t));e.cm?gr(e.cm,t,r):wn(e,t,r);ft(e,i,Ta)}}function gr(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;if(!e.options.lineWrapping){u=Hn(on(Bn(r,s.line)));r.iter(u,a.line+1,function(e){if(e==n.maxLine){l=!0;return!0}})}r.sel.contains(t.from,t.to)>-1&&ho(e);wn(r,t,i,o(e));if(!e.options.lineWrapping){r.iter(u,s.line+t.text.length,function(e){var t=c(e);if(t>n.maxLineLength){n.maxLine=e;n.maxLineLength=t;n.maxLineChanged=!0;l=!1}});l&&(e.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,s.line);yt(e,400);var p=t.text.length-(a.line-s.line)-1;t.full?xi(e):s.line!=a.line||1!=t.text.length||Dn(e.doc,t)?xi(e,s.line,a.line+1,p):Ni(e,s.line,"text");var d=Eo(e,"changes"),f=Eo(e,"change");if(f||d){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&po(e,"change",e,h);d&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function vr(e,t,i,r,n){r||(r=i);if(ys(r,i)<0){var o=r;r=i;i=o}"string"==typeof t&&(t=Ga(t));dr(e,{from:i,to:r,text:t,origin:n})}function xr(e,t){if(!fo(e,"scrollCursorIntoView")){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1);if(null!=n&&!fs){var o=bo("div","​",null,"position: absolute; top: "+(t.top-i.viewOffset-Rt(e.display))+"px; height: "+(t.bottom-t.top+Pt(e)+i.barHeight)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o);o.scrollIntoView(n);e.display.lineSpace.removeChild(o)}}}function Nr(e,t,i,r){null==r&&(r=0);for(var n=0;5>n;n++){var o=!1,s=Qt(e,t),a=i&&i!=t?Qt(e,i):s,l=Lr(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-r,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+r),u=e.doc.scrollTop,p=e.doc.scrollLeft;if(null!=l.scrollTop){qi(e,l.scrollTop);Math.abs(e.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zi(e,l.scrollLeft);Math.abs(e.doc.scrollLeft-p)>1&&(o=!0)}if(!o)break}return s}function Tr(e,t,i,r,n){var o=Lr(e,t,i,r,n);null!=o.scrollTop&&qi(e,o.scrollTop);null!=o.scrollLeft&&zi(e,o.scrollLeft)}function Lr(e,t,i,r,n){var o=e.display,s=ii(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=wt(e),u={};n-i>l&&(n=i+l);var p=e.doc.height+bt(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var f=Math.min(i,(d?p:n)-l);f!=a&&(u.scrollTop=f)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,E=Dt(e)-(e.options.fixedGutter?o.gutters.offsetWidth:0),m=r-t>E;m&&(r=t+E);10>t?u.scrollLeft=0:h>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>E+h-3&&(u.scrollLeft=r+(m?0:10)-E);return u}function Ir(e,t,i){(null!=t||null!=i)&&Ar(e);null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t);null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function yr(e){Ar(e);var t=e.getCursor(),i=t,r=t;if(!e.options.lineWrapping){i=t.ch?Is(t.line,t.ch-1):t;r=Is(t.line,t.ch+1)}e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function Ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Zt(e,t.from),r=Zt(e,t.to),n=Lr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function Sr(e,t,i,r){var n,o=e.doc;null==i&&(i="add");"smart"==i&&(o.mode.indent?n=Ct(e,t):i="prev");var s=e.options.tabSize,a=Bn(o,t),l=ya(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i){u=o.mode.indent(n,a.text.slice(p.length),a.text);if(u==Na||u>150){if(!r)return;i="prev"}}}else{u=0;i="not"}"prev"==i?u=t>o.first?ya(Bn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i);u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(u/s);f;--f){d+=s;c+=" "}u>d&&(c+=xo(u-d));if(c!=p)vr(o,c,Is(t,0),Is(t,p.length),"+input");else for(var f=0;f<o.sel.ranges.length;f++){var h=o.sel.ranges[f];if(h.head.line==t&&h.head.ch<p.length){var d=Is(t,p.length);lt(o,f,new Q(d,d));break}}a.stateAfter=null}function Cr(e,t,i,r){var n=t,o=t;"number"==typeof t?o=Bn(e,et(e,t)):n=Hn(t);if(null==n)return null;r(o,n)&&e.cm&&Ni(e.cm,n,i);return o}function Rr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ys(o.from,No(r).to)<=0;){var s=r.pop();if(ys(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}fi(e,function(){for(var t=r.length-1;t>=0;t--)vr(e.doc,"",r[t].from,r[t].to,"+delete");yr(e)})}function br(e,t,i,r,n){function o(){var t=a+i;if(t<e.first||t>=e.first+e.size)return c=!1;a=t;return p=Bn(e,t)}function s(e){var t=(n?Jo:es)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?zo:qo)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=Bn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),E=!0;!(0>i)||s(!E);E=!1){var m=p.text.charAt(l)||"\n",g=So(m,h)?"w":f&&"\n"==m?"n":!f||/\s/.test(m)?null:"p";!f||E||g||(g="s");if(d&&d!=g){if(0>i){i=1;s()}break}g&&(d=g);if(i>0&&!s(!E))break}var v=gt(e,Is(a,l),u,!0);c||(v.hitSide=!0);return v}function Or(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*ii(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=ei(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Pr(t,i,r,n){e.defaults[t]=i;r&&(Vs[t]=n?function(e,t,i){i!=Fs&&r(e,t,i)}:r)}function Dr(e){for(var t,i,r,n,o=e.split(/-(?!$)/),e=o[o.length-1],s=0;s<o.length-1;s++){var a=o[s];if(/^(cmd|meta|m)$/i.test(a))n=!0;else if(/^a(lt)?$/i.test(a))t=!0;else if(/^(c|ctrl|control)$/i.test(a))i=!0;else{if(!/^s(hift)$/i.test(a))throw new Error("Unrecognized modifier name: "+a);r=!0}}t&&(e="Alt-"+e);i&&(e="Ctrl-"+e);n&&(e="Cmd-"+e);r&&(e="Shift-"+e);return e}function wr(e){return"string"==typeof e?$s[e]:e}function _r(e,t,i,r,n){if(r&&r.shared)return Mr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return hi(e.cm,_r)(e,t,i,r,n);var o=new ta(e,n),s=ys(t,i);r&&yo(r,o,!1);if(s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=bo("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true");r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(nn(e,t.line,t,i,o)||t.line!=i.line&&nn(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ls=!0}o.addToHistory&&$n(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&on(e)==u.display.maxLine&&(a=!0);o.collapsed&&l!=t.line&&Fn(e,0);Hr(e,new Ur(o,l==t.line?t.ch:null,l==i.line?i.ch:null));++l});o.collapsed&&e.iter(t.line,i.line+1,function(t){un(e,t)&&Fn(t,0)});o.clearOnEnter&&Ea(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){Ts=!0;(e.history.done.length||e.history.undone.length)&&e.clearHistory()}if(o.collapsed){o.id=++ia;o.atomic=!0}if(u){a&&(u.curOp.updateMaxLine=!0);if(o.collapsed)xi(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle||o.css)for(var p=t.line;p<=i.line;p++)Ni(u,p,"text");o.atomic&&Et(u.doc);po(u,"markerAdded",u,o)}return o}function Mr(e,t,i,r,n){r=yo(r);r.shared=!1;var o=[_r(e,t,i,r,n)],s=o[0],a=r.widgetNode;kn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0));o.push(_r(e,tt(e,t),tt(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=No(o)});return new ra(o,s)}function kr(e){return e.findMarks(Is(e.first,0),e.clipPos(Is(e.lastLine())),function(e){return e.parent})}function Gr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ys(o,s)){var a=_r(e,o,s,r.primary,r.primary.type);r.markers.push(a);a.parent=r}}}function Br(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];kn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];if(-1==To(r,o.doc)){o.parent=null;i.markers.splice(n--,1)}}}}function Ur(e,t,i){this.marker=e;this.from=t;this.to=i}function Vr(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Fr(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function Hr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t];t.marker.attachLine(e)}function jr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ur(s,o.from,l?null:o.to))}}return r}function Wr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ur(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function qr(e,t){if(t.full)return null;var i=rt(e,t.from.line)&&Bn(e,t.from.line).markedSpans,r=rt(e,t.to.line)&&Bn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ys(t.from,t.to),a=jr(i,n,s),l=Wr(r,o,s),u=1==t.text.length,p=No(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var f=Vr(l,d.marker);f?u&&(d.to=null==f.to?null:f.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];null!=d.to&&(d.to+=p);if(null==d.from){var f=Vr(a,d.marker);if(!f){d.from=p;u&&(a||(a=[])).push(d)}}else{d.from+=p;u&&(a||(a=[])).push(d)}}a&&(a=zr(a));l&&l!=a&&(l=zr(l));var h=[a];if(!u){var E,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(E||(E=[])).push(new Ur(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(E);h.push(l)}return h}function zr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Xr(e,t){var i=io(e,t),r=qr(e,t); if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Yr(e,t,i){var r=null;e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=To(r,i)||(r||(r=[])).push(i)}});if(!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ys(u.to,a.from)<0||ys(u.from,a.to)>0)){var p=[l,1],c=ys(u.from,a.from),d=ys(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from});(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to});n.splice.apply(n,p);l+=p.length-1}}return n}function Kr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function $r(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function Qr(e){return e.inclusiveLeft?-1:0}function Zr(e){return e.inclusiveRight?1:0}function Jr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ys(r.from,n.from)||Qr(e)-Qr(t);if(o)return-o;var s=ys(r.to,n.to)||Zr(e)-Zr(t);return s?s:t.id-e.id}function en(e,t){var i,r=Ls&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o){n=r[o];n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||Jr(i,n.marker)<0)&&(i=n.marker)}return i}function tn(e){return en(e,!0)}function rn(e){return en(e,!1)}function nn(e,t,i,r,n){var o=Bn(e,t),s=Ls&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ys(u.from,i)||Qr(l.marker)-Qr(n),c=ys(u.to,r)||Zr(l.marker)-Zr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ys(u.to,i)>0||l.marker.inclusiveRight&&n.inclusiveLeft)||p>=0&&(ys(u.from,r)<0||l.marker.inclusiveLeft&&n.inclusiveRight)))return!0}}}function on(e){for(var t;t=tn(e);)e=t.find(-1,!0).line;return e}function sn(e){for(var t,i;t=rn(e);){e=t.find(1,!0).line;(i||(i=[])).push(e)}return i}function an(e,t){var i=Bn(e,t),r=on(i);return i==r?t:Hn(r)}function ln(e,t){if(t>e.lastLine())return t;var i,r=Bn(e,t);if(!un(e,r))return t;for(;i=rn(r);)r=i.find(1,!0).line;return Hn(r)+1}function un(e,t){var i=Ls&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n){r=i[n];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&pn(e,t,r))return!0}}}function pn(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return pn(e,r.line,Vr(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o){n=t.markedSpans[o];if(n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&pn(e,t,n))return!0}}function cn(e,t,i){Wn(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Ir(e,null,i)}function dn(e){if(null!=e.height)return e.height;if(!Do(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.display.gutters.offsetWidth+"px;");e.noHScroll&&(t+="width: "+e.cm.display.wrapper.clientWidth+"px;");Po(e.cm.display.measure,bo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function fn(e,t,i,r){var n=new na(e,i,r);n.noHScroll&&(e.display.alignWidgets=!0);Cr(e.doc,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n);n.line=t;if(!un(e.doc,t)){var r=Wn(t)<e.doc.scrollTop;Fn(t,t.height+dn(n));r&&Ir(e,null,n.height);e.curOp.forceUpdate=!0}return!0});return n}function hn(e,t,i,r){e.text=t;e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null);null!=e.order&&(e.order=null);Kr(e);$r(e,i);var n=r?r(e):1;n!=e.height&&Fn(e,n)}function En(e){e.parent=null;Kr(e)}function mn(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function gn(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function vn(t,i,r,n){for(var o=0;10>o;o++){n&&(n[0]=e.innerMode(t,r).mode);var s=t.token(i,r);if(i.pos>i.start)return s}throw new Error("Mode "+t.name+" failed to advance stream.")}function xn(e,t,i,r){function n(e){return{start:c.start,end:c.pos,string:c.current(),type:o||null,state:e?Xs(s.mode,p):p}}var o,s=e.doc,a=s.mode;t=tt(s,t);var l,u=Bn(s,t.line),p=Ct(e,t.line,i),c=new ea(u.text,e.options.tabSize);r&&(l=[]);for(;(r||c.pos<t.ch)&&!c.eol();){c.start=c.pos;o=vn(a,c,p);r&&l.push(n(!0))}return r?l:n()}function Nn(e,t,i,r,n,o,s){var a=i.flattenSpans;null==a&&(a=e.options.flattenSpans);var l,u=0,p=null,c=new ea(t,e.options.tabSize),d=e.options.addModeClass&&[null];""==t&&mn(gn(i,r),o);for(;!c.eol();){if(c.pos>e.options.maxHighlightLength){a=!1;s&&In(e,t,r,c.pos);c.pos=t.length;l=null}else l=mn(vn(i,c,r,d),o);if(d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!a||p!=l){for(;u<c.start;){u=Math.min(c.start,u+5e4);n(u,p)}p=l}c.start=c.pos}for(;u<c.pos;){var h=Math.min(c.pos,u+5e4);n(h,p);u=h}}function Tn(e,t,i,r){var n=[e.state.modeGen],o={};Nn(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;Nn(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r);l+=2;u=Math.min(e,r)}if(t)if(a.opaque){n.splice(i,l-i,e,"cm-overlay "+t);l=i+2}else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function Ln(e,t,i){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=Tn(e,t,t.stateAfter=Ct(e,Hn(t)));t.styles=r.styles;r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null);i===e.doc.frontier&&e.doc.frontier++}return t.styles}function In(e,t,i,r){var n=e.doc.mode,o=new ea(t,e.options.tabSize);o.start=o.pos=r||0;""==t&&gn(n,i);for(;!o.eol()&&o.pos<=e.options.maxHighlightLength;){vn(n,o,i);o.start=o.pos}}function yn(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?aa:sa;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function An(e,t){var i=bo("span",null,null,ss?"padding-right: .1px":null),r={pre:bo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0;r.addToken=Cn;(ns||ss)&&e.getOption("lineWrapping")&&(r.addToken=Rn(r.addToken));Vo(e.display.measure)&&(o=qn(s))&&(r.addToken=bn(r.addToken,o));r.map=[];var a=t!=e.display.externalMeasured&&Hn(s);Pn(s,r,Ln(e,s,a));if(s.styleClasses){s.styleClasses.bgClass&&(r.bgClass=Mo(s.styleClasses.bgClass,r.bgClass||""));s.styleClasses.textClass&&(r.textClass=Mo(s.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Uo(e.display.measure)));if(0==n){t.measure.map=r.map;t.measure.cache={}}else{(t.measure.maps||(t.measure.maps=[])).push(r.map);(t.measure.caches||(t.measure.caches=[])).push({})}}ss&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");ga(e,"renderLine",e,t.line,r.pre);r.pre.className&&(r.textClass=Mo(r.pre.className,r.textClass||""));return r}function Sn(e){var t=bo("span","•","cm-invalidchar");t.title="\\u"+e.charCodeAt(0).toString(16);return t}function Cn(e,t,i,r,n,o,s){if(t){var a=e.cm.options.specialChars,l=!1;if(a.test(t))for(var u=document.createDocumentFragment(),p=0;;){a.lastIndex=p;var c=a.exec(t),d=c?c.index-p:t.length-p;if(d){var f=document.createTextNode(t.slice(p,p+d));u.appendChild(ns&&9>os?bo("span",[f]):f);e.map.push(e.pos,e.pos+d,f);e.col+=d;e.pos+=d}if(!c)break;p+=d+1;if(" "==c[0]){var h=e.cm.options.tabSize,E=h-e.col%h,f=u.appendChild(bo("span",xo(E),"cm-tab"));e.col+=E}else{var f=e.cm.options.specialCharPlaceholder(c[0]);u.appendChild(ns&&9>os?bo("span",[f]):f);e.col+=1}e.map.push(e.pos,e.pos+1,f);e.pos++}else{e.col+=t.length;var u=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,u);ns&&9>os&&(l=!0);e.pos+=t.length}if(i||r||n||l||s){var m=i||"";r&&(m+=r);n&&(m+=n);var g=bo("span",[u],m,s);o&&(g.title=o);return e.content.appendChild(g)}e.content.appendChild(u)}}function Rn(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";t+=" ";return t}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function bn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a);o=null;r=r.slice(c.to-l);l=c.to}}}function On(e,t,i,r){var n=!r&&i.widgetNode;if(n){e.map.push(e.pos,e.pos+t,n);e.content.appendChild(n)}e.pos+=t}function Pn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d,f=n.length,h=0,E=1,m="",g=0;;){if(g==h){l=u=p=c=a="";d=null;g=1/0;for(var v=[],x=0;x<r.length;++x){var N=r[x],T=N.marker;if(N.from<=h&&(null==N.to||N.to>h)){if(null!=N.to&&g>N.to){g=N.to;u=""}T.className&&(l+=" "+T.className);T.css&&(a=T.css);T.startStyle&&N.from==h&&(p+=" "+T.startStyle);T.endStyle&&N.to==g&&(u+=" "+T.endStyle);T.title&&!c&&(c=T.title);T.collapsed&&(!d||Jr(d.marker,T)<0)&&(d=N)}else N.from>h&&g>N.from&&(g=N.from);"bookmark"==T.type&&N.from==h&&T.widgetNode&&v.push(T)}if(d&&(d.from||0)==h){On(t,(null==d.to?f+1:d.to)-h,d.marker,null==d.from);if(null==d.to)return}if(!d&&v.length)for(var x=0;x<v.length;++x)On(t,0,v[x])}if(h>=f)break;for(var L=Math.min(f,g);;){if(m){var I=h+m.length;if(!d){var y=I>L?m.slice(0,L-h):m;t.addToken(t,y,s?s+l:l,p,h+y.length==g?u:"",c,a)}if(I>=L){m=m.slice(L-h);h=L;break}h=I;p=""}m=n.slice(o,o=i[E++]);s=yn(i[E++],t.cm.options)}}else for(var E=1;E<i.length;E+=2)t.addToken(t,n.slice(o,o=i[E]),yn(i[E+1],t.cm.options))}function Dn(e,t){return 0==t.from.ch&&0==t.to.ch&&""==No(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function wn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){hn(e,i,n,r);po(e,"change",e,t)}function s(e,t){for(var i=e,o=[];t>i;++i)o.push(new oa(u[i],n(i),r));return o}var a=t.from,l=t.to,u=t.text,p=Bn(e,a.line),c=Bn(e,l.line),d=No(u),f=n(u.length-1),h=l.line-a.line;if(t.full){e.insert(0,s(0,u.length));e.remove(u.length,e.size-u.length)}else if(Dn(e,t)){var E=s(0,u.length-1);o(c,c.text,f);h&&e.remove(a.line,h);E.length&&e.insert(a.line,E)}else if(p==c)if(1==u.length)o(p,p.text.slice(0,a.ch)+d+p.text.slice(l.ch),f);else{var E=s(1,u.length-1);E.push(new oa(d+p.text.slice(l.ch),f,r));o(p,p.text.slice(0,a.ch)+u[0],n(0));e.insert(a.line+1,E)}else if(1==u.length){o(p,p.text.slice(0,a.ch)+u[0]+c.text.slice(l.ch),n(0));e.remove(a.line+1,h)}else{o(p,p.text.slice(0,a.ch)+u[0],n(0));o(c,d+c.text.slice(l.ch),f);var E=s(1,u.length-1);h>1&&e.remove(a.line+1,h-1);e.insert(a.line+1,E)}po(e,"change",e,t)}function _n(e){this.lines=e;this.parent=null;for(var t=0,i=0;t<e.length;++t){e[t].parent=this;i+=e[t].height}this.height=i}function Mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize();i+=n.height;n.parent=this}this.size=t;this.height=i;this.parent=null}function kn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;if(!i||l){t(a.doc,l);r(a.doc,e,l)}}}}r(e,null,!0)}function Gn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t;t.cm=e;s(e);i(e);e.options.lineWrapping||d(e);e.options.mode=t.modeOption;xi(e)}function Bn(e,t){t-=e.first;if(0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Un(e,t,i){var r=[],n=t.line;e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch));n==t.line&&(o=o.slice(t.ch));r.push(o);++n});return r}function Vn(e,t,i){var r=[];e.iter(t,i,function(e){r.push(e.text)});return r}function Fn(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function Hn(e){if(null==e.parent)return null;for(var t=e.parent,i=To(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function jn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o;i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function Wn(e){e=on(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function qn(e){var t=e.order;null==t&&(t=e.order=ja(e.text));return t}function zn(e){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=e||1}function Xn(e,t){var i={from:X(t.from),to:Bs(t),text:Un(e,t.from,t.to)};eo(e,i,t.from.line,t.to.line+1);kn(e,function(e){eo(e,i,t.from.line,t.to.line+1)},!0);return i}function Yn(e){for(;e.length;){var t=No(e);if(!t.ranges)break;e.pop()}}function Kn(e,t){if(t){Yn(e.done);return No(e.done)}if(e.done.length&&!No(e.done).ranges)return No(e.done);if(e.done.length>1&&!e.done[e.done.length-2].ranges){e.done.pop();return No(e.done)}}function $n(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Kn(n,n.lastOp==r))){var a=No(o.changes);0==ys(t.from,t.to)&&0==ys(t.from,a.to)?a.to=Bs(t):o.changes.push(Xn(e,t))}else{var l=No(n.done);l&&l.ranges||Jn(e.sel,n.done);o={changes:[Xn(e,t)],generation:n.generation};n.done.push(o);for(;n.done.length>n.undoDepth;){n.done.shift();n.done[0].ranges||n.done.shift()}}n.done.push(i);n.generation=++n.maxGeneration;n.lastModTime=n.lastSelTime=s;n.lastOp=n.lastSelOp=r;n.lastOrigin=n.lastSelOrigin=t.origin;a||ga(e,"historyAdded")}function Qn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Zn(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastSelOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Qn(e,o,No(n.done),t))?n.done[n.done.length-1]=t:Jn(t,n.done);n.lastSelTime=+new Date;n.lastSelOrigin=o;n.lastSelOp=i;r&&r.clearRedo!==!1&&Yn(n.undone)}function Jn(e,t){var i=No(t);i&&i.ranges&&i.equals(e)||t.push(e)}function eo(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans);++o})}function to(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function io(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(to(i[r]));return n}function ro(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?$.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];a.push({from:p.from,to:p.to,text:p.text});if(t)for(var c in p)if((u=c.match(/^spans_(\d+)$/))&&To(t,Number(u[1]))>-1){No(a)[c]=p[c];delete p[c]}}}}return n}function no(e,t,i,r){if(i<e.line)e.line+=r;else if(t<e.line){e.line=t;e.ch=0}}function oo(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){if(!o.copied){o=e[n]=o.deepCopy();o.copied=!0}for(var a=0;a<o.ranges.length;a++){no(o.ranges[a].anchor,t,i,r);no(o.ranges[a].head,t,i,r)}}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line){l.from=Is(l.from.line+r,l.from.ch);l.to=Is(l.to.line+r,l.to.ch)}else if(t<=l.to.line){s=!1;break}}if(!s){e.splice(0,n+1);n=0}}}}function so(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;oo(e.done,i,r,n);oo(e.undone,i,r,n)}function ao(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function lo(e){return e.target||e.srcElement}function uo(e){var t=e.which;null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2));ms&&e.ctrlKey&&1==t&&(t=3);return t}function po(e,t){function i(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var n,o=Array.prototype.slice.call(arguments,2);if(bs)n=bs.delayedCallbacks;else if(va)n=va;else{n=va=[];setTimeout(co,0)}for(var s=0;s<r.length;++s)n.push(i(r[s]))}}function co(){var e=va;va=null;for(var t=0;t<e.length;++t)e[t]()}function fo(e,t,i){"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}});ga(e,i||t.type,e,t);return ao(t)||t.codemirrorIgnore}function ho(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==To(i,t[r])&&i.push(t[r])}function Eo(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function mo(e){e.prototype.on=function(e,t){Ea(this,e,t)};e.prototype.off=function(e,t){ma(this,e,t)}}function go(){this.id=null}function vo(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);n+=o-r;n+=i-n%i;r=o+1;if(n>=t)return r}}function xo(e){for(;Aa.length<=e;)Aa.push(No(Aa)+" ");return Aa[e]}function No(e){return e[e.length-1]}function To(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function Lo(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function Io(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e;i=new r}t&&yo(t,i);return i}function yo(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function Ao(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function So(e,t){return t?t.source.indexOf("\\w")>-1&&ba(e)?!0:t.test(e):ba(e)}function Co(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Ro(e){return e.charCodeAt(0)>=768&&Oa.test(e)}function bo(e,t,i,r){var n=document.createElement(e);i&&(n.className=i);r&&(n.style.cssText=r);if("string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function Oo(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Po(e,t){return Oo(e).appendChild(t)}function Do(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function wo(){return document.activeElement}function _o(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function Mo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!_o(i[r]).test(t)&&(t+=" "+i[r]);return t}function ko(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function Go(){if(!Ma){Bo();Ma=!0}}function Bo(){var e;Ea(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null;ko(_i)},100))});Ea(window,"blur",function(){ko(nr)})}function Uo(e){if(null==Pa){var t=bo("span","​");Po(e,bo("span",[t,document.createTextNode("x")]));0!=e.firstChild.offsetHeight&&(Pa=t.offsetWidth<=1&&t.offsetHeight>2&&!(ns&&8>os))}return Pa?bo("span","​"):bo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Vo(e){if(null!=Da)return Da;var t=Po(e,document.createTextNode("AخA")),i=Ca(t,0,1).getBoundingClientRect();if(!i||i.left==i.right)return!1;var r=Ca(t,1,2).getBoundingClientRect();return Da=r.right-i.right<3}function Fo(e){if(null!=Va)return Va;var t=Po(e,bo("span","x")),i=t.getBoundingClientRect(),r=Ca(t,0,1).getBoundingClientRect();return Va=Math.abs(i.left-r.left)>1}function Ho(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];if(s.from<i&&s.to>t||t==i&&s.to==t){r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr");n=!0}}n||r(t,i,"ltr")}function jo(e){return e.level%2?e.to:e.from}function Wo(e){return e.level%2?e.from:e.to}function qo(e){var t=qn(e);return t?jo(t[0]):0}function zo(e){var t=qn(e);return t?Wo(No(t)):e.text.length}function Xo(e,t){var i=Bn(e.doc,t),r=on(i);r!=i&&(t=Hn(r));var n=qn(r),o=n?n[0].level%2?zo(r):qo(r):0;return Is(t,o)}function Yo(e,t){for(var i,r=Bn(e.doc,t);i=rn(r);){r=i.find(1,!0).line;t=null}var n=qn(r),o=n?n[0].level%2?qo(r):zo(r):r.text.length;return Is(null==t?Hn(r):t,o)}function Ko(e,t){var i=Xo(e,t.line),r=Bn(e.doc,i.line),n=qn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.line==i.line&&t.ch<=o&&t.ch;return Is(i.line,s?0:o)}return i}function $o(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function Qo(e,t){Ha=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i){if($o(e,n.level,e[i].level)){n.from!=n.to&&(Ha=i);return r}n.from!=n.to&&(Ha=r);return i}i=r}}return i}function Zo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&Ro(e.text.charAt(t)));return t}function Jo(e,t,i,r){var n=qn(e);if(!n)return es(e,t,i,r);for(var o=Qo(n,t),s=n[o],a=Zo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to){if(Qo(n,a)==o)return a;s=n[o+=i];return i>0==s.level%2?s.to:s.from}s=n[o+=i];if(!s)return null;a=i>0==s.level%2?Zo(e,s.to,-1,r):Zo(e,s.from,1,r)}}function es(e,t,i,r){var n=t+i;if(r)for(;n>0&&Ro(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ts=/gecko\/\d/i.test(navigator.userAgent),is=/MSIE \d/.test(navigator.userAgent),rs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),ns=is||rs,os=ns&&(is?document.documentMode||6:rs[1]),ss=/WebKit\//.test(navigator.userAgent),as=ss&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ls=/Chrome\//.test(navigator.userAgent),us=/Opera\//.test(navigator.userAgent),ps=/Apple Computer/.test(navigator.vendor),cs=/KHTML\//.test(navigator.userAgent),ds=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),fs=/PhantomJS/.test(navigator.userAgent),hs=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Es=hs||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),ms=hs||/Mac/.test(navigator.platform),gs=/win/i.test(navigator.platform),vs=us&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);vs&&(vs=Number(vs[1]));if(vs&&vs>=15){us=!1;ss=!0}var xs=ms&&(as||us&&(null==vs||12.11>vs)),Ns=ts||ns&&os>=9,Ts=!1,Ls=!1;E.prototype=yo({update:function(e){var t=e.scrollWidth>e.clientWidth+1,i=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(i){this.vert.style.display="block";this.vert.style.bottom=t?r+"px":"0";var n=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+n)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(t){this.horiz.style.display="block";this.horiz.style.right=i?r+"px":"0";this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(i?r:0);this.horiz.firstChild.style.width=e.scrollWidth-e.clientWidth+o+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedOverlay&&e.clientHeight>0){0==r&&this.overlayHack();this.checkedOverlay=!0}return{right:i?r:0,bottom:t?r:0}},setScrollLeft:function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e)},setScrollTop:function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e)},overlayHack:function(){var e=ms&&!ds?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=e;var t=this,i=function(e){lo(e)!=t.vert&&lo(e)!=t.horiz&&hi(t.cm,Gi)(e)};Ea(this.vert,"mousedown",i);Ea(this.horiz,"mousedown",i)},clear:function(){var e=this.horiz.parentNode;e.removeChild(this.horiz);e.removeChild(this.vert)}},E.prototype);m.prototype=yo({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},m.prototype);e.scrollbarModel={"native":E,"null":m};var Is=e.Pos=function(e,t){if(!(this instanceof Is))return new Is(e,t);this.line=e;this.ch=t},ys=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ys(i.anchor,r.anchor)||0!=ys(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Q(X(this.ranges[t].anchor),X(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ys(t,r.from())>=0&&ys(e,r.to())<=0)return i}return-1}};Q.prototype={from:function(){return K(this.anchor,this.head)},to:function(){return Y(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var As,Ss,Cs,Rs={left:0,right:0,top:0,bottom:0},bs=null,Os=0,Ps=null,Ds=0,ws=0,_s=null;ns?_s=-.53:ts?_s=15:ls?_s=-.7:ps&&(_s=-1/3);var Ms=function(e){var t=e.wheelDeltaX,i=e.wheelDeltaY;null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail);null==i&&e.detail&&e.axis==e.VERTICAL_AXIS?i=e.detail:null==i&&(i=e.wheelDelta);return{x:t,y:i}};e.wheelEventPixels=function(e){var t=Ms(e);t.x*=_s;t.y*=_s;return t};var ks=new go,Gs=null,Bs=e.changeEnd=function(e){return e.text?Is(e.from.line+e.text.length-1,No(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus();Oi(this);Ci(this)},setOption:function(e,t){var i=this.options,r=i[e];if(i[e]!=t||"mode"==e){i[e]=t;Vs.hasOwnProperty(e)&&hi(this,Vs[e])(this,t,r)}},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](wr(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||t[i].name==e){t.splice(i,1);return!0}},addOverlay:Ei(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque});this.state.modeGen++;xi(this)}),removeOverlay:Ei(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e){t.splice(i,1);this.state.modeGen++;xi(this);return}}}),indentLine:Ei(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract");rt(this.doc,e)&&Sr(this,e,t,i)}),indentSelection:Ei(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty()){if(n.head.line>i){Sr(this,n.head.line,e,!0);i=n.head.line;r==this.doc.sel.primIndex&&yr(this)}}else{var o=n.from(),s=n.to(),a=Math.max(i,o.line);i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;i>l;++l)Sr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&&lt(this.doc,r,new Q(o,u[r].to()),Ta)}}}),getTokenAt:function(e,t){return xn(this,e,t)},getLineTokens:function(e,t){return xn(this,Is(e),t,!0)},getTokenTypeAt:function(e){e=tt(this.doc,e);var t,i=Ln(this,Bn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!zs.hasOwnProperty(t))return zs;var r=zs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==To(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;e=et(i,null==e?i.first+i.size-1:e);return Ct(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();i=null==e?r.head:"object"==typeof e?tt(this.doc,e):e?r.from():r.to();return Qt(this,i,t||"page")},charCoords:function(e,t){return $t(this,tt(this.doc,e),t||"page")},coordsChar:function(e,t){e=Kt(this,e,t||"page");return ei(this,e.left,e.top)},lineAtHeight:function(e,t){e=Kt(this,{top:e,left:0},t||"page").top;return jn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;if(e<this.doc.first)e=this.doc.first;else if(e>r){e=r;i=!0}var n=Bn(this.doc,e);return Yt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-Wn(n):0)},defaultTextHeight:function(){return ii(this.display)},defaultCharWidth:function(){return ri(this.display)},setGutterMarker:Ei(function(e,t,i){return Cr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});r[t]=i;!i&&Co(r)&&(e.gutterMarkers=null);return!0})}),clearGutter:Ei(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){if(i.gutterMarkers&&i.gutterMarkers[e]){i.gutterMarkers[e]=null;Ni(t,r,"gutter");Co(i.gutterMarkers)&&(i.gutterMarkers=null)}++r})}),addLineWidget:Ei(function(e,t,i){return fn(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!rt(this.doc,e))return null;var t=e;e=Bn(this.doc,e);if(!e)return null}else{var t=Hn(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Qt(this,tt(this.doc,e));var s=e.bottom,a=e.left;t.style.position="absolute";t.setAttribute("cm-ignore-events","true");o.sizer.appendChild(t);if("over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom);a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px";t.style.left=t.style.right="";if("right"==n){a=o.sizer.clientWidth-t.offsetWidth;t.style.right="0px"}else{"left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2);t.style.left=a+"px"}i&&Tr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Ei(Ji),triggerOnKeyPress:Ei(ir),triggerOnKeyUp:tr,execCommand:function(e){return Ks.hasOwnProperty(e)?Ks[e](this):void 0},findPosH:function(e,t,i,r){var n=1;if(0>t){n=-1;t=-t}for(var o=0,s=tt(this.doc,e);t>o;++o){s=br(this.doc,s,n,i,r);if(s.hitSide)break}return s},moveH:Ei(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?br(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},Ia)}),deleteH:Ei(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):Rr(this,function(i){var n=br(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;if(0>t){n=-1;t=-t}for(var s=0,a=tt(this.doc,e);t>s;++s){var l=Qt(this,a,"div");null==o?o=l.left:l.left=o;a=Or(this,l,n,i);if(a.hitSide)break}return a},moveV:Ei(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Qt(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn);n.push(a.left);var l=Or(i,a,e,t); "page"==t&&s==r.sel.primary()&&Ir(i,null,$t(i,l,"div").top-a.top);return l},Ia);if(n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),findWordAt:function(e){var t=this.doc,i=Bn(t,e.line).text,r=e.ch,n=e.ch;if(i){var o=this.getHelper(e,"wordChars");(e.xRel<0||n==i.length)&&r?--r:++n;for(var s=i.charAt(r),a=So(s,o)?function(e){return So(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!So(e)};r>0&&a(i.charAt(r-1));)--r;for(;n<i.length&&a(i.charAt(n));)++n}return new Q(Is(e.line,r),Is(e.line,n))},toggleOverwrite:function(e){if(null==e||e!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?_a(this.display.cursorDiv,"CodeMirror-overwrite"):wa(this.display.cursorDiv,"CodeMirror-overwrite");ga(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return wo()==this.display.input},scrollTo:Ei(function(e,t){(null!=e||null!=t)&&Ar(this);null!=e&&(this.curOp.scrollLeft=e);null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Pt(this)-this.display.barHeight,width:e.scrollWidth-Pt(this)-this.display.barWidth,clientHeight:wt(this),clientWidth:Dt(this)}},scrollIntoView:Ei(function(e,t){if(null==e){e={from:this.doc.sel.primary().head,to:null};null==t&&(t=this.options.cursorScrollMargin)}else"number"==typeof e?e={from:Is(e,0),to:null}:null==e.from&&(e={from:e,to:null});e.to||(e.to=e.from);e.margin=t||0;if(null!=e.from.line){Ar(this);this.curOp.scrollToPos=e}else{var i=Lr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Ei(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=i(e));null!=t&&(r.display.wrapper.style.height=i(t));r.options.lineWrapping&&Wt(this);var n=r.display.viewFrom;r.doc.iter(n,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){Ni(r,n,"widget");break}++n});r.curOp.forceUpdate=!0;ga(r,"refresh",this)}),operation:function(e){return fi(this,e)},refresh:Ei(function(){var e=this.display.cachedTextHeight;xi(this);this.curOp.forceUpdate=!0;qt(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);p(this);(null==e||Math.abs(e-ii(this.display))>.5)&&s(this);ga(this,"refresh",this)}),swapDoc:Ei(function(e){var t=this.doc;t.cm=null;Gn(this,e);qt(this);bi(this);this.scrollTo(e.scrollLeft,e.scrollTop);this.curOp.forceScroll=!0;po(this,"swapDoc",this,t);return t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};mo(e);var Us=e.defaults={},Vs=e.optionHandlers={},Fs=e.Init={toString:function(){return"CodeMirror.Init"}};Pr("value","",function(e,t){e.setValue(t)},!0);Pr("mode",null,function(e,t){e.doc.modeOption=t;i(e)},!0);Pr("indentUnit",2,i,!0);Pr("indentWithTabs",!1);Pr("smartIndent",!0);Pr("tabSize",4,function(e){r(e);qt(e);xi(e)},!0);Pr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g");e.refresh()},!0);Pr("specialCharPlaceholder",Sn,function(e){e.refresh()},!0);Pr("electricChars",!0);Pr("rtlMoveVisually",!gs);Pr("wholeLineUpdateBefore",!0);Pr("theme","default",function(e){a(e);l(e)},!0);Pr("keyMap","default",function(t,i,r){var n=wr(i),o=r!=e.Init&&wr(r);o&&o.detach&&o.detach(t,n);n.attach&&n.attach(t,o||null)});Pr("extraKeys",null);Pr("lineWrapping",!1,n,!0);Pr("gutters",[],function(e){f(e.options);l(e)},!0);Pr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?y(e.display)+"px":"0";e.refresh()},!0);Pr("coverGutterNextToScrollbar",!1,function(e){v(e)},!0);Pr("scrollbarStyle","native",function(e){g(e);v(e);e.display.scrollbars.setScrollTop(e.doc.scrollTop);e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0);Pr("lineNumbers",!1,function(e){f(e.options);l(e)},!0);Pr("firstLineNumber",1,l,!0);Pr("lineNumberFormatter",function(e){return e},l,!0);Pr("showCursorWhenSelecting",!1,Nt,!0);Pr("resetSelectionOnContextMenu",!0);Pr("readOnly",!1,function(e,t){if("nocursor"==t){nr(e);e.display.input.blur();e.display.disabled=!0}else{e.display.disabled=!1;t||bi(e)}});Pr("disableInput",!1,function(e,t){t||bi(e)},!0);Pr("dragDrop",!0);Pr("cursorBlinkRate",530);Pr("cursorScrollMargin",0);Pr("cursorHeight",1,Nt,!0);Pr("singleCursorHeightPerLine",!0,Nt,!0);Pr("workTime",100);Pr("workDelay",100);Pr("flattenSpans",!0,r,!0);Pr("addModeClass",!1,r,!0);Pr("pollInterval",100);Pr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t});Pr("historyEventDelay",1250);Pr("viewportMargin",10,function(e){e.refresh()},!0);Pr("maxHighlightLength",1e4,r,!0);Pr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)});Pr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""});Pr("autofocus",null);var Hs=e.modes={},js=e.mimeModes={};e.defineMode=function(t,i){e.defaults.mode||"null"==t||(e.defaults.mode=t);arguments.length>2&&(i.dependencies=Array.prototype.slice.call(arguments,2));Hs[t]=i};e.defineMIME=function(e,t){js[e]=t};e.resolveMode=function(t){if("string"==typeof t&&js.hasOwnProperty(t))t=js[t];else if(t&&"string"==typeof t.name&&js.hasOwnProperty(t.name)){var i=js[t.name];"string"==typeof i&&(i={name:i});t=Io(i,t);t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}};e.getMode=function(t,i){var i=e.resolveMode(i),r=Hs[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(Ws.hasOwnProperty(i.name)){var o=Ws[i.name];for(var s in o)if(o.hasOwnProperty(s)){n.hasOwnProperty(s)&&(n["_"+s]=n[s]);n[s]=o[s]}}n.name=i.name;i.helperType&&(n.helperType=i.helperType);if(i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n};e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}});e.defineMIME("text/plain","null");var Ws=e.modeExtensions={};e.extendMode=function(e,t){var i=Ws.hasOwnProperty(e)?Ws[e]:Ws[e]={};yo(t,i)};e.defineExtension=function(t,i){e.prototype[t]=i};e.defineDocExtension=function(e,t){ua.prototype[e]=t};e.defineOption=Pr;var qs=[];e.defineInitHook=function(e){qs.push(e)};var zs=e.helpers={};e.registerHelper=function(t,i,r){zs.hasOwnProperty(t)||(zs[t]=e[t]={_global:[]});zs[t][i]=r};e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n);zs[t]._global.push({pred:r,val:n})};var Xs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([]));i[r]=n}return i},Ys=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state;e=i.mode}return i||{mode:e,state:t}};var Ks=e.commands={selectAll:function(e){e.setSelection(Is(e.firstLine(),0),Is(e.lastLine()),Ta)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),Ta)},killLine:function(e){Rr(e,function(t){if(t.empty()){var i=Bn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:Is(t.head.line+1,0)}:{from:t.head,to:Is(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Rr(e,function(t){return{from:Is(t.from().line,0),to:tt(e.doc,Is(t.to().line+1,0))}})},delLineLeft:function(e){Rr(e,function(e){return{from:Is(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(Is(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(Is(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Xo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Ko(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Yo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},Ia)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},Ia)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return r.ch<e.getLine(r.line).search(/\S/)?Ko(e,t.head):r},Ia)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=ya(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){fi(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=Bn(e.doc,n.line).text;if(o){n.ch==o.length&&(n=new Is(n.line,n.ch-1));if(n.ch>0){n=new Is(n.line,n.ch+1);e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),Is(n.line,n.ch-2),n,"+transpose")}else if(n.line>e.doc.first){var s=Bn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),Is(n.line-1,s.length-1),Is(n.line,1),"+transpose")}}i.push(new Q(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){fi(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input");e.indentLine(r.from().line+1,null,!0);yr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},$s=e.keyMap={};$s.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};$s.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};$s.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};$s.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};$s["default"]=ms?$s.macDefault:$s.pcDefault;e.normalizeKeyMap=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i)){var r=e[i];if(/^(name|fallthrough|(de|at)tach)$/.test(i))continue;if("..."==r){delete e[i];continue}for(var n=Lo(i.split(" "),Dr),o=0;o<n.length;o++){var s,a;if(o==n.length-1){a=i;s=r}else{a=n.slice(0,o+1).join(" ");s="..."}var l=t[a];if(l){if(l!=s)throw new Error("Inconsistent bindings for "+a)}else t[a]=s}delete e[i]}for(var u in t)e[u]=t[u];return e};var Qs=e.lookupKey=function(e,t,i,r){t=wr(t);var n=t.call?t.call(e,r):t[e];if(n===!1)return"nothing";if("..."===n)return"multi";if(null!=n&&i(n))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Qs(e,t.fallthrough,i,r);for(var o=0;o<t.fallthrough.length;o++){var s=Qs(e,t.fallthrough[o],i,r);if(s)return s}}},Zs=e.isModifierKey=function(e){var t="string"==typeof e?e:Fa[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Js=e.keyName=function(e,t){if(us&&34==e.keyCode&&e["char"])return!1;var i=Fa[e.keyCode],r=i;if(null==r||e.altGraphKey)return!1;e.altKey&&"Alt"!=i&&(r="Alt-"+r);(xs?e.metaKey:e.ctrlKey)&&"Ctrl"!=i&&(r="Ctrl-"+r);(xs?e.ctrlKey:e.metaKey)&&"Cmd"!=i&&(r="Cmd-"+r);!t&&e.shiftKey&&"Shift"!=i&&(r="Shift-"+r);return r};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}i||(i={});i.value=t.value;!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex);!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder);if(null==i.autofocus){var n=wo();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form){Ea(t.form,"submit",r);if(!i.leaveSubmitMethodAlone){var o=t.form,s=o.submit;try{var a=o.submit=function(){r();o.submit=s;o.submit();o.submit=a}}catch(l){}}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);u.save=r;u.getTextArea=function(){return t};u.toTextArea=function(){u.toTextArea=isNaN;r();t.parentNode.removeChild(u.getWrapperElement());t.style.display="";if(t.form){ma(t.form,"submit",r);"function"==typeof t.form.submit&&(t.form.submit=s)}};return u};var ea=e.StringStream=function(e,t){this.pos=this.start=0;this.string=e;this.tabSize=t||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};ea.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));if(i){++this.pos;return t}},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1){this.pos=t;return!0}},backUp:function(e){this.pos-=e},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ya(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ya(this.string,null,this.tabSize)-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);if(r&&r.index>0)return null;r&&t!==!1&&(this.pos+=r[0].length);return r}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);if(n(o)==n(e)){t!==!1&&(this.pos+=e.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var ta=e.TextMarker=function(e,t){this.lines=[];this.type=t;this.doc=e};mo(ta);ta.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;t&&ni(e);if(Eo(this,"clear")){var i=this.find();i&&po(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Vr(s.markedSpans,this);if(e&&!this.collapsed)Ni(e,Hn(s),"text");else if(e){null!=a.to&&(n=Hn(s));null!=a.from&&(r=Hn(s))}s.markedSpans=Fr(s.markedSpans,a);null==a.from&&this.collapsed&&!un(this.doc,s)&&e&&Fn(s,ii(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=on(this.lines[o]),u=c(l);if(u>e.display.maxLineLength){e.display.maxLine=l;e.display.maxLineLength=u;e.display.maxLineChanged=!0}}null!=r&&e&&this.collapsed&&xi(e,r,n+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;e&&Et(e.doc)}e&&po(e,"markerCleared",e,this);t&&si(e);this.parent&&this.parent.clear()}};ta.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Vr(o.markedSpans,this);if(null!=s.from){i=Is(t?o:Hn(o),s.from);if(-1==e)return i}if(null!=s.to){r=Is(t?o:Hn(o),s.to);if(1==e)return r}}return i&&{from:i,to:r}};ta.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&fi(i,function(){var r=e.line,n=Hn(e.line),o=Bt(i,n);if(o){jt(o);i.curOp.selectionChanged=i.curOp.forceUpdate=!0}i.curOp.updateMaxLine=!0;if(!un(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=dn(t)-s;a&&Fn(r,r.height+a)}})};ta.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=To(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)};ta.prototype.detachLine=function(e){this.lines.splice(To(this.lines,e),1);if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ia=0,ra=e.SharedTextMarker=function(e,t){this.markers=e;this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};mo(ra);ra.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();po(this,"clear")}};ra.prototype.find=function(e,t){return this.primary.find(e,t)};var na=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e;this.node=t};mo(na);na.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=Hn(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=dn(this);fi(e,function(){cn(e,i,-o);Ni(e,r,"widget");Fn(i,Math.max(0,i.height-o))})}};na.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=dn(this)-e;r&&fi(t,function(){t.curOp.forceUpdate=!0;cn(t,i,r);Fn(i,i.height+r)})};var oa=e.Line=function(e,t,i){this.text=e;$r(this,t);this.height=i?i(this):1};mo(oa);oa.prototype.lineNo=function(){return Hn(this)};var sa={},aa={};_n.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height;En(n);po(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i;this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}};Mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;r.removeInner(e,o);this.height-=s-r.height;if(n==o){this.children.splice(i--,1);r.parent=null}if(0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof _n))){var a=[];this.collapse(a);this.children=[new _n(a)];this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length;this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){n.insertInner(e,t,i);if(n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new _n(s);n.height-=a.height;this.children.splice(r+1,0,a);a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new Mn(t);if(e.parent){e.size-=i.size;e.height-=i.height;var r=To(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new Mn(e.children);n.parent=e;e.children=[n,i];e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var la=0,ua=e.Doc=function(e,t,i){if(!(this instanceof ua))return new ua(e,t,i);null==i&&(i=0);Mn.call(this,[new _n([new oa("",null)])]);this.first=i;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=i;var r=Is(i,0);this.sel=J(r);this.history=new zn(null);this.id=++la;this.modeOption=t;"string"==typeof e&&(e=Ga(e));wn(this,{from:r,to:r,text:e});dt(this,J(r),Ta)};ua.prototype=Io(Mn.prototype,{constructor:ua,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Vn(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:mi(function(e){var t=Is(this.first,0),i=this.first+this.size-1;dr(this,{from:t,to:Is(i,Bn(this,i).text.length),text:Ga(e),origin:"setValue",full:!0},!0);dt(this,J(t))}),replaceRange:function(e,t,i,r){t=tt(this,t);i=i?tt(this,i):t;vr(this,e,t,i,r)},getRange:function(e,t,i){var r=Un(this,tt(this,e),tt(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return rt(this,e)?Bn(this,e):void 0},getLineNumber:function(e){return Hn(e)},getLineHandleVisualStart:function(e){"number"==typeof e&&(e=Bn(this,e));return on(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return tt(this,e)},getCursor:function(e){var t,i=this.sel.primary();t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:mi(function(e,t,i){ut(this,tt(this,"number"==typeof e?Is(e,t||0):e),null,i)}),setSelection:mi(function(e,t,i){ut(this,tt(this,e),tt(this,t||e),i)}),extendSelection:mi(function(e,t,i){st(this,tt(this,e),t&&tt(this,t),i)}),extendSelections:mi(function(e,t){at(this,nt(this,e,t))}),extendSelectionsBy:mi(function(e,t){at(this,Lo(this.sel.ranges,e),t)}),setSelections:mi(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new Q(tt(this,e[r].anchor),tt(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex));dt(this,Z(n,t),i)}}),addSelection:mi(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new Q(tt(this,e),tt(this,t||e)));dt(this,Z(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n"));t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:mi(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:Ga(e[o]),origin:i}}for(var a=t&&"end"!=t&&pr(this,r,t),o=r.length-1;o>=0;o--)dr(this,r[o]);a?ct(this,a):this.cm&&yr(this.cm)}),undo:mi(function(){hr(this,"undo")}),redo:mi(function(){hr(this,"redo")}),undoSelection:mi(function(){hr(this,"undo",!0)}),redoSelection:mi(function(){hr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new zn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:ro(this.history.done),undone:ro(this.history.undone)}},setHistory:function(e){var t=this.history=new zn(this.history.maxGeneration);t.done=ro(e.done.slice(0),null,!0);t.undone=ro(e.undone.slice(0),null,!0)},addLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(_o(i).test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(_o(i));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),markText:function(e,t,i){return _r(this,tt(this,e),tt(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};e=tt(this,e);return _r(this,e,e,i,"bookmark")},findMarksAt:function(e){e=tt(this,e);var t=[],i=Bn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=tt(this,e);t=tt(this,t);var r=[],n=e.line;this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n});return r},getAllMarks:function(){var e=[];this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)});return e},posFromIndex:function(e){var t,i=this.first;this.iter(function(r){var n=r.text.length+1;if(n>e){t=e;return!0}e-=n;++i});return tt(this,Is(i,t))},indexFromPos:function(e){e=tt(this,e);var t=e.ch;if(e.line<this.first||e.ch<0)return 0;this.iter(this.first,e.line,function(e){t+=e.text.length+1});return t},copy:function(e){var t=new ua(Vn(this,this.first,this.first+this.size),this.modeOption,this.first);t.scrollTop=this.scrollTop;t.scrollLeft=this.scrollLeft;t.sel=this.sel;t.extend=!1;if(e){t.history.undoDepth=this.history.undoDepth;t.setHistory(this.getHistory())}return t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from);null!=e.to&&e.to<i&&(i=e.to);var r=new ua(Vn(this,t,i),e.mode||this.modeOption,t);e.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}];Gr(r,kr(this));return r},unlinkDoc:function(t){t instanceof e&&(t=t.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1);t.unlinkDoc(this);Br(kr(this));break}}if(t.history==this.history){var n=[t.id];kn(t,function(e){n.push(e.id)},!0);t.history=new zn(null);t.history.done=ro(this.history.done,n);t.history.undone=ro(this.history.undone,n)}},iterLinkedDocs:function(e){kn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});ua.prototype.eachLine=ua.prototype.iter;var pa="iter insert remove copy getEditor".split(" ");for(var ca in ua.prototype)ua.prototype.hasOwnProperty(ca)&&To(pa,ca)<0&&(e.prototype[ca]=function(e){return function(){return e.apply(this.doc,arguments)}}(ua.prototype[ca]));mo(ua);var da=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},fa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ha=e.e_stop=function(e){da(e);fa(e)},Ea=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},ma=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},ga=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},va=null,xa=30,Na=e.Pass={toString:function(){return"CodeMirror.Pass"}},Ta={scroll:!1},La={origin:"*mouse"},Ia={origin:"+move"};go.prototype.set=function(e,t){clearTimeout(this.id);this.id=setTimeout(t,e)};var ya=e.countColumn=function(e,t,i,r,n){if(null==t){t=e.search(/[^\s\u00a0]/);-1==t&&(t=e.length)}for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o;s+=i-s%i;o=a+1}},Aa=[""],Sa=function(e){e.select()};hs?Sa=function(e){e.selectionStart=0;e.selectionEnd=e.value.length}:ns&&(Sa=function(e){try{e.select()}catch(t){}});var Ca,Ra=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ba=e.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Ra.test(e))},Oa=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; Ca=document.createRange?function(e,t,i){var r=document.createRange();r.setEnd(e,i);r.setStart(e,t);return r}:function(e,t,i){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(n){return r}r.collapse(!0);r.moveEnd("character",i);r.moveStart("character",t);return r};ns&&11>os&&(wo=function(){try{return document.activeElement}catch(e){return document.body}});var Pa,Da,wa=e.rmClass=function(e,t){var i=e.className,r=_o(t).exec(i);if(r){var n=i.slice(r.index+r[0].length);e.className=i.slice(0,r.index)+(n?r[1]+n:"")}},_a=e.addClass=function(e,t){var i=e.className;_o(t).test(i)||(e.className+=(i?" ":"")+t)},Ma=!1,ka=function(){if(ns&&9>os)return!1;var e=bo("div");return"draggable"in e||"dragDrop"in e}(),Ga=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");if(-1!=s){i.push(o.slice(0,s));t+=s+1}else{i.push(o);t=n+1}}return i}:function(e){return e.split(/\r\n?|\n/)},Ba=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Ua=function(){var e=bo("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),Va=null,Fa={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=Fa;(function(){for(var e=0;10>e;e++)Fa[e+48]=Fa[e+96]=String(e);for(var e=65;90>=e;e++)Fa[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Fa[e+111]=Fa[e+63235]="F"+e})();var Ha,ja=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e;this.from=t;this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,f=u;p>d;++d){var r=c[d];"m"==r?c[d]=f:f=r}for(var d=0,h=u;p>d;++d){var r=c[d];if("1"==r&&"r"==h)c[d]="n";else if(s.test(r)){h=r;"r"==r&&(c[d]="R")}}for(var d=1,f=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==f&&"1"==c[d+1]?c[d]="1":","!=r||f!=c[d+1]||"1"!=f&&"n"!=f||(c[d]=f);f=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var E=d+1;p>E&&"%"==c[E];++E);for(var m=d&&"!"==c[d-1]||p>E&&"1"==c[E]?"1":"N",g=d;E>g;++g)c[g]=m;d=E-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var E=d+1;p>E&&o.test(c[E]);++E);for(var v="L"==(d?c[d-1]:u),x="L"==(p>E?c[E]:u),m=v||x?"L":"R",g=d;E>g;++g)c[g]=m;d=E-1}for(var N,T=[],d=0;p>d;)if(a.test(c[d])){var L=d;for(++d;p>d&&a.test(c[d]);++d);T.push(new t(0,L,d))}else{var I=d,y=T.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&T.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);T.splice(y,0,new t(2,A,g));I=g}else++g;d>I&&T.splice(y,0,new t(1,I,d))}if(1==T[0].level&&(N=i.match(/^\s+/))){T[0].from=N[0].length;T.unshift(new t(0,0,N[0].length))}if(1==No(T).level&&(N=i.match(/\s+$/))){No(T).to-=N[0].length;T.push(new t(0,p-N[0].length,p))}T[0].level!=No(T).level&&T.push(new t(T[0].level,p,p));return T}}();e.version="4.12.0";return e})},{}],15:[function(t,i){(function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)})("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(ft.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Tt[e]={};ot.each(e.match(Nt)||[],function(e,i){t[i]=!0});return t}function a(){if(Et.addEventListener){Et.removeEventListener("DOMContentLoaded",l,!1);t.removeEventListener("load",l,!1)}else{Et.detachEvent("onreadystatechange",l);t.detachEvent("onload",l)}}function l(){if(Et.addEventListener||"load"===event.type||"complete"===Et.readyState){a();ot.ready()}}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();i=e.getAttribute(r);if("string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t){u||(u=a?e[s]=K.pop()||ot.guid++:s);l[u]||(l[u]=a?{}:{toJSON:ot.noop});("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==i&&(o[ot.camelCase(t)]=i);if("string"==typeof t){n=o[t];null==n&&(n=o[ot.camelCase(t)])}else n=o;return n}}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t){r=i?s[a]:s[a].data;if(r){if(ot.isArray(t))t=t.concat(ot.map(t,ot.camelCase));else if(t in r)t=[t];else{t=ot.camelCase(t);t=t in r?[t]:t.split(" ")}n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}}if(!i){delete s[a].data;if(!p(s[a]))return}o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null}}}function f(){return!0}function h(){return!1}function E(){try{return Et.activeElement}catch(e){}}function m(e){var t=Gt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type;return e}function T(e){var t=Yt.exec(e.type);t?e.type=t[1]:e.removeAttribute("type");return e}function L(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle;s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){i=t.nodeName.toLowerCase();if(!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}if("script"===i&&t.text!==e.text){N(t).text=e.text;T(t)}else if("object"===i){t.parentNode&&(t.outerHTML=e.outerHTML);rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)}else if("input"===i&&Pt.test(e.type)){t.defaultChecked=t.checked=e.checked;t.value!==e.value&&(t.value=e.value)}else"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");n.detach();return o}function S(e){var t=Et,i=ei[e];if(!i){i=A(e,t);if("none"===i||!i){Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement);t=(Jt[0].contentWindow||Jt[0].contentDocument).document;t.write();t.close();i=A(e,t);Jt.detach()}ei[e]=i}return i}function C(e,t){return{get:function(){var i=e();if(null!=i){if(!i)return(this.get=t).apply(this,arguments);delete this.get}}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=fi.length;n--;){t=fi[n]+i;if(t in e)return t}return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++){r=e[s];if(r.style){o[s]=ot._data(r,"olddisplay");i=r.style.display;if(t){o[s]||"none"!==i||(r.style.display="");""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))}else{n=bt(r);(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))}}}for(s=0;a>s;s++){r=e[s];r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"))}return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2){"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n));if(r){"content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n));"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))}else{s+=ot.css(e,"padding"+Rt[o],!0,n);"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n))}}return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){n=ii(e,t,o);(0>n||null==n)&&(n=e.style[t]);if(ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]);n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function w(e,t,i,r,n){return new w.prototype.init(e,t,i,r,n)}function _(){setTimeout(function(){hi=void 0});return hi=ot.now()}function M(e,t){var i,r={height:e},n=0;t=t?1:0;for(;4>n;n+=2-t){i=Rt[n];r["margin"+i]=r["padding"+i]=e}t&&(r.opacity=r.width=e);return r}function k(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function G(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},f=e.style,h=e.nodeType&&bt(e),E=ot._data(e,"fxshow");if(!i.queue){a=ot._queueHooks(e,"fx");if(null==a.unqueued){a.unqueued=0;l=a.empty.fire;a.empty.fire=function(){a.unqueued||l()}}a.unqueued++;c.always(function(){c.always(function(){a.unqueued--;ot.queue(e,"fx").length||a.empty.fire()})})}if(1===e.nodeType&&("height"in t||"width"in t)){i.overflow=[f.overflow,f.overflowX,f.overflowY];u=ot.css(e,"display");p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u;"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?f.zoom=1:f.display="inline-block")}if(i.overflow){f.overflow="hidden";rt.shrinkWrapBlocks()||c.always(function(){f.overflow=i.overflow[0];f.overflowX=i.overflow[1];f.overflowY=i.overflow[2]})}for(r in t){n=t[r];if(mi.exec(n)){delete t[r];o=o||"toggle"===n;if(n===(h?"hide":"show")){if("show"!==n||!E||void 0===E[r])continue;h=!0}d[r]=E&&E[r]||ot.style(e,r)}else u=void 0}if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(f.display=u);else{E?"hidden"in E&&(h=E.hidden):E=ot._data(e,"fxshow",{});o&&(E.hidden=!h);h?ot(e).show():c.done(function(){ot(e).hide()});c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d){s=k(h?E[r]:0,r,c);if(!(r in E)){E[r]=s.start;if(h){s.end=s.start;s.start="width"===r||"height"===r?1:0}}}}}function B(e,t){var i,r,n,o,s;for(i in e){r=ot.camelCase(i);n=t[r];o=e[i];if(ot.isArray(o)){n=o[1];o=e[i]=o[0]}if(i!==r){e[r]=o;delete e[i]}s=ot.cssHooks[r];if(s&&"expand"in s){o=s.expand(o);delete e[r];for(i in o)if(!(i in e)){e[i]=o[i];t[i]=n}}else t[r]=n}}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||_(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);a.notifyWith(e,[u,o,i]);if(1>o&&l)return i;a.resolveWith(e,[u]);return!1},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||_(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);u.tweens.push(r);return r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;n=!0;for(;r>i;i++)u.tweens[i].run(1);t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]);return this}}),p=u.props;B(p,u.opts.specialEasing);for(;s>o;o++){r=xi[o].call(u,e,p,u.opts);if(r)return r}ot.map(p,k,u);ot.isFunction(u.opts.start)&&u.opts.start.call(e,u);ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){if("string"!=typeof t){i=t;t="*"}var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(e[r]=e[r]||[]).unshift(i)}else(e[r]=e[r]||[]).push(i)}}function F(e,t,i,r){function n(a){var l;o[a]=!0;ot.each(e[a]||[],function(e,a){var u=a(t,i,r);if("string"==typeof u&&!s&&!o[u]){t.dataTypes.unshift(u);n(u);return!1}return s?!(l=u):void 0});return l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function H(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);i&&ot.extend(!0,e,i);return e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];){l.shift();void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"))}if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return i[o]}}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];o=p.shift();for(;o;){e.responseFields[o]&&(i[e.responseFields[o]]=t);!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType));l=o;o=p.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){s=u[l+" "+o]||u["* "+o];if(!s)for(n in u){a=n.split(" ");if(a[1]===o){s=u[l+" "+a[0]]||u["* "+a[0]];if(s){if(s===!0)s=u[n];else if(u[n]!==!0){o=a[0];p.unshift(a[1])}break}}}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.2",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);t.prevObject=this;t.context=this.context;return t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice};ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;if("boolean"==typeof s){u=s;s=arguments[a]||{};a++}"object"==typeof s||ot.isFunction(s)||(s={});if(a===l){s=this;a--}for(;l>a;a++)if(null!=(n=arguments[a]))for(r in n){e=s[r];i=n[r];if(s!==i)if(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))){if(t){t=!1;o=e&&ot.isArray(e)?e:[]}else o=e&&ot.isPlainObject(e)?e:{};s[r]=ot.extend(u,o,i)}else void 0!==i&&(s[r]=i)}return s};ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i)if(a)for(;s>o;o++){n=t.apply(e[o],i);if(n===!1)break}else for(o in e){n=t.apply(e[o],i);if(n===!1)break}else if(a)for(;s>o;o++){n=t.call(e[o],o,e[o]);if(n===!1)break}else for(o in e){n=t.call(e[o],o,e[o]);if(n===!1)break}return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e));return i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);r=t.length;i=i?0>i?Math.max(0,r+i):i:0;for(;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++];if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];e.length=n;return e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++){r=!t(e[o],o);r!==a&&n.push(e[o])}return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++){n=t(e[o],o,i);null!=n&&l.push(n)}else for(o in e){n=t(e[o],o,i);null!=n&&l.push(n)}return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;if("string"==typeof t){n=e[t];t=e;e=n}if(!ot.isFunction(e))return void 0;i=$.call(arguments,2);r=function(){return e.apply(t||this,i.concat($.call(arguments)))};r.guid=e.guid=e.guid||ot.guid++;return r},now:function(){return+new Date},support:rt});ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,f,h,E;(t?t.ownerDocument||t:V)!==D&&P(t);t=t||D;i=i||[];a=t.nodeType;if("string"!=typeof e||!e||1!==a&&9!==a&&11!==a)return i;if(!r&&_){if(11!==a&&(n=vt.exec(e)))if(s=n[1]){if(9===a){o=t.getElementById(s);if(!o||!o.parentNode)return i;if(o.id===s){i.push(o);return i}}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s){i.push(o);return i}}else{if(n[2]){Z.apply(i,t.getElementsByTagName(e));return i}if((s=n[3])&&T.getElementsByClassName){Z.apply(i,t.getElementsByClassName(s));return i}}if(T.qsa&&(!M||!M.test(e))){f=c=U;h=t;E=1!==a&&e;if(1===a&&"object"!==t.nodeName.toLowerCase()){u=A(e);(c=t.getAttribute("id"))?f=c.replace(Nt,"\\$&"):t.setAttribute("id",f);f="[id='"+f+"'] ";l=u.length;for(;l--;)u[l]=f+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t;E=u.join(",")}if(E)try{Z.apply(i,h.querySelectorAll(E));return i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){t.push(i+" ")>L.cacheLength&&delete e[t.shift()];return e[i+" "]=r}var t=[];return e}function r(e){e[U]=!0;return e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)L.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||X)-(~e.sourceIndex||X);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){t=+t;return r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function f(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=H++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[F,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){l=t[U]||(t[U]={});if((a=l[r])&&a[0]===F&&a[1]===o)return u[2]=a[2];l[r]=u;if(u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function E(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)if((o=e[a])&&(!i||i(o,r,n))){s.push(o);u&&t.push(a)}return s}function g(e,t,i,n,o,s){n&&!n[U]&&(n=g(n));o&&!o[U]&&(o=g(o,s));return r(function(r,s,a,l){var u,p,c,d=[],f=[],h=s.length,g=r||E(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;i&&i(v,x,a,l);if(n){u=m(x,f);n(u,[],a,l);p=u.length;for(;p--;)(c=u[p])&&(x[f[p]]=!(v[f[p]]=c))}if(r){if(o||e){if(o){u=[];p=x.length;for(;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}p=x.length;for(;p--;)(c=x[p])&&(u=o?et(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else{x=m(x===s?x.splice(h,x.length):x);o?o(null,s,x,l):Z.apply(s,x)}})}function v(e){for(var t,i,r,n=e.length,o=L.relative[e[0].type],s=o||L.relative[" "],a=o?1:0,l=f(function(e){return e===t},s,!0),u=f(function(e){return et(t,e)>-1},s,!0),p=[function(e,i,r){var n=!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r));t=null;return n}];n>a;a++)if(i=L.relative[e[a].type])p=[f(h(p),i)];else{i=L.filter[e[a].type].apply(null,e[a].matches);if(i[U]){r=++a;for(;n>r&&!L.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,f=0,h="0",E=r&&[],g=[],v=R,x=r||o&&L.find.TAG("*",u),N=F+=null==v?1:Math.random()||.1,T=x.length;u&&(R=s!==D&&s);for(;h!==T&&null!=(p=x[h]);h++){if(o&&p){c=0;for(;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(F=N)}if(n){(p=!d&&p)&&f--;r&&E.push(p)}}f+=h;if(n&&h!==f){c=0;for(;d=i[c++];)d(E,g,s,a);if(r){if(f>0)for(;h--;)E[h]||g[h]||(g[h]=$.call(l));g=m(g)}Z.apply(l,g);u&&!r&&g.length>0&&f+i.length>1&&t.uniqueSort(l)}if(u){F=N;R=v}return E};return n?r(s):s}var N,T,L,I,y,A,S,C,R,b,O,P,D,w,_,M,k,G,B,U="sizzle"+1*new Date,V=e.document,F=0,H=0,j=i(),W=i(),q=i(),z=function(e,t){e===t&&(O=!0);return 0},X=1<<31,Y={}.hasOwnProperty,K=[],$=K.pop,Q=K.push,Z=K.push,J=K.slice,et=function(e,t){for(var i=0,r=e.length;r>i;i++)if(e[i]===t)return i;return-1},tt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",it="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=rt.replace("w","w#"),ot="\\["+it+"*("+rt+")(?:"+it+"*([*^$|!~]?=)"+it+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+nt+"))|)"+it+"*\\]",st=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ot+")*)|.*)\\)|)",at=new RegExp(it+"+","g"),lt=new RegExp("^"+it+"+|((?:^|[^\\\\])(?:\\\\.)*)"+it+"+$","g"),ut=new RegExp("^"+it+"*,"+it+"*"),pt=new RegExp("^"+it+"*([>+~]|"+it+")"+it+"*"),ct=new RegExp("="+it+"*([^\\]'\"]*?)"+it+"*\\]","g"),dt=new RegExp(st),ft=new RegExp("^"+nt+"$"),ht={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt.replace("w","w*")+")"),ATTR:new RegExp("^"+ot),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+it+"*(even|odd|(([+-]|)(\\d*)n|)"+it+"*(?:([+-]|)"+it+"*(\\d+)|))"+it+"*\\)|)","i"),bool:new RegExp("^(?:"+tt+")$","i"),needsContext:new RegExp("^"+it+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+it+"*((?:-\\d)?\\d*)"+it+"*\\)|)(?=[^-]|$)","i")},Et=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Tt=new RegExp("\\\\([\\da-f]{1,6}"+it+"?|("+it+")|.)","ig"),Lt=function(e,t,i){var r="0x"+t-65536;return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},It=function(){P()};try{Z.apply(K=J.call(V.childNodes),V.childNodes);K[V.childNodes.length].nodeType}catch(yt){Z={apply:K.length?function(e,t){Q.apply(e,J.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}T=t.support={};y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1};P=t.setDocument=function(e){var t,i,r=e?e.ownerDocument||e:V;if(r===D||9!==r.nodeType||!r.documentElement)return D;D=r;w=r.documentElement;i=r.defaultView;i&&i!==i.top&&(i.addEventListener?i.addEventListener("unload",It,!1):i.attachEvent&&i.attachEvent("onunload",It));_=!y(r);T.attributes=n(function(e){e.className="i";return!e.getAttribute("className")});T.getElementsByTagName=n(function(e){e.appendChild(r.createComment(""));return!e.getElementsByTagName("*").length});T.getElementsByClassName=gt.test(r.getElementsByClassName);T.getById=n(function(e){w.appendChild(e).id=U;return!r.getElementsByName||!r.getElementsByName(U).length});if(T.getById){L.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}};L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){return e.getAttribute("id")===t}}}else{delete L.find.ID;L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){var i="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return i&&i.value===t}}}L.find.TAG=T.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):T.qsa?t.querySelectorAll(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o};L.find.CLASS=T.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0};k=[];M=[];if(T.qsa=gt.test(r.querySelectorAll)){n(function(e){w.appendChild(e).innerHTML="<a id='"+U+"'></a><select id='"+U+"-\f]' msallowcapture=''><option selected=''></option></select>";e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+it+"*(?:''|\"\")");e.querySelectorAll("[selected]").length||M.push("\\["+it+"*(?:value|"+tt+")");e.querySelectorAll("[id~="+U+"-]").length||M.push("~=");e.querySelectorAll(":checked").length||M.push(":checked");e.querySelectorAll("a#"+U+"+*").length||M.push(".#.+[+~]")});n(function(e){var t=r.createElement("input");t.setAttribute("type","hidden");e.appendChild(t).setAttribute("name","D");e.querySelectorAll("[name=d]").length&&M.push("name"+it+"*[*^$|!~]?=");e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled");e.querySelectorAll("*,:x");M.push(",.*:")})}(T.matchesSelector=gt.test(G=w.matches||w.webkitMatchesSelector||w.mozMatchesSelector||w.oMatchesSelector||w.msMatchesSelector))&&n(function(e){T.disconnectedMatch=G.call(e,"div");G.call(e,"[s!='']:x");k.push("!=",st)});M=M.length&&new RegExp(M.join("|"));k=k.length&&new RegExp(k.join("|"));t=gt.test(w.compareDocumentPosition);B=t||gt.test(w.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1};z=t?function(e,t){if(e===t){O=!0;return 0}var i=!e.compareDocumentPosition-!t.compareDocumentPosition;if(i)return i;i=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1;return 1&i||!T.sortDetached&&t.compareDocumentPosition(e)===i?e===r||e.ownerDocument===V&&B(V,e)?-1:t===r||t.ownerDocument===V&&B(V,t)?1:b?et(b,e)-et(b,t):0:4&i?-1:1}:function(e,t){if(e===t){O=!0;return 0}var i,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:b?et(b,e)-et(b,t):0;if(o===a)return s(e,t);i=e;for(;i=i.parentNode;)l.unshift(i);i=t;for(;i=i.parentNode;)u.unshift(i);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0};return r};t.matches=function(e,i){return t(e,null,null,i)};t.matchesSelector=function(e,i){(e.ownerDocument||e)!==D&&P(e);i=i.replace(ct,"='$1']");if(!(!T.matchesSelector||!_||k&&k.test(i)||M&&M.test(i)))try{var r=G.call(e,i);if(r||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0};t.contains=function(e,t){(e.ownerDocument||e)!==D&&P(e);return B(e,t)};t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=L.attrHandle[t.toLowerCase()],r=i&&Y.call(L.attrHandle,t.toLowerCase())?i(e,t,!_):void 0;return void 0!==r?r:T.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null};t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};t.uniqueSort=function(e){var t,i=[],r=0,n=0;O=!T.detectDuplicates;b=!T.sortStable&&e.slice(0);e.sort(z);if(O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}b=null;return e};I=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=I(t);return i};L=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(Tt,Lt);e[3]=(e[3]||e[4]||e[5]||"").replace(Tt,Lt);"~="===e[2]&&(e[3]=" "+e[3]+" ");return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if("nth"===e[1].slice(0,3)){e[3]||t.error(e[0]);e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3]));e[5]=+(e[7]+e[8]||"odd"===e[3])}else e[3]&&t.error(e[0]);return e},PSEUDO:function(e){var t,i=!e[6]&&e[2]; if(ht.CHILD.test(e[0]))return null;if(e[3])e[2]=e[4]||e[5]||"";else if(i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)){e[0]=e[0].slice(0,t);e[2]=i.slice(0,t)}return e.slice(0,3)}},filter:{TAG:function(e){var t=e.replace(Tt,Lt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+it+")"+e+"("+it+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);if(null==o)return"!="===i;if(!i)return!0;o+="";return"="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,f,h,E=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;E;){c=t;for(;c=c[E];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=E="only"===e&&!h&&"nextSibling"}return!0}h=[s?m.firstChild:m.lastChild];if(s&&v){p=m[U]||(m[U]={});u=p[e]||[];f=u[0]===F&&u[1];d=u[0]===F&&u[2];c=f&&m.childNodes[f];for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[F,f,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===F)d=u[1];else for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if((a?c.nodeName.toLowerCase()===g:1===c.nodeType)&&++d){v&&((c[U]||(c[U]={}))[e]=[F,d]);if(c===t)break}d-=n;return d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=L.pseudos[e]||L.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);if(o[U])return o(i);if(o.length>1){n=[e,e,"",i];return L.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;){r=et(e,n[s]);e[r]=!(t[r]=n[s])}}):function(e){return o(e,0,n)}}return o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){t[0]=e;n(t,null,o,i);t[0]=null;return!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){e=e.replace(Tt,Lt);return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:r(function(e){ft.test(e||"")||t.error("unsupported lang: "+e);e=e.replace(Tt,Lt).toLowerCase();return function(t){var i;do if(i=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang")){i=i.toLowerCase();return i===e||0===i.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===w},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){e.parentNode&&e.parentNode.selectedIndex;return e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!L.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return Et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}};L.pseudos.nth=L.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})L.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})L.pseudos[N]=l(N);c.prototype=L.filters=L.pseudos;L.setFilters=new c;A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);a=e;l=[];u=L.preFilter;for(;a;){if(!r||(n=ut.exec(a))){n&&(a=a.slice(n[0].length)||a);l.push(o=[])}r=!1;if(n=pt.exec(a)){r=n.shift();o.push({value:r,type:n[0].replace(lt," ")});a=a.slice(r.length)}for(s in L.filter)if((n=ht[s].exec(a))&&(!u[s]||(n=u[s](n)))){r=n.shift();o.push({value:r,type:s,matches:n});a=a.slice(r.length)}if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)};S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){t||(t=A(e));i=t.length;for(;i--;){o=v(t[i]);o[U]?r.push(o):n.push(o)}o=q(e,x(n,r));o.selector=e}return o};C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);i=i||[];if(1===c.length){o=c[0]=c[0].slice(0);if(o.length>2&&"ID"===(s=o[0]).type&&T.getById&&9===t.nodeType&&_&&L.relative[o[1].type]){t=(L.find.ID(s.matches[0].replace(Tt,Lt),t)||[])[0];if(!t)return i;u&&(t=t.parentNode);e=e.slice(o.shift().value.length)}n=ht.needsContext.test(e)?0:o.length;for(;n--;){s=o[n];if(L.relative[a=s.type])break;if((l=L.find[a])&&(r=l(s.matches[0].replace(Tt,Lt),xt.test(o[0].type)&&p(t.parentNode)||t))){o.splice(n,1);e=r.length&&d(o);if(!e){Z.apply(i,r);return i}break}}}(u||S(e,c))(r,t,!_,i,xt.test(e)&&p(t.parentNode)||t);return i};T.sortStable=U.split("").sort(z).join("")===U;T.detectDuplicates=!!O;P();T.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))});n(function(e){e.innerHTML="<a href='#'></a>";return"#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)});T.attributes&&n(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue});n(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});return t}(t);ot.find=pt;ot.expr=pt.selectors;ot.expr[":"]=ot.expr.pseudos;ot.unique=pt.uniqueSort;ot.text=pt.getText;ot.isXMLDoc=pt.isXML;ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];i&&(e=":not("+e+")");return 1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))};ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);i=this.pushStack(n>1?ot.unique(i):i);i.selector=this.selector?this.selector+" "+e:e;return i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,Et=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e);if(!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){t=t instanceof ot?t[0]:t;ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:Et,!0));if(dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}r=Et.getElementById(i[2]);if(r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1;this[0]=r}this.context=Et;this.selector=e;return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(ot.isFunction(e))return"undefined"!=typeof ht.ready?ht.ready(e):e(ot);if(void 0!==e.selector){this.selector=e.selector;this.context=e.context}return ot.makeArray(e,this)};gt.prototype=ot.fn;ht=ot(Et);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));){1===n.nodeType&&r.push(n);n=n[t]}return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}});ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);"Until"!==e.slice(-5)&&(r=i);r&&"string"==typeof r&&(n=ot.filter(r,n));if(this.length>1){xt[e]||(n=ot.unique(n));vt.test(e)&&(n=n.reverse())}return this.pushStack(n)}});var Nt=/\S+/g,Tt={};ot.Callbacks=function(e){e="string"==typeof e?Tt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){i=e.memory&&s;r=!0;o=a||0;a=0;n=l.length;t=!0;for(;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1;l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;(function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})})(arguments);if(t)n=l.length;else if(i){a=r;p(i)}}return this},remove:function(){l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;){l.splice(r,1);if(t){n>=r&&n--;o>=r&&o--}}});return this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){l=[];n=0;return this},disable:function(){l=u=i=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;i||c.disable();return this},locked:function(){return!u},fireWith:function(e,i){if(l&&(!r||u)){i=i||[];i=[e,i.slice?i.slice():i];t?u.push(i):p(i)}return this},fire:function(){c.fireWith(this,arguments);return this},fired:function(){return!!r}};return c};ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){n.done(arguments).fail(arguments);return this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})});e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};r.pipe=r.then;ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add;a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock);n[o[0]]=function(){n[o[0]+"With"](this===n?r:this,arguments);return this};n[o[0]+"With"]=s.fireWith});r.promise(n);e&&e.call(n,n);return n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this;r[e]=arguments.length>1?$.call(arguments):n;r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1){t=new Array(s);i=new Array(s);r=new Array(s);for(;s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a}a||l.resolveWith(r,o);return l.promise()}});var Lt;ot.fn.ready=function(e){ot.ready.promise().done(e);return this};ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!Et.body)return setTimeout(ot.ready);ot.isReady=!0;if(!(e!==!0&&--ot.readyWait>0)){Lt.resolveWith(Et,[ot]);if(ot.fn.triggerHandler){ot(Et).triggerHandler("ready");ot(Et).off("ready")}}}}});ot.ready.promise=function(e){if(!Lt){Lt=ot.Deferred();if("complete"===Et.readyState)setTimeout(ot.ready);else if(Et.addEventListener){Et.addEventListener("DOMContentLoaded",l,!1);t.addEventListener("load",l,!1)}else{Et.attachEvent("onreadystatechange",l);t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&Et.documentElement}catch(r){}i&&i.doScroll&&function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a();ot.ready()}}()}}return Lt.promise(e)};var It,yt="undefined";for(It in ot(rt))break;rt.ownLast="0"!==It;rt.inlineBlockNeedsLayout=!1;ot(function(){var e,t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";rt.inlineBlockNeedsLayout=e=3===t.offsetWidth;e&&(i.style.zoom=1)}i.removeChild(r)}});(function(){var e=Et.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null})();ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando];return!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}});ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length){n=ot.data(o);if(1===o.nodeType&&!ot._data(o,"parsedAttrs")){i=s.length;for(;i--;)if(s[i]){r=s[i].name;if(0===r.indexOf("data-")){r=ot.camelCase(r.slice(5));u(o,r,n[r])}}ot._data(o,"parsedAttrs",!0)}}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}});ot.extend({queue:function(e,t,i){var r;if(e){t=(t||"fx")+"queue";r=ot._data(e,t);i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i));return r||[]}},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};if("inprogress"===n){n=i.shift();r--}if(n){"fx"===t&&i.unshift("inprogress");delete o.stop;n.call(e,s,o)}!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue");ot._removeData(e,i)})})}});ot.fn.extend({queue:function(e,t){var i=2;if("string"!=typeof e){t=e;e="fx";i--}return arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e);"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};if("string"!=typeof e){t=e;e=void 0}e=e||"fx";for(;s--;){i=ot._data(o[s],e+"queueHooks");if(i&&i.empty){r++;i.empty.add(a)}}a();return n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){e=t||e;return"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r){n=!0;ot.isFunction(r)||(s=!0);if(u)if(s){t.call(e,r);t=null}else{u=t;t=function(e,t,i){return u.call(ot(e),i)}}if(t)for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)))}return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;(function(){var e=Et.createElement("input"),t=Et.createElement("div"),i=Et.createDocumentFragment();t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";rt.leadingWhitespace=3===t.firstChild.nodeType;rt.tbody=!t.getElementsByTagName("tbody").length;rt.htmlSerialize=!!t.getElementsByTagName("link").length;rt.html5Clone="<:nav></:nav>"!==Et.createElement("nav").cloneNode(!0).outerHTML;e.type="checkbox";e.checked=!0;i.appendChild(e);rt.appendChecked=e.checked;t.innerHTML="<textarea>x</textarea>";rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue;i.appendChild(t);t.innerHTML="<input type='radio' checked='checked' name='t'/>";rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked;rt.noCloneEvent=!0;if(t.attachEvent){t.attachEvent("onclick",function(){rt.noCloneEvent=!1});t.cloneNode(!0).click()}if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}})();(function(){var e,i,r=Et.createElement("div");for(e in{submit:!0,change:!0,focusin:!0}){i="on"+e;if(!(rt[e+"Bubbles"]=i in t)){r.setAttribute(i,"t");rt[e+"Bubbles"]=r.attributes[i].expando===!1}}r=null})();var Dt=/^(?:input|select|textarea)$/i,wt=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,Mt=/^(?:focusinfocus|focusoutblur)$/,kt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot._data(e);if(m){if(i.handler){l=i;i=l.handler;n=l.selector}i.guid||(i.guid=ot.guid++);(s=m.events)||(s=m.events={});if(!(p=m.handle)){p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)};p.elem=e}t=(t||"").match(Nt)||[""];a=t.length;for(;a--;){o=kt.exec(t[a])||[];f=E=o[1];h=(o[2]||"").split(".").sort();if(f){u=ot.event.special[f]||{};f=(n?u.delegateType:u.bindType)||f;u=ot.event.special[f]||{};c=ot.extend({type:f,origType:E,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l);if(!(d=s[f])){d=s[f]=[];d.delegateCount=0;u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(f,p,!1):e.attachEvent&&e.attachEvent("on"+f,p))}if(u.add){u.add.call(e,c);c.handler.guid||(c.handler.guid=i.guid)}n?d.splice(d.delegateCount++,0,c):d.push(c);ot.event.global[f]=!0}}e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){t=(t||"").match(Nt)||[""];u=t.length;for(;u--;){a=kt.exec(t[u])||[];f=E=a[1];h=(a[2]||"").split(".").sort();if(f){c=ot.event.special[f]||{};f=(r?c.delegateType:c.bindType)||f;d=p[f]||[];a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=d.length;for(;o--;){s=d[o];if(!(!n&&E!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector))){d.splice(o,1);s.selector&&d.delegateCount--;c.remove&&c.remove.call(e,s)}}if(l&&!d.length){c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,f,m.handle);delete p[f]}}else for(f in p)ot.event.remove(e,f+t[u],i,r,!0)}if(ot.isEmptyObject(p)){delete m.handle;ot._removeData(e,"events")}}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||Et],f=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];a=p=r=r||Et;if(3!==r.nodeType&&8!==r.nodeType&&!Mt.test(f+ot.event.triggered)){if(f.indexOf(".")>=0){h=f.split(".");f=h.shift();h.sort()}s=f.indexOf(":")<0&&"on"+f;e=e[ot.expando]?e:new ot.Event(f,"object"==typeof e&&e);e.isTrigger=n?2:3;e.namespace=h.join(".");e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;e.result=void 0;e.target||(e.target=r);i=null==i?[e]:ot.makeArray(i,[e]);u=ot.event.special[f]||{};if(n||!u.trigger||u.trigger.apply(r,i)!==!1){if(!n&&!u.noBubble&&!ot.isWindow(r)){l=u.delegateType||f;Mt.test(l+f)||(a=a.parentNode);for(;a;a=a.parentNode){d.push(a);p=a}p===(r.ownerDocument||Et)&&d.push(p.defaultView||p.parentWindow||t)}c=0;for(;(a=d[c++])&&!e.isPropagationStopped();){e.type=c>1?l:u.bindType||f;o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle");o&&o.apply(a,i);o=s&&a[s];if(o&&o.apply&&ot.acceptData(a)){e.result=o.apply(a,i);e.result===!1&&e.preventDefault()}}e.type=f;if(!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[f]&&!ot.isWindow(r)){p=r[s];p&&(r[s]=null);ot.event.triggered=f;try{r[f]()}catch(E){}ot.event.triggered=void 0;p&&(r[s]=p)}return e.result}}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};a[0]=e;e.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,e)!==!1){s=ot.event.handlers.call(this,e,l);t=0;for(;(n=s[t++])&&!e.isPropagationStopped();){e.currentTarget=n.elem;o=0;for(;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)if(!e.namespace_re||e.namespace_re.test(r.namespace)){e.handleObj=r;e.data=r.data;i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a);if(void 0!==i&&(e.result=i)===!1){e.preventDefault();e.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,e);return e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){n=[];for(o=0;a>o;o++){r=t[o];i=r.selector+" ";void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length);n[i]&&n.push(r)}n.length&&s.push({elem:l,handlers:n})}a<t.length&&s.push({elem:this,handlers:t.slice(a)});return s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];s||(this.fixHooks[n]=s=_t.test(n)?this.mouseHooks:wt.test(n)?this.keyHooks:{});r=s.props?this.props.concat(s.props):this.props;e=new ot.Event(o);t=r.length;for(;t--;){i=r[t];e[i]=o[i]}e.target||(e.target=o.srcElement||Et);3===e.target.nodeType&&(e.target=e.target.parentNode);e.metaKey=!!e.metaKey;return s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode);return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;if(null==e.pageX&&null!=t.clientX){r=e.target.ownerDocument||Et;n=r.documentElement;i=r.body;e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0);e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)}!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s);e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0);return e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==E()&&this.focus)try{this.focus();return!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){if(this===E()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n);n.isDefaultPrevented()&&i.preventDefault()}};ot.removeEvent=Et.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;if(e.detachEvent){typeof e[r]===yt&&(e[r]=null);e.detachEvent(r,i)}};ot.Event=function(e,t){if(!(this instanceof ot.Event))return new ot.Event(e,t);if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h}else this.type=e;t&&ot.extend(this,t);this.timeStamp=e&&e.timeStamp||ot.now();this[ot.expando]=!0};ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f;if(e){e.stopPropagation&&e.stopPropagation();e.cancelBubble=!0}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f;e&&e.stopImmediatePropagation&&e.stopImmediatePropagation();this.stopPropagation()}};ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;if(!n||n!==r&&!ot.contains(r,n)){e.type=o.origType;i=o.handler.apply(this,arguments);e.type=t}return i}}});rt.submitBubbles||(ot.event.special.submit={setup:function(){if(ot.nodeName(this,"form"))return!1;ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;if(i&&!ot._data(i,"submitBubbles")){ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0});ot._data(i,"submitBubbles",!0)}});return void 0},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0)}},teardown:function(){if(ot.nodeName(this,"form"))return!1;ot.event.remove(this,"._submit");return void 0}});rt.changeBubbles||(ot.event.special.change={setup:function(){if(Dt.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)});ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1);ot.event.simulate("change",this,e,!0)})}return!1}ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")){ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)});ot._data(t,"changeBubbles",!0)}})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){ot.event.remove(this,"._change");return!Dt.test(this.nodeName)}});rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0);ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;if(n)ot._data(r,t,n);else{r.removeEventListener(e,i,!0);ot._removeData(r,t)}}}});ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){if("string"!=typeof t){i=i||t;t=void 0}for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r){r=t;i=t=void 0}else if(null==r)if("string"==typeof t){r=i;i=void 0}else{r=i;i=t;t=void 0}if(r===!1)r=h;else if(!r)return this;if(1===n){s=r;r=function(e){ot().off(e);return s.apply(this,arguments)};r.guid=s.guid||(s.guid=ot.guid++)}return this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj){r=e.handleObj;ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}if(t===!1||"function"==typeof t){i=t;t=void 0}i===!1&&(i=h);return this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var Gt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+Gt+")[\\s/>]","i"),Vt=/^\s+/,Ft=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ht=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(Et),Zt=Qt.appendChild(Et.createElement("div"));$t.optgroup=$t.option;$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead;$t.th=$t.td;ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">"))o=e.cloneNode(!0);else{Zt.innerHTML=e.outerHTML;Zt.removeChild(o=Zt.firstChild)}if(!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e))){r=g(o);a=g(e);for(s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s])}if(t)if(i){a=a||g(e);r=r||g(o);for(s=0;null!=(n=a[s]);s++)I(n,r[s])}else I(e,o);r=g(o,"script");r.length>0&&L(r,!l&&g(e,"script"));r=a=n=null;return o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),f=[],h=0;c>h;h++){o=e[h];if(o||0===o)if("object"===ot.type(o))ot.merge(f,o.nodeType?[o]:o);else if(Wt.test(o)){a=a||d.appendChild(t.createElement("div"));l=(Ht.exec(o)||["",""])[1].toLowerCase();p=$t[l]||$t._default;a.innerHTML=p[1]+o.replace(Ft,"<$1></$2>")+p[2];n=p[0];for(;n--;)a=a.lastChild;!rt.leadingWhitespace&&Vt.test(o)&&f.push(t.createTextNode(Vt.exec(o)[0]));if(!rt.tbody){o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild;n=o&&o.childNodes.length;for(;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u) }ot.merge(f,a.childNodes);a.textContent="";for(;a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else f.push(t.createTextNode(o))}a&&d.removeChild(a);rt.appendChecked||ot.grep(g(f,"input"),v);h=0;for(;o=f[h++];)if(!r||-1===ot.inArray(o,r)){s=ot.contains(o.ownerDocument,o);a=g(d.appendChild(o),"script");s&&L(a);if(i){n=0;for(;o=a[n++];)Xt.test(o.type||"")&&i.push(o)}}a=null;return d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if(t||ot.acceptData(i)){n=i[a];o=n&&l[n];if(o){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);if(l[n]){delete l[n];u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null;K.push(n)}}}}});ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||Et).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++){t||1!==i.nodeType||ot.cleanData(g(i));if(i.parentNode){t&&ot.contains(i.ownerDocument,i)&&L(g(i,"script"));i.parentNode.removeChild(i)}}return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){1===e.nodeType&&ot.cleanData(g(e,!1));for(;e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){e=null==e?!1:e;t=null==t?e:t;return this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ht.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ft,"<$1></$2>");try{for(;r>i;i++){t=this[i]||{};if(1===t.nodeType){ot.cleanData(g(t,!1));t.innerHTML=e}}t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(t){e=this.parentNode;ot.cleanData(g(this));e&&e.replaceChild(t,this)});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],f=ot.isFunction(d);if(f||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);f&&(e[0]=d.call(this,i,r.html()));r.domManip(e,t)});if(u){a=ot.buildFragment(e,this[0].ownerDocument,!1,this);i=a.firstChild;1===a.childNodes.length&&(a=i);if(i){o=ot.map(g(a,"script"),N);n=o.length;for(;u>l;l++){r=a;if(l!==c){r=ot.clone(r,!0,!0);n&&ot.merge(o,g(r,"script"))}t.call(this[l],r,l)}if(n){s=o[o.length-1].ownerDocument;ot.map(o,T);for(l=0;n>l;l++){r=o[l];Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")))}}a=i=null}}return this}});ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++){i=r===s?this:this.clone(!0);ot(o[r])[t](i);Z.apply(n,i.get())}return this.pushStack(n)}});var Jt,ei={};(function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1";t.appendChild(Et.createElement("div")).style.width="5px";e=3!==t.offsetWidth}i.removeChild(r);return e}}})();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;if(t.getComputedStyle){ti=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i.getPropertyValue(t)||i[t]:void 0;if(i){""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t));if(ni.test(s)&&ri.test(t)){r=a.width;n=a.minWidth;o=a.maxWidth;a.minWidth=a.maxWidth=a.width=s;s=i.width;a.width=r;a.minWidth=n;a.maxWidth=o}}return void 0===s?s:s+""}}else if(Et.documentElement.currentStyle){ti=function(e){return e.currentStyle};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i[t]:void 0;null==s&&a&&a[t]&&(s=a[t]);if(ni.test(s)&&!oi.test(t)){r=a.left;n=e.runtimeStyle;o=n&&n.left;o&&(n.left=e.currentStyle.left);a.left="fontSize"===t?"1em":s;s=a.pixelLeft+"px";a.left=r;o&&(n.left=o)}return void 0===s?s:s+""||"auto"}}(function(){function e(){var e,i,r,n;i=Et.getElementsByTagName("body")[0];if(i&&i.style){e=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(e);e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";o=s=!1;l=!0;if(t.getComputedStyle){o="1%"!==(t.getComputedStyle(e,null)||{}).top;s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width;n=e.appendChild(Et.createElement("div"));n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";n.style.marginRight=n.style.width="0";e.style.width="1px";l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight);e.removeChild(n)}e.innerHTML="<table><tr><td></td><td>t</td></tr></table>";n=e.getElementsByTagName("td");n[0].style.cssText="margin:0;border:0;padding:0;display:none";a=0===n[0].offsetHeight;if(a){n[0].style.display="";n[1].style.display="none";a=0===n[0].offsetHeight}i.removeChild(r)}}var i,r,n,o,s,a,l;i=Et.createElement("div");i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";n=i.getElementsByTagName("a")[0];r=n&&n.style;if(r){r.cssText="float:left;opacity:.5";rt.opacity="0.5"===r.opacity;rt.cssFloat=!!r.cssFloat;i.style.backgroundClip="content-box";i.cloneNode(!0).style.backgroundClip="";rt.clearCloneStyle="content-box"===i.style.backgroundClip;rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;ot.extend(rt,{reliableHiddenOffsets:function(){null==a&&e();return a},boxSizingReliable:function(){null==s&&e();return s},pixelPosition:function(){null==o&&e();return o},reliableMarginRight:function(){null==l&&e();return l}})}})();ot.swap=function(e,t,i,r){var n,o,s={};for(o in t){s[o]=e.style[o];e.style[o]=t[o]}n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},fi=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},cssNumber:{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":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a));s=ot.cssHooks[t]||ot.cssHooks[a];if(void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];o=typeof i;if("string"===o&&(n=pi.exec(i))){i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t));o="number"}if(null!=i&&i===i){"number"!==o||ot.cssNumber[a]||(i+="px");rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit");if(!(s&&"set"in s&&void 0===(i=s.set(e,i,r))))try{l[t]=i}catch(u){}}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a));s=ot.cssHooks[t]||ot.cssHooks[a];s&&"get"in s&&(o=s.get(e,!0,i));void 0===o&&(o=ii(e,t,r));"normal"===o&&t in di&&(o=di[t]);if(""===i||i){n=parseFloat(o);return i===!0||ot.isNumeric(n)?n||0:o}return o}});ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}});rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1;if((t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute){i.removeAttribute("filter");if(""===t||r&&!r.filter)return}i.filter=si.test(o)?o.replace(si,n):o+" "+n}});ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0});ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}};ri.test(e)||(ot.cssHooks[e+t].set=O)});ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){r=ti(e);n=t.length;for(;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}});ot.Tween=w;w.prototype={constructor:w,init:function(e,t,i,r,n,o){this.elem=e;this.prop=i;this.easing=n||"swing";this.options=t;this.start=this.now=this.cur();this.end=r;this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=w.propHooks[this.prop];return e&&e.get?e.get(this):w.propHooks._default.get(this)},run:function(e){var t,i=w.propHooks[this.prop];this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e;this.now=(this.end-this.start)*t+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);i&&i.set?i.set(this):w.propHooks._default.set(this);return this}};w.prototype.init.prototype=w.prototype;w.propHooks={_default:{get:function(e){var t;if(null!=e.elem[e.prop]&&(!e.elem.style||null==e.elem.style[e.prop]))return e.elem[e.prop];t=ot.css(e.elem,e.prop,"");return t&&"auto"!==t?t:0},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}};w.propHooks.scrollTop=w.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}};ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}};ot.fx=w.prototype.init;ot.fx.step={};var hi,Ei,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[G],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3];n=n||[];s=+r||1;do{a=a||".5";s/=a;ot.style(i.elem,e,s+o)}while(a!==(a=i.cur()/r)&&1!==a&&--l)}if(n){s=i.start=+s||+r||0;i.unit=o;i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]}return i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){if(ot.isFunction(e)){t=e;e=["*"]}else e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++){i=e[r];Ni[i]=Ni[i]||[];Ni[i].unshift(t)}},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}});ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){ot.isFunction(r.old)&&r.old.call(this);r.queue&&ot.dequeue(this,r.queue)};return r};ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};s.finish=s;return n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop;t(i)};if("string"!=typeof e){i=t;t=e;e=void 0}t&&e!==!1&&this.queue(e||"fx",[]);return this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)if(o[n].elem===this&&(null==e||o[n].queue===e)){o[n].anim.stop(i);t=!1;o.splice(n,1)}(t||!i)&&ot.dequeue(this,e)})},finish:function(e){e!==!1&&(e=e||"fx");return this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;i.finish=!0;ot.queue(this,e,[]);n&&n.stop&&n.stop.call(this,!0);for(t=o.length;t--;)if(o[t].elem===this&&o[t].queue===e){o[t].anim.stop(!0);o.splice(t,1)}for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}});ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(M(t,!0),e,r,n)}});ot.each({slideDown:M("show"),slideUp:M("hide"),slideToggle:M("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}});ot.timers=[];ot.fx.tick=function(){var e,t=ot.timers,i=0;hi=ot.now();for(;i<t.length;i++){e=t[i];e()||t[i]!==e||t.splice(i--,1)}t.length||ot.fx.stop();hi=void 0};ot.fx.timer=function(e){ot.timers.push(e);e()?ot.fx.start():ot.timers.pop()};ot.fx.interval=13;ot.fx.start=function(){Ei||(Ei=setInterval(ot.fx.tick,ot.fx.interval))};ot.fx.stop=function(){clearInterval(Ei);Ei=null};ot.fx.speeds={slow:600,fast:200,_default:400};ot.fn.delay=function(e,t){e=ot.fx?ot.fx.speeds[e]||e:e;t=t||"fx";return this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})};(function(){var e,t,i,r,n;t=Et.createElement("div");t.setAttribute("className","t");t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=t.getElementsByTagName("a")[0];i=Et.createElement("select");n=i.appendChild(Et.createElement("option"));e=t.getElementsByTagName("input")[0];r.style.cssText="top:1px";rt.getSetAttribute="t"!==t.className;rt.style=/top/.test(r.getAttribute("style"));rt.hrefNormalized="/a"===r.getAttribute("href");rt.checkOn=!!e.value;rt.optSelected=n.selected;rt.enctype=!!Et.createElement("form").enctype;i.disabled=!0;rt.optDisabled=!n.disabled;e=Et.createElement("input");e.setAttribute("value","");rt.input=""===e.getAttribute("value");e.value="t";e.setAttribute("type","radio");rt.radioValue="t"===e.value})();var Ti=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];if(arguments.length){r=ot.isFunction(e);return this.each(function(i){var n;if(1===this.nodeType){n=r?e.call(this,i,ot(this).val()):e;null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""}));t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()];t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n)}})}if(n){t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()];if(t&&"get"in t&&void 0!==(i=t.get(n,"value")))return i;i=n.value;return"string"==typeof i?i.replace(Ti,""):null==i?"":i}}});ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++){i=r[l];if(!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){t=ot(i).val();if(o)return t;s.push(t)}}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;){r=n[s];if(ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1}i||(e.selectedIndex=-1);return n}}}});ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}};rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Li,Ii,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}});ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o){if(typeof e.getAttribute===yt)return ot.prop(e,t,i);if(1!==o||!ot.isXMLDoc(e)){t=t.toLowerCase();r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ii:Li)}if(void 0===i){if(r&&"get"in r&&null!==(n=r.get(e,t)))return n;n=ot.find.attr(e,t);return null==n?void 0:n}if(null!==i){if(r&&"set"in r&&void 0!==(n=r.set(e,i,t)))return n;e.setAttribute(t,i+"");return i}ot.removeAttr(e,t)}},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];){r=ot.propFix[i]||i;ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,"");e.removeAttribute(Si?i:r)}},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;e.setAttribute("type",t);i&&(e.value=i);return t}}}}});Ii={set:function(e,t,i){t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0;return i}};ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;if(!r){o=yi[t];yi[t]=n;n=null!=i(e,t,r)?t.toLowerCase():null;yi[t]=o}return n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}});Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){if(!ot.nodeName(e,"input"))return Li&&Li.set(e,t,i);e.defaultValue=t;return void 0}});if(!Si){Li={set:function(e,t,i){var r=e.getAttributeNode(i);r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i));r.value=t+="";return"value"===i||t===e.getAttribute(i)?t:void 0}};yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null};ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Li.set};ot.attrHooks.contenteditable={set:function(e,t,i){Li.set(e,""===t?!1:t,i)}};ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){if(""===i){e.setAttribute(t,"auto");return i}}}})}rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){e=ot.propFix[e]||e;return this.each(function(){try{this[e]=void 0;delete this[e]}catch(t){}})}});ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s){o=1!==s||!ot.isXMLDoc(e);if(o){t=ot.propFix[t]||t;n=ot.propHooks[t]}return void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]}},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}});rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}});rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;if(t){t.selectedIndex;t.parentNode&&t.parentNode.selectedIndex}return null}});ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this});rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ");if(r){o=0;for(;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r);i.className!==s&&(i.className=s)}}}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"");if(r){o=0;for(;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"";i.className!==s&&(i.className=s)}}}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else if(i===yt||"boolean"===i){this.className&&ot._data(this,"__className__",this.className);this.className=this.className||e===!1?"":ot._data(this,"__className__")||""}})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}});ot.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(e,t){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}});ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,wi=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(wi,function(e,t,n,o){i&&t&&(r=0);if(0===r)return e;i=n||t;r+=!o-!n;return""}))?Function("return "+n)():ot.error("Invalid JSON: "+e)};ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{if(t.DOMParser){r=new DOMParser;i=r.parseFromString(e,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(e)}}catch(n){i=void 0}i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e);return i};var _i,Mi,ki=/#.*$/,Gi=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Fi=/^\/\//,Hi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{Mi=location.href}catch(zi){Mi=Et.createElement("a");Mi.href="";Mi=Mi.href}_i=Hi.exec(Mi.toLowerCase())||[];ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mi,type:"GET",isLocal:Ui.test(_i[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,ot.ajaxSettings),t):H(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,L=t;if(2!==x){x=2;a&&clearTimeout(a);u=void 0;s=r||"";T.readyState=e>0?4:0;n=e>=200&&300>e||304===e;i&&(v=j(c,T,i));v=W(c,v,T,n);if(n){if(c.ifModified){N=T.getResponseHeader("Last-Modified");N&&(ot.lastModified[o]=N);N=T.getResponseHeader("etag");N&&(ot.etag[o]=N)}if(204===e||"HEAD"===c.type)L="nocontent";else if(304===e)L="notmodified";else{L=v.state;p=v.data;g=v.error;n=!g}}else{g=L;if(e||!L){L="error";0>e&&(e=0)}}T.status=e;T.statusText=(t||L)+"";n?h.resolveWith(d,[p,L,T]):h.rejectWith(d,[T,L,g]);T.statusCode(m);m=void 0;l&&f.trigger(n?"ajaxSuccess":"ajaxError",[T,c,n?p:g]);E.fireWith(d,[T,L]);if(l){f.trigger("ajaxComplete",[T,c]);--ot.active||ot.event.trigger("ajaxStop")}}}if("object"==typeof e){t=e;e=void 0}t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,f=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),E=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p){p={};for(;t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2]}t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();if(!x){e=v[i]=v[i]||e;g[e]=t}return this},overrideMimeType:function(e){x||(c.mimeType=e);return this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||N;u&&u.abort(t);i(0,t);return this}};h.promise(T).complete=E.add;T.success=T.done;T.error=T.fail;c.url=((e||c.url||Mi)+"").replace(ki,"").replace(Fi,_i[1]+"//");c.type=t.method||t.type||c.method||c.type;c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""];if(null==c.crossDomain){r=Hi.exec(c.url.toLowerCase());c.crossDomain=!(!r||r[1]===_i[1]&&r[2]===_i[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(_i[3]||("http:"===_i[1]?"80":"443")))}c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional));F(ji,c,t,T);if(2===x)return T;l=ot.event&&c.global;l&&0===ot.active++&&ot.event.trigger("ajaxStart");c.type=c.type.toUpperCase();c.hasContent=!Vi.test(c.type);o=c.url;if(!c.hasContent){if(c.data){o=c.url+=(Di.test(o)?"&":"?")+c.data;delete c.data}c.cache===!1&&(c.url=Gi.test(o)?o.replace(Gi,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)}if(c.ifModified){ot.lastModified[o]&&T.setRequestHeader("If-Modified-Since",ot.lastModified[o]);ot.etag[o]&&T.setRequestHeader("If-None-Match",ot.etag[o])}(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType);T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)T.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,T,c)===!1||2===x))return T.abort();N="abort";for(n in{success:1,error:1,complete:1})T[n](c[n]);u=F(Wi,c,t,T);if(u){T.readyState=1;l&&f.trigger("ajaxSend",[T,c]);c.async&&c.timeout>0&&(a=setTimeout(function(){T.abort("timeout")},c.timeout));try{x=1;u.send(g,i)}catch(L){if(!(2>x))throw L;i(-1,L)}}else i(-1,"No Transport");return T},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}});ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){if(ot.isFunction(i)){n=n||r;r=i;i=void 0}return ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}});ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}});ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))};ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional);if(ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")};ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}});ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in Ji)Ji[e](void 0,!0)});rt.cors=!!er&&"withCredentials"in er;er=rt.ajax=!!er;er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;o.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType);e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null);t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState)){delete Ji[s];t=void 0;o.onreadystatechange=ot.noop;if(n)4!==o.readyState&&o.abort();else{u={};a=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText }catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}}u&&r(a,l,u,o.getAllResponseHeaders())};e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}});ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){ot.globalEval(e);return e}}});ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1);if(e.crossDomain){e.type="GET";e.global=!1}});ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=Et.head||ot("head")[0]||Et.documentElement;return{send:function(r,n){t=Et.createElement("script");t.async=!0;e.scriptCharset&&(t.charset=e.scriptCharset);t.src=e.url;t.onload=t.onreadystatechange=function(e,i){if(i||!t.readyState||/loaded|complete/.test(t.readyState)){t.onload=t.onreadystatechange=null;t.parentNode&&t.parentNode.removeChild(t);t=null;i||n(200,"success")}};i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;this[e]=!0;return e}});ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0]){n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback;a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n);e.converters["script json"]=function(){s||ot.error(n+" was not called");return s[0]};e.dataTypes[0]="json";o=t[n];t[n]=function(){s=arguments};r.always(function(){t[n]=o;if(e[n]){e.jsonpCallback=i.jsonpCallback;tr.push(n)}s&&ot.isFunction(o)&&o(s[0]);s=o=void 0});return"script"}});ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;if("boolean"==typeof t){i=t;t=!1}t=t||Et;var r=dt.exec(e),n=!i&&[];if(r)return[t.createElement(r[1])];r=ot.buildFragment([e],t,n);n&&n.length&&ot(n).remove();return ot.merge([],r.childNodes)};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");if(a>=0){r=ot.trim(e.slice(a,e.length));e=e.slice(0,a)}if(ot.isFunction(t)){i=t;t=void 0}else t&&"object"==typeof t&&(o="POST");s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments;s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])});return this};ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}});ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative");a=c.offset();o=ot.css(e,"top");l=ot.css(e,"left");u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1;if(u){r=c.position();s=r.top;n=r.left}else{s=parseFloat(o)||0;n=parseFloat(l)||0}ot.isFunction(t)&&(t=t.call(e,i,a));null!=t.top&&(d.top=t.top-a.top+s);null!=t.left&&(d.left=t.left-a.left+n);"using"in t?t.using.call(e,d):c.css(d)}};ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o){t=o.documentElement;if(!ot.contains(t,n))return r;typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect());i=Y(o);return{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}}},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];if("fixed"===ot.css(r,"position"))t=r.getBoundingClientRect();else{e=this.offsetParent();t=this.offset();ot.nodeName(e[0],"html")||(i=e.offset());i.top+=ot.css(e[0],"borderTopWidth",!0);i.left+=ot.css(e[0],"borderLeftWidth",!0)}return{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}});ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);if(void 0===n)return o?t in o?o[t]:o.document.documentElement[r]:e[r];o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n;return void 0},e,r,arguments.length,null)}});ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){if(i){i=ii(e,t);return ni.test(i)?ot(e).position()[t]+"px":i}})});ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;if(ot.isWindow(t))return t.document.documentElement["client"+e];if(9===t.nodeType){n=t.documentElement;return Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])}return void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})});ot.fn.size=function(){return this.length};ot.fn.andSelf=ot.fn.addBack;"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;ot.noConflict=function(e){t.$===ot&&(t.$=sr);e&&t.jQuery===ot&&(t.jQuery=or);return ot};typeof i===yt&&(t.jQuery=t.$=ot);return ot})},{}],16:[function(t,i){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function n(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,i){if(null==i){i=t;t=null}null==t&&(t={});var r=s.get(e,t);i(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var i=s.deserialize(o.getItem(e));return void 0===i?t:i};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var i=o.key(t);e(i,s.get(i))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var i=e.apply(s,t);p.removeChild(o);return i}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,i){t=n(t);if(void 0===i)return s.remove(t);e.setAttribute(t,s.serialize(i));e.save(l);return i});s.get=f(function(e,t,i){t=n(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?i:r});s.remove=f(function(e,t){t=n(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=f(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,s.deserialize(e.getAttribute(i.name)))})}try{var E="__storejs__";s.set(E,E);s.get(E)!=E&&(s.disabled=!0);s.remove(E)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],17:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],18:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":17,"./storage.js":19,"./svg.js":20}],19:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){if(i.enabled&&e&&t){"string"==typeof n&&(n=r[n]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));i.set(e,{val:t,exp:n,time:(new Date).getTime()})}},remove:function(e){i.enabled&&e&&i.remove(e)},get:function(e){if(!i.enabled)return null;if(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:16}],20:[function(e,t){t.exports={draw:function(e,i){if(e){var r=t.exports.getElement(i);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,i=t.parseFromString(e,"text/xml"),r=i.documentElement,n=document.createElement("div");n.className="svgImg";n.appendChild(r);return n}return!1}}},{}],21:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.3",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],22:[function(e,t){"use strict";var i=e("jquery"),r=e("../utils.js"),n=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var n=i(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;n.is(":visible")&&(o=n.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,i){u[e.name]=new o;for(var s=0;s<i.length;s++)u[e.name].insert(i[s]);var a=r.getPersistencyId(t,e.persistent);a&&n.storage.set(a,i,"month")},c=function(e,i){var o=l[e]=new i(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=n.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var n=function(i){if(r&&(!i.autoShow||!i.bulk&&i.async))return!1;var n={closeCharacters:/(?=a)b/,completeSingle:!1};!i.bulk&&i.async&&(n.async=!0);{var o=function(e,t){return f(i,t)};e.showHint(t,o,n)}return!0};for(var o in l)if(-1!=i.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=n(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,i){var r=function(t){var i=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(i);else if("function"==typeof e.get&&0==e.async)r=e.get(i);else if("object"==typeof e.get)for(var n=i.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,n)==i&&r.push(s)}return h(r,e,t)},n=t.getCompleteToken();e.preProcessToken&&(n=e.preProcessToken(n));if(n){if(e.bulk||!e.async)return r(n);var o=function(t){i(h(t,e,n))};e.get(n,o)}},h=function(e,i,r){for(var n=[],o=0;o<e.length;o++){var a=e[o];i.postProcessToken&&(a=i.postProcessToken(r,a));n.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:n,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(i.callbacks)for(var p in i.callbacks)i.callbacks[p]&&t.on(u,p,i.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return i(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=i("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(i(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)}},{"../../lib/trie.js":4,"../utils.js":35,jquery:15,"yasgui-utils":18}],23:[function(e,t){"use strict";e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var i=e.getCursor(),r=e.getPreviousNonWsToken(i.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],24:[function(e,t){"use strict";var i=e("jquery"),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){i.get("http://prefix.cc/popular/all.file.json",function(e){var i=[];for(var r in e)if("bif"!=r){var n=r+": <"+e[r]+">";i.push(n)}i.sort();t(i)})},preProcessToken:function(i){return t.exports.preprocessPrefixTokenForCompletion(e,i)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==i.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var n=e.getPreviousNonWsToken(t.line,r);return n&&"PREFIX"==n.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var i=e.getPreviousNonWsToken(e.getCursor().line,t);i&&i.string&&":"==i.string.slice(-1)&&(t={start:i.start,end:t.end,string:i.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var i=e.getCursor(),n=e.getTokenAt(i);if("prefixed"==r[n.type]){var o=n.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(i.line,n).string.toUpperCase(),a=e.getTokenAt({line:i.line,ch:n.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=n.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:15}],25:[function(e,t){"use strict";var i=e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(i.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),n=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==n.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],26:[function(e,t){"use strict";var i=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),n=function(e,t){var i=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=i[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=i[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in i)if(0==t.string.indexOf(r)){t.autocompletionString=i[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,i){i=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+i.substring(t.tokenPrefixUri.length):"<"+i+">";return i},s=function(t,n,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(n).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==n.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+i.param(l)};c();var d=function(){l.page++;c()},f=function(){i.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(i.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,n):t.autocompleters.notifications.getEl(n).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(n).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(n).empty().append(i("<span>Fetchting autocompletions &nbsp;</span>")).append(i(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:n,postprocessResourceTokenForCompletion:o}},{"../imgs.js":29,"./utils.js":26,jquery:15,"yasgui-utils":18}],27:[function(e,t){"use strict";var i=e("jquery");t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};i(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var n=i(this).next(),o=n.attr("class");o&&n.attr("class").indexOf("cm-atom")>=0&&(e+=n.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var n=[];for(var o in r)n.push(o);n.sort();return n},async:!1,bulk:!1,autoShow:!0}}},{jquery:15}],28:[function(e){var t=e("jquery"),i=e("./main.js");i.defaults=t.extend(!0,{},i.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,foldGutter:{rangeFinder:i.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":i.autoComplete,"Cmd-Space":i.autoComplete,"Ctrl-D":i.deleteLine,"Ctrl-K":i.deleteLine,"Cmd-D":i.deleteLine,"Cmd-K":i.deleteLine,"Ctrl-/":i.commentLines,"Cmd-/":i.commentLines,"Ctrl-Alt-Down":i.copyLineDown,"Ctrl-Alt-Up":i.copyLineUp,"Cmd-Alt-Down":i.copyLineDown,"Cmd-Alt-Up":i.copyLineUp,"Shift-Ctrl-F":i.doAutoFormat,"Shift-Cmd-F":i.doAutoFormat,"Ctrl-]":i.indentMore,"Cmd-]":i.indentMore,"Ctrl-[":i.indentLess,"Cmd-[":i.indentLess,"Ctrl-S":i.storeQuery,"Cmd-S":i.storeQuery,"Ctrl-Enter":i.executeQuery,"Cmd-Enter":i.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:i.createShareLink,consumeShareLink:i.consumeShareLink,persistent:function(e){return"yasqe_"+t(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})},{"./main.js":30,jquery:15}],29:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="warning.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" inkscape:zoom="3.1936344" inkscape:cx="36.8135" inkscape:cy="36.9485" inkscape:window-x="2625" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)" ><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><path d="M 66.129381,65.903784 H 49.769875 c -1.64721,0 -2.889385,-0.581146 -3.498678,-1.63595 -0.609293,-1.055608 -0.491079,-2.422161 0.332391,-3.848223 l 8.179753,-14.167069 c 0.822934,-1.42633 1.9477,-2.211737 3.166018,-2.211737 1.218319,0 2.343086,0.785407 3.166019,2.211737 l 8.179751,14.167069 c 0.823472,1.426062 0.941686,2.792615 0.33239,3.848223 -0.609023,1.054804 -1.851197,1.63595 -3.498138,1.63595 z M 59.618815,60.91766 c 0,-0.850276 -0.68944,-1.539719 -1.539717,-1.539719 -0.850276,0 -1.539718,0.689443 -1.539718,1.539719 0,0.850277 0.689442,1.539718 1.539718,1.539718 0.850277,0 1.539717,-0.689441 1.539717,-1.539718 z m 0.04155,-9.265919 c 0,-0.873061 -0.707939,-1.580998 -1.580999,-1.580998 -0.873061,0 -1.580999,0.707937 -1.580999,1.580998 l 0.373403,5.610965 h 0.0051 c 0.05415,0.619747 0.568548,1.10761 1.202504,1.10761 0.586239,0 1.075443,-0.415756 1.188563,-0.968489 0.0092,-0.04476 0.0099,-0.09248 0.01392,-0.138854 h 0.01072 l 0.367776,-5.611232 z" inkscape:connector-curvature="0" style="fill:#aa8800" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'} },{}],30:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var i=e("jquery"),r=e("codemirror"),n=e("./utils.js"),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var n=i("<div>",{"class":"yasqe"}).appendTo(i(e));t=l(t);var o=u(r(n[0],t));d(o);return o},l=function(e){var t=i.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(i,r){return e("./tokenUtils.js").getCompleteToken(t,i,r)};t.getPreviousNonWsToken=function(i,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,i,r)};t.getNextNonWsToken=function(i,r){return e("./tokenUtils.js").getNextNonWsToken(t,i,r)};t.query=function(e){a.executeQuery(t,e)};t.getUrlArguments=function(e){return a.getUrlArguments(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(i){return e("./prefixUtils.js").addPrefixes(t,i)};t.removePrefixes=function(i){return e("./prefixUtils.js").removePrefixes(t,i)};t.getValueWithoutComments=function(){var e="";a.runMode(t.getValue(),"sparql11",function(t,i){"comment"!=i&&(e+=t)});return e};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=i.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=n.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("changes",function(){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=i.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=i(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(n.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var n=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),n=u.state;t.queryType=n.queryType;if(0==n.OK){if(!t.options.syntaxErrorCheck){i(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);n.possibleCurrent&&n.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];n.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+i("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=n&&void 0!=n.stack){var c=n.stack,d=n.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};i.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=i(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=i.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=i("<div class='yasqe_buttons'></div>").appendTo(i(e.getWrapperElement()));if(e.options.createShareLink){var t=i(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var n=i("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);i("html").click(function(){n&&n.remove()});n.click(function(e){e.stopPropagation()});var o=i("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+i.param(e.options.createShareLink(e)));o.focus(function(){var e=i(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});n.empty().append(o);var s=t.position();n.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-n.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=i("<div>",{"class":"fullscreenToggleBtns"}).append(i(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(i(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){i("<div>",{"class":"yasqe_queryButton"}).click(function(){if(i(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var E={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=i(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[E[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var n=(i("<div>",{"class":"yasqe"}).insertBefore(i(e)).append(i(e)),u(r.fromTextArea(e,t)));d(n);return n};a.storeQuery=function(e){var t=n.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:i,ch:r})}};var m=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=g(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},g=function(e,t,n){e=e.substring(t,n);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=i.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);if(0!=i){if(1==i){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return i.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js"),e("./defaults.js");a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:i.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":2,"../lib/flint.js":3,"../package.json":21,"./autocompleters/autocompleterBase.js":22,"./autocompleters/classes.js":23,"./autocompleters/prefixes.js":24,"./autocompleters/properties.js":25,"./autocompleters/variables.js":27,"./defaults.js":28,"./imgs.js":29,"./prefixUtils.js":31,"./sparql.js":32,"./tokenUtils.js":33,"./tooltip":34,"./utils.js":35,codemirror:14,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/edit/matchbrackets.js":6,"codemirror/addon/fold/brace-fold.js":7,"codemirror/addon/fold/foldcode.js":8,"codemirror/addon/fold/foldgutter.js":9,"codemirror/addon/fold/xml-fold.js":10,"codemirror/addon/hint/show-hint.js":11,"codemirror/addon/runmode/runmode.js":12,"codemirror/addon/search/searchcursor.js":13,jquery:15,"yasgui-utils":18}],31:[function(e,t){"use strict";var i=function(e,t){var i=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var n in t)n in i||r(e,n+": <"+t[n]+">")},r=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){i=a;r=o}}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},n=function(e,t){var i=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+i("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},i=!0,r=function(n,s){if(i){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(i=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(n,u.end+1)}else r(n,l.end+1)}else r(n,a.end+1)}else r(n,a.end+1)}}},n=e.lineCount(),o=0;n>o&&i;o++)r(o);return t},s=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:i,getPrefixesFromQuery:o,removePrefixes:n}},{}],32:[function(e){"use strict";var t=e("jquery"),i=e("./main.js");i.executeQuery=function(e,n){var o="function"==typeof n?n:null,s="object"==typeof n?n:{};e.options.sparql&&(s=t.extend({},e.options.sparql,s));s.handlers&&t.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var a={url:"function"==typeof s.endpoint?s.endpoint(e):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(e):s.requestMethod,headers:{Accept:r(e,s)}},l=!1;if(s.callbacks)for(var u in s.callbacks)if(s.callbacks[u]){l=!0;a[u]=s.callbacks[u]}a.data=e.getUrlArguments(s);if(l||o){o&&(a.complete=o);s.headers&&!t.isEmptyObject(s.headers)&&t.extend(a.headers,s.headers);i.updateQueryButton(e,"busy");var p=function(){i.updateQueryButton(e)};a.complete=a.complete?[p,a.complete]:p;e.xhr=t.ajax(a)}}};i.getUrlArguments=function(e,i){var r=e.getQueryMode(),n=[{name:e.getQueryMode(),value:e.getValue()}];if(i.namedGraphs&&i.namedGraphs.length>0)for(var o="query"==r?"named-graph-uri":"using-named-graph-uri ",s=0;s<i.namedGraphs.length;s++)n.push({name:o,value:i.namedGraphs[s]});if(i.defaultGraphs&&i.defaultGraphs.length>0)for(var o="query"==r?"default-graph-uri":"using-graph-uri ",s=0;s<i.defaultGraphs.length;s++)n.push({name:o,value:i.defaultGraphs[s]});i.args&&i.args.length>0&&t.merge(n,i.args);return n};var r=function(e,t){var i=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())i="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();i="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else i="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return i}},{"./main.js":30,jquery:15}],33:[function(e,t){"use strict";var i=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var n=e.getTokenAt({line:r.line,ch:t.start});if(null!=n.type&&"ws"!=n.type&&null!=t.type&&"ws"!=t.type){t.start=n.start;t.string=n.string+t.string;return i(e,t,{line:r.line,ch:n.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,i){var n=e.getTokenAt({line:t,ch:i.start});null!=n&&"ws"==n.type&&(n=r(e,t,n));return n},n=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?n(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:i,getNextNonWsToken:n}},{}],34:[function(e,t){"use strict";{var i=e("jquery");e("./utils.js")}t.exports=function(e,t,r){var n,t=i(t);t.hover(function(){"function"==typeof r&&(r=r());n=i("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){i(".yasqe_tooltip").remove()});var o=function(){if(i(e.getWrapperElement()).offset().top>=n.offset().top){n.css("bottom","auto");n.css("top","26px")}}}},{"./utils.js":35,jquery:15}],35:[function(e,t){"use strict";var i=e("jquery"),r=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},n=function(e,t){var i=null;t&&(i="string"==typeof t?t:t(e));return i},o=function(){function e(e){var t,r,n;t=i(e).offset();r=i(e).width();n=i(e).height();return[[t.left,t.left+r],[t.top,t.top+n]]}function t(e,t){var i,r;i=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return i[1]>r[0]||i[0]===r[0]}return function(i,r){var n=e(i),o=e(r);return t(n[0],o[0])&&t(n[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:n,elementsOverlap:o}},{jquery:15}]},{},[1])(1)}); //# sourceMappingURL=yasqe.bundled.min.js.map
Magistrate/client/components/filterBar.js
Pondidum/Magistrate
import React from 'react' const FilterBar = ({ filterChanged }) => ( <div className="filter-bar col-sm-5 pull-right"> <input type="text" className="form-control" placeholder="filter..." onChange={e => filterChanged(e.target.value)} /> </div> ); export default FilterBar
modules/DOMUtils.js
carlosmontes/react-router
export var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ) export function addEventListener(node, type, listener) { if (node.addEventListener) { node.addEventListener(type, listener, false) } else { node.attachEvent('on' + type, listener) } } export function removeEventListener(node, type, listener) { if (node.removeEventListener) { node.removeEventListener(type, listener, false) } else { node.detachEvent('on' + type, listener) } } export function getHashPath() { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! return window.location.href.split('#')[1] || '' } export function replaceHashPath(path) { window.location.replace( window.location.pathname + window.location.search + '#' + path ) } export function getWindowPath() { return window.location.pathname + window.location.search } export function getWindowScrollPosition() { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop } } export function setWindowScrollPosition(scrollX, scrollY) { window.scrollTo(scrollX, scrollY) } /** * taken from modernizr * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js * changed to avoid false negatives for Windows Phones: https://github.com/rackt/react-router/issues/586 */ export function supportsHistory() { var ua = navigator.userAgent if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) { return false } return window.history && 'pushState' in window.history }
src/Parser/Rogue/Subtlety/Modules/Features/SymbolsOfDeathUptime.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import Analyzer from 'Parser/Core/Analyzer'; import Enemies from 'Parser/Core/Modules/Enemies'; import Combatants from 'Parser/Core/Modules/Combatants'; class SymbolsOfDeathUptime extends Analyzer { static dependencies = { enemies: Enemies, combatants: Combatants, }; statistic() { const symbolsOfDeathUptime = this.combatants.selected.getBuffUptime(SPELLS.SYMBOLS_OF_DEATH.id) / this.owner.fightDuration; return ( <StatisticBox icon={<SpellIcon id={SPELLS.SYMBOLS_OF_DEATH.id} />} value={`${formatPercentage(symbolsOfDeathUptime)} %`} label="Symbols of Death uptime" /> ); } statisticOrder = STATISTIC_ORDER.CORE(3); } export default SymbolsOfDeathUptime;
new-lamassu-admin/src/pages/Machines/MachineComponents/Overview.js
lamassu/lamassu-server
import { makeStyles } from '@material-ui/core/styles' import BigNumber from 'bignumber.js' import { formatDistance } from 'date-fns' import React from 'react' import { Status } from 'src/components/Status' import MachineActions from 'src/components/machineActions/MachineActions' import { H3, Label1, P } from 'src/components/typography' import CopyToClipboard from 'src/pages/Transactions/CopyToClipboard.js' import styles from '../Machines.styles' const useStyles = makeStyles(styles) const Overview = ({ data, onActionSuccess }) => { const classes = useStyles() return ( <div className={classes.contentContainer}> <div className={classes.row}> <div className={classes.rowItem}> <H3>{data.name}</H3> </div> </div> <div className={classes.row}> <div className={classes.rowItem}> <Label1 className={classes.label3}>Status</Label1> {data && data.statuses ? <Status status={data.statuses[0]} /> : null} </div> </div> <div className={classes.row}> <div className={classes.rowItem}> <Label1 className={classes.label3}>Ping</Label1> <P noMargin> {data.responseTime ? new BigNumber(data.responseTime).toFixed(3).toString() + ' ms' : 'unavailable'} </P> </div> <div className={classes.rowItem}> <Label1 className={classes.label3}>Last ping</Label1> <P noMargin> {data.lastPing ? formatDistance(new Date(data.lastPing), new Date(), { addSuffix: true }) : 'unknown'} </P> </div> <div className={classes.rowItem}> <Label1 className={classes.label3}>Network speed</Label1> <P noMargin> {data.downloadSpeed ? new BigNumber(data.downloadSpeed) .toFixed(data.downloadSpeed < 10 ? 2 : 0) .toString() + ' MB/s' : 'unavailable'} </P> </div> </div> <div className={classes.row}> <div className={classes.rowItem}> <Label1 className={classes.label3}>Device ID</Label1> <P noMargin> <CopyToClipboard buttonClassname={classes.copyToClipboard}> {data.deviceId} </CopyToClipboard> </P> </div> </div> <div className={classes.row}> <MachineActions machine={data} onActionSuccess={onActionSuccess}></MachineActions> </div> </div> ) } export default Overview
app/javascript/mastodon/components/media_gallery.js
yi0713/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { is } from 'immutable'; import IconButton from './icon_button'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { isIOS } from '../is_mobile'; import classNames from 'classnames'; import { autoPlayGif, cropImages, displayMedia, useBlurhash } from '../initial_state'; import { debounce } from 'lodash'; import Blurhash from 'mastodon/components/blurhash'; const messages = defineMessages({ toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: '{number, plural, one {Hide image} other {Hide images}}' }, }); class Item extends React.PureComponent { static propTypes = { attachment: ImmutablePropTypes.map.isRequired, standalone: PropTypes.bool, index: PropTypes.number.isRequired, size: PropTypes.number.isRequired, onClick: PropTypes.func.isRequired, displayWidth: PropTypes.number, visible: PropTypes.bool.isRequired, autoplay: PropTypes.bool, }; static defaultProps = { standalone: false, index: 0, size: 1, }; state = { loaded: false, }; handleMouseEnter = (e) => { if (this.hoverToPlay()) { e.target.play(); } } handleMouseLeave = (e) => { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } } getAutoPlay() { return this.props.autoplay || autoPlayGif; } hoverToPlay () { const { attachment } = this.props; return !this.getAutoPlay() && attachment.get('type') === 'gifv'; } handleClick = (e) => { const { index, onClick } = this.props; if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } e.preventDefault(); onClick(index); } e.stopPropagation(); } handleImageLoad = () => { this.setState({ loaded: true }); } render () { const { attachment, index, size, standalone, displayWidth, visible } = this.props; let width = 50; let height = 100; let top = 'auto'; let left = 'auto'; let bottom = 'auto'; let right = 'auto'; if (size === 1) { width = 100; } if (size === 4 || (size === 3 && index > 0)) { height = 50; } if (size === 2) { if (index === 0) { right = '2px'; } else { left = '2px'; } } else if (size === 3) { if (index === 0) { right = '2px'; } else if (index > 0) { left = '2px'; } if (index === 1) { bottom = '2px'; } else if (index > 1) { top = '2px'; } } else if (size === 4) { if (index === 0 || index === 2) { right = '2px'; } if (index === 1 || index === 3) { left = '2px'; } if (index < 2) { bottom = '2px'; } else { top = '2px'; } } let thumbnail = ''; if (attachment.get('type') === 'unknown') { return ( <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || attachment.get('url')} style={{ cursor: 'pointer' }} title={attachment.get('description')} target='_blank' rel='noopener noreferrer'> <Blurhash hash={attachment.get('blurhash')} className='media-gallery__preview' dummy={!useBlurhash} /> </a> </div> ); } else if (attachment.get('type') === 'image') { const previewUrl = attachment.get('preview_url'); const previewWidth = attachment.getIn(['meta', 'small', 'width']); const originalUrl = attachment.get('url'); const originalWidth = attachment.getIn(['meta', 'original', 'width']); const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number'; const srcSet = hasSize ? `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w` : null; const sizes = hasSize && (displayWidth > 0) ? `${displayWidth * (width / 100)}px` : null; const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0; const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0; const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; thumbnail = ( <a className='media-gallery__item-thumbnail' href={attachment.get('remote_url') || originalUrl} onClick={this.handleClick} target='_blank' rel='noopener noreferrer' > <img src={previewUrl} srcSet={srcSet} sizes={sizes} alt={attachment.get('description')} title={attachment.get('description')} style={{ objectPosition: `${x}% ${y}%` }} onLoad={this.handleImageLoad} /> </a> ); } else if (attachment.get('type') === 'gifv') { const autoPlay = !isIOS() && this.getAutoPlay(); thumbnail = ( <div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}> <video className='media-gallery__item-gifv-thumbnail' aria-label={attachment.get('description')} title={attachment.get('description')} role='application' src={attachment.get('url')} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} autoPlay={autoPlay} loop muted /> <span className='media-gallery__gifv__label'>GIF</span> </div> ); } return ( <div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}> <Blurhash hash={attachment.get('blurhash')} dummy={!useBlurhash} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && this.state.loaded, })} /> {visible && thumbnail} </div> ); } } export default @injectIntl class MediaGallery extends React.PureComponent { static propTypes = { sensitive: PropTypes.bool, standalone: PropTypes.bool, media: ImmutablePropTypes.list.isRequired, size: PropTypes.object, height: PropTypes.number.isRequired, onOpenMedia: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, defaultWidth: PropTypes.number, cacheWidth: PropTypes.func, visible: PropTypes.bool, autoplay: PropTypes.bool, onToggleVisibility: PropTypes.func, }; static defaultProps = { standalone: false, }; state = { visible: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'), width: this.props.defaultWidth, }; componentDidMount () { window.addEventListener('resize', this.handleResize, { passive: true }); } componentWillUnmount () { window.removeEventListener('resize', this.handleResize); } componentWillReceiveProps (nextProps) { if (!is(nextProps.media, this.props.media) && nextProps.visible === undefined) { this.setState({ visible: displayMedia !== 'hide_all' && !nextProps.sensitive || displayMedia === 'show_all' }); } else if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) { this.setState({ visible: nextProps.visible }); } } handleResize = debounce(() => { if (this.node) { this._setDimensions(); } }, 250, { trailing: true, }); handleOpen = () => { if (this.props.onToggleVisibility) { this.props.onToggleVisibility(); } else { this.setState({ visible: !this.state.visible }); } } handleClick = (index) => { this.props.onOpenMedia(this.props.media, index); } handleRef = c => { this.node = c; if (this.node) { this._setDimensions(); } } _setDimensions () { const width = this.node.offsetWidth; // offsetWidth triggers a layout, so only calculate when we need to if (this.props.cacheWidth) { this.props.cacheWidth(width); } this.setState({ width: width, }); } isFullSizeEligible() { const { media } = this.props; return media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']); } render () { const { media, intl, sensitive, height, defaultWidth, standalone, autoplay } = this.props; const { visible } = this.state; const width = this.state.width || defaultWidth; let children, spoilerButton; const style = {}; if (this.isFullSizeEligible() && (standalone || !cropImages)) { if (width) { style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']); } } else if (width) { style.height = width / (16/9); } else { style.height = height; } const size = media.take(4).size; const uncached = media.every(attachment => attachment.get('type') === 'unknown'); if (standalone && this.isFullSizeEligible()) { children = <Item standalone autoplay={autoplay} onClick={this.handleClick} attachment={media.get(0)} displayWidth={width} visible={visible} />; } else { children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} autoplay={autoplay} onClick={this.handleClick} attachment={attachment} index={i} size={size} displayWidth={width} visible={visible || uncached} />); } if (uncached) { spoilerButton = ( <button type='button' disabled className='spoiler-button__overlay'> <span className='spoiler-button__overlay__label'><FormattedMessage id='status.uncached_media_warning' defaultMessage='Not available' /></span> </button> ); } else if (visible) { spoilerButton = <IconButton title={intl.formatMessage(messages.toggle_visible, { number: size })} icon='eye-slash' overlay onClick={this.handleOpen} />; } else { spoilerButton = ( <button type='button' onClick={this.handleOpen} className='spoiler-button__overlay'> <span className='spoiler-button__overlay__label'>{sensitive ? <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /> : <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />}</span> </button> ); } return ( <div className='media-gallery' style={style} ref={this.handleRef}> <div className={classNames('spoiler-button', { 'spoiler-button--minified': visible && !uncached, 'spoiler-button--click-thru': uncached })}> {spoilerButton} </div> {children} </div> ); } }
sites/all/modules/jquery_update/replace/jquery/1.10/jquery.min.js
kaypro4/cf-openshift
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,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%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
public/js/components/profile/visitor/profile.react.js
TRomesh/Coupley
import React from 'react'; import Card from 'material-ui/lib/card/card'; import CardActions from 'material-ui/lib/card/card-actions'; import CardHeader from 'material-ui/lib/card/card-header'; import FlatButton from 'material-ui/lib/flat-button'; import CardText from 'material-ui/lib/card/card-text'; import Divider from 'material-ui/lib/divider'; import ProfilePic from './ProfilePic.react'; import { Link } from 'react-router' import ProfileVisitorActions from '../../../actions/ProfileVisitorActions'; import VisitorStore from '../../../stores/VisitorStore'; import Countries from '../../register/countries.js'; const tabStyle = { marginTop: 30, marginLeft: 50, marginReft: 50 }; var str = window.location.hash; var username = str.split(/[\/?]/)[1]; var visitorUsername; const urlTable = { username: username } const Profile = React.createClass({ getInitialState: function() { let str = window.location.hash; let username = str.split(/[\/?]/)[1]; localStorage.setItem("visitor", username); visitorUsername = localStorage.getItem('visitor'); return { firstname: VisitorStore.getUserData().firstname, lastname: VisitorStore.getUserData().lastname, country: VisitorStore.getUserData().country, gender: VisitorStore.getUserData().gender, age: VisitorStore.getUserData().age, permission: VisitorStore.getPermission() } }, componentDidMount: function() { let str = window.location.hash; let username = str.split(/[\/?]/)[1]; VisitorStore.addChangeListener(this._onChange); ProfileVisitorActions.loadProfileData(username); }, componentWillUnmount: function() { ProfileVisitorActions.clearAll(); }, _onChange: function() { this.setState({ firstname: VisitorStore.getUserData().firstname, lastname: VisitorStore.getUserData().lastname, country: VisitorStore.getUserData().country, gender: VisitorStore.getUserData().gender, age: VisitorStore.getUserData().age, permission: VisitorStore.getPermission() }); }, _renderCountry: function() { var found = false; for(var i = 0; i < Countries.length; i++) { if (Countries[i].code == this.state.country) { found = true; this.setState({ country: Countries[i].name }) break; } } }, render: function() { return ( <div> <div className="panel panel-default"> <ProfilePic firstname={this.state.firstname} lastname={this.state.lastname} country={this.state.country} gender={this.state.gender} age={this.state.age}/> <Divider /> <div style={tabStyle}> <div className="btn-group btn-group-justified btn-group-info"> <Link to={'/' + visitorUsername + '/activityfeed'} className="btn ">My Activity Feed</Link> <Link to={'/' + visitorUsername + '/about'} className="btn ">About</Link> {this.state.permission ? <Link to={'/' + visitorUsername + '/photos'} className="btn ">Photos</Link> : <Link to="" className="btn "></Link>} </div> </div> {this._renderCountry()} </div> {this.props.children} </div> ); } }); export default Profile;
v21/v21.0.0/sdk/registerrootcomponent.js
ccheever/expo-docs
import markdown from 'markdown-in-js' import withDoc, { components } from '~/lib/with-doc' import { expoteam } from '~/data/team' // import { InternalLink, ExternalLink } from "~/components/text/link"; // import { P } from "~/components/text/paragraph"; // import Image from '~/components/base/image' import { Code } from '~/components/base/code' // import SnackEmbed from '~/components/plugins/snack-embed' // import { // TerminalInput, // TerminalOutput // } from "~/components/text/terminal"; // prettier-ignore export default withDoc({ title: 'registerRootComponent', authors: [expoteam], })(markdown(components)` ### Expo.registerRootComponent(component) Sets the main component for Expo to use for your app. > **Note: ** Prior to SDK 18, it was necessary to use \`registerRootComponent\` directly, but for projects created as of SDK 18 or later, this is handled automatically in the Expo SDK. #### Arguments - **component (ReactComponent)** -- The React component class that renders the rest of your app. #### Returns No return value. > **Note:** \`Expo.registerRootComponent\` is roughly equivalent to React Native's [AppRegistry.registerComponent](https://facebook.github.io/react-native/docs/appregistry.html), with some additional hooks to provide Expo specific functionality. ## Common questions ### I created my project before SDK 18 and I want to remove Expo.registerRootComponent, how do I do this? - Before continuing, make sure your project is running on SDK 18 or later. - Open up \`main.js\` (or if you changed it, whatever your \`"main"\` is in \`package.json\`). - Set \`"main"\` to \`"node_modules/expo/AppEntry.js"\`. - Delete the \`Expo.registerRootComponent\` call from \`main.js\` and put \`export default\` before your root component's class declaration. - Rename \`main.js\` to \`App.js\`. ### What if I want to name my main app file something other than App.js? You can set the \`"main"\` in \`package.json\` to any file within your project. If you do this, then you need to use \`registerRootComponent\`; \`export default\` will not make this component the root for the Expo app if you are using a custom entry file. For example, let's say you want to make \`"src/main.js"\` the entry file for your app -- maybe you don't like having JavaScript files in the project root, for example. First, set this in \`package.json\`: ${<Code>{` { 'main': 'src/main.js' } `}</Code>} Then in \`"src/main.js"\`, make sure you call \`registerRootComponent\` and pass in the component you want to render at the root of the app. ${<Code>{` import Expo from 'expo'; import React from 'react'; import { View } from 'react-native'; class App extends React.Component { render() { return <View />; } } Expo.registerRootComponent(App); `}</Code>} `)
docs/0.6d3799bc16004a89cfb9.js
quark-ui/quark-ui
webpackJsonp([0],{"/3hJ":function(e,t){e.exports='import Popover from \'../Popover\';\nimport { Component } from \'react\';\nimport Button from \'../../button/Button\';\n// import CSSModules from \'react-css-modules\';\nimport { allowMultiple } from \'../../../constants\';\nimport styles from \'./index.css\';\n\nexport default class PopoverDemo extends Component {\n render() {\n const ele = (<div><p>top</p><p>这是一个气泡框</p></div>);\n return (\n <div>\n <div className={styles[\'top-tooltip\']}>\n <div className={styles[\'top-tooltip-div\']}><Popover title="标题" popovers="topLeft" placement="topLeft" ><Button type="secondary">上左</Button></Popover></div>\n <div className={styles[\'top-tooltip-div\']}><Popover title="标题" popovers={ele} placement="top" action="click" hasButton={true}><Button type="secondary">点击</Button></Popover></div>\n <div className={styles[\'top-tooltip-div\']}><Popover popovers="topRight" placement="topRight" ><Button type="secondary">上右</Button></Popover></div>\n </div>\n <div className={styles[\'left-tooltip\']} >\n <div className={styles[\'left-tooltip-div\']}><Popover popovers=\'leftTop\' placement="leftTop" ><Button type="secondary">左上</Button></Popover></div>\n <div className={styles[\'left-tooltip-div\']}><Popover popovers=\'left\' placement="left" ><Button type="secondary">左</Button></Popover></div>\n <div className={styles[\'left-tooltip-div\']}><Popover popovers=\'leftBottom\' placement="leftBottom" ><Button type="secondary">左下</Button></Popover></div>\n </div>\n <div className={styles[\'right-tooltip\']} >\n <div className={styles[\'right-tooltip-div\']}><Popover popovers="rightTop" placement="rightTop" ><Button type="secondary">右上</Button></Popover></div>\n <div className={styles[\'right-tooltip-div\']}><Popover popovers="right" placement="right" ><Button type="secondary">右</Button></Popover></div>\n <div className={styles[\'right-tooltip-div\']}><Popover popovers="rightBottom" placement="rightBottom" ><Button type="secondary">左下</Button></Popover></div>\n </div>\n <div className={styles[\'bottom-tooltip\']}>\n <div className={styles[\'bottom-tooltip-div\']}><Popover popovers="bottomLeft" placement="bottomLeft" ><Button type="secondary">下左</Button></Popover></div>\n <div className={styles[\'bottom-tooltip-div\']}><Popover popovers="bottom" placement="bottom"><Button type="secondary">下</Button></Popover></div>\n <div className={styles[\'bottom-tooltip-div\']}><Popover popovers="bottomRight" placement="bottomRight"><Button type="secondary">下右</Button></Popover></div>\n </div>\n </div>\n );\n }\n}\n'},"0P4F":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return r});var a=n("Jmof"),l=(n.n(a),n("lkey")),o=n("UJDU"),s=n("Pp2j"),i=n("WB2H"),r=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e=()=>{o.a.config({placement:"bottomRight",bottom:50,duration:0}),i.a.success("全局配置成功")},t=()=>{o.a.open({message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})},n=e=>{o.a.open({placement:e,message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})};return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本使用"),React.createElement("p",null,"最简单的用法,4.5 秒后自动关闭"),React.createElement(l.a,{onClick:t},"显示通知")," ",React.createElement("h3",null,"带有图标的通知提醒框"),React.createElement("p",null,"通知提醒框左侧有图标"),React.createElement(l.a,{onClick:()=>{o.a.open({type:"info",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"消息")," ",React.createElement(l.a,{onClick:()=>{o.a.open({type:"success",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"成功")," ",React.createElement(l.a,{onClick:()=>{o.a.open({type:"error",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"错误")," ",React.createElement(l.a,{onClick:()=>{o.a.open({type:"warning",message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案"})}},"警告")," ",React.createElement("h3",null,"自定义图标"),React.createElement("p",null,"可自定义图标"),React.createElement(l.a,{onClick:()=>{o.a.open({message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案",duration:0,icon:React.createElement(s.a,{style:{width:"34px",height:"34px",top:"16px",left:"24px",position:"absolute"},name:"clock"})})}},"自定义")," ",React.createElement("h3",null,"自动关闭的延时"),React.createElement("p",null,"取消4.5秒自动关闭"),React.createElement(l.a,{onClick:()=>{o.a.open({message:"需要及时知道的系统通知",description:"文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案",duration:0})}},"显示通知")," ",React.createElement("h3",null,"自定义按钮"),React.createElement("p",null,"可以置入功能按钮"),React.createElement(l.a,{onClick:()=>{var e=`open${Date.now()}`,t=()=>{o.a.close(e)},n=React.createElement("div",null,React.createElement(l.a,{type:"primary",onClick:t},"立即更新")," ",React.createElement(l.a,{type:"secondary",onClick:t},"今晚提醒"));o.a.open({type:"warning",message:"请更新系统",description:"如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。",key:e,btn:n})}},"按钮功能")," ",React.createElement(l.a,{onClick:()=>{var e=React.createElement("a",{href:"./notification"},"查看");o.a.open({type:"warning",message:"请更新系统",description:"如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。",btn:e})}},"链接功能")," ",React.createElement("h3",null,"位置"),React.createElement("p",null,"从右上角、右下角、左下角、左上角弹出"),React.createElement(l.a,{onClick:()=>n("topRight")},"右上角")," ",React.createElement(l.a,{onClick:()=>n("topLeft")},"左上角")," ",React.createElement(l.a,{onClick:()=>n("bottomLeft")},"左下角")," ",React.createElement(l.a,{onClick:()=>n("bottomRight")},"右下角")," ",React.createElement("h3",null,"全局配置"),React.createElement("p",null,"在调用前提前配置,全局一次生效"),React.createElement("p",null,`notification.config({\n placement: 'bottomRight',\n bottom:50,\n duration:0,\n getContainer:'App'\n });`),React.createElement(l.a,{onClick:()=>e()},"配置")," ",React.createElement(l.a,{onClick:t},"显示通知")," ")}}},"0h7d":function(e,t){e.exports="import { Component } from 'react';\nimport Icon from '../../icon';\nimport Radio from '../../radio';\nimport Button from '../../button';\nimport Tabs from '../Tabs';\nconst Panel = Tabs.Panel;\n\nclass TabsDemo1 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <p>标准线条式页签</p>\n <Tabs\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\nclass TabsDemo2 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>禁用</h3>\n <p>对某项实行禁用</p>\n <Tabs\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 1</span>} key=\"1\">\n Tab 1\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 2</span>} key=\"2\">\n Tab 2\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 3</span>} key=\"3\" disabled >\n Tab 3\n </Panel>\n </Tabs>\n </div>\n );\n }\n}\n\nclass TabsDemo3 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>迷你</h3>\n <p>用在狭小的区块或子级Tab</p>\n <Tabs\n size={'small'}\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\n\nclass TabsDemo4 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>带图标</h3>\n <p>带图标的Tab</p>\n <Tabs\n activeKey={this.state.activeKey}\n onClick={this.onClick}\n >\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 1</span>} key=\"1\">\n Tab 1\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 2</span>} key=\"2\">\n Tab 2\n </Panel>\n <Panel title={<span><Icon size={18} name=\"account\" />Tab 3</span>} key=\"3\" >\n Tab 3\n </Panel>\n </Tabs>\n </div>\n );\n }\n}\n\n\nclass TabsDemo5 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>纵向</h3>\n <p>纵向的Tab</p>\n <Tabs\n activeKey={this.state.activeKey}\n tabPosition={'left'}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\n\nclass TabsDemo6 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>卡片式</h3>\n <p>卡片式的页签,常用于容器顶部</p>\n <Tabs\n activeKey={this.state.activeKey}\n type={'card'}\n tabDeleteButton\n deleteButton={this.deleteButton}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\nclass TabsDemo7 extends Component {\n constructor(props) {\n super(props);\n const panes = [\n { title: 'Tab 1', content: 'Content of Tab 1', key: 1, closable: false },\n { title: 'Tab 2', content: 'Content of Tab 2', key: 2 },\n { title: 'Tab 3', content: 'Content of Tab 3', key: 3 },\n ];\n\n this.state = {\n activeKey: panes[0].key,\n panes,\n };\n }\n\n deleteButton = () => {\n const data = this.state.panes;\n let activeKey = this.state.activeKey;\n data.splice(activeKey, 1);\n\n if (data.length <= activeKey + 1) { activeKey = data.length - 1; }\n this.setState({\n panes: data,\n activeKey,\n });\n }\n\n onClick = (key) => {\n this.setState({ activeKey: key });\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <p>button可作为更次级的页签来使用</p>\n <Tabs\n activeKey={this.state.activeKey}\n type={'button'}\n onClick={this.onClick}\n >\n {this.state.panes.map(pane => <Panel title={pane.title} key={pane.key} closable={pane.closable}>{pane.content}</Panel>)}\n </Tabs>\n </div>\n );\n }\n}\n\nexport default class TabsDemo extends Component {\n render() {\n return (\n <div className=\"markdown-block\">\n <TabsDemo1 />\n <br /><br />\n <TabsDemo2 />\n <br /><br />\n <TabsDemo3 />\n <br /><br />\n <TabsDemo4 />\n <br /><br />\n <TabsDemo5 />\n <br /><br />\n <TabsDemo6 />\n <br /><br />\n <TabsDemo7 />\n <br /><br />\n </div>\n );\n }\n}\n"},"13mF":function(e,t,n){"use strict";function a(e,t){if(t)for(var n=Object.keys(t),a=0,l=n.length;a<l;a++)e[n[a]]=t[n[a]];return e}function l(e){return a({},e)}function o(e){var t=l(p);if(e)for(var n=Object.keys(e),a=0,o=n.length;a<o;a++){var s=n[a];null==e[s]?delete t[s]:t[s]=e[s]}return t}function s(e,t,n,a){if(!(this instanceof s))return new s(e,t,n);this.placeholderChar=n||u,this.formatCharacters=t||p,this.source=e,this.pattern=[],this.length=0,this.firstEditableIndex=null,this.lastEditableIndex=null,this._editableIndices={},this.isRevealingMask=a||!1,this._parse()}function i(e){if(!(this instanceof i))return new i(e);if(null==(e=a({formatCharacters:null,pattern:null,isRevealingMask:!1,placeholderChar:u,selection:{start:0,end:0},value:""},e)).pattern)throw new Error("InputMask: you must provide a pattern.");if("string"!=typeof e.placeholderChar||e.placeholderChar.length>1)throw new Error("InputMask: placeholderChar should be a single character or an empty string.");this.placeholderChar=e.placeholderChar,this.formatCharacters=o(e.formatCharacters),this.setPattern(e.pattern,{value:e.value,selection:e.selection,isRevealingMask:e.isRevealingMask})}var r=/^\d$/,c=/^[A-Za-z]$/,m=/^[\dA-Za-z]$/,u="_",p={"*":{validate:function(e){return m.test(e)}},1:{validate:function(e){return r.test(e)}},a:{validate:function(e){return c.test(e)}},A:{validate:function(e){return c.test(e)},transform:function(e){return e.toUpperCase()}},"#":{validate:function(e){return m.test(e)},transform:function(e){return e.toUpperCase()}}};s.prototype._parse=function(){for(var e=this.source.split(""),t=0,n=[],a=0,l=e.length;a<l;a++){var o=e[a];if("\\"===o){if(a===l-1)throw new Error("InputMask: pattern ends with a raw \\");o=e[++a]}else o in this.formatCharacters&&(null===this.firstEditableIndex&&(this.firstEditableIndex=t),this.lastEditableIndex=t,this._editableIndices[t]=!0);n.push(o),t++}if(null===this.firstEditableIndex)throw new Error('InputMask: pattern "'+this.source+'" does not contain any editable characters.');this.pattern=n,this.length=n.length},s.prototype.formatValue=function(e){for(var t=new Array(this.length),n=0,a=0,l=this.length;a<l;a++)if(this.isEditableIndex(a)){if(this.isRevealingMask&&e.length<=n&&!this.isValidAtIndex(e[n],a))break;t[a]=e.length>n&&this.isValidAtIndex(e[n],a)?this.transform(e[n],a):this.placeholderChar,n++}else t[a]=this.pattern[a],e.length>n&&e[n]===this.pattern[a]&&n++;return t},s.prototype.isEditableIndex=function(e){return!!this._editableIndices[e]},s.prototype.isValidAtIndex=function(e,t){return this.formatCharacters[this.pattern[t]].validate(e)},s.prototype.transform=function(e,t){var n=this.formatCharacters[this.pattern[t]];return"function"==typeof n.transform?n.transform(e):e},i.prototype.input=function(e){if(this.selection.start===this.selection.end&&this.selection.start===this.pattern.length)return!1;var t=l(this.selection),n=this.getValue(),a=this.selection.start;if(a<this.pattern.firstEditableIndex&&(a=this.pattern.firstEditableIndex),this.pattern.isEditableIndex(a)){if(!this.pattern.isValidAtIndex(e,a))return!1;this.value[a]=this.pattern.transform(e,a)}for(var o=this.selection.end-1;o>a;)this.pattern.isEditableIndex(o)&&(this.value[o]=this.placeholderChar),o--;for(this.selection.start=this.selection.end=a+1;this.pattern.length>this.selection.start&&!this.pattern.isEditableIndex(this.selection.start);)this.selection.start++,this.selection.end++;return null!=this._historyIndex&&(this._history.splice(this._historyIndex,this._history.length-this._historyIndex),this._historyIndex=null),("input"!==this._lastOp||t.start!==t.end||null!==this._lastSelection&&t.start!==this._lastSelection.start)&&this._history.push({value:n,selection:t,lastOp:this._lastOp}),this._lastOp="input",this._lastSelection=l(this.selection),!0},i.prototype.backspace=function(){if(0===this.selection.start&&0===this.selection.end)return!1;var e=l(this.selection),t=this.getValue();if(this.selection.start===this.selection.end)this.pattern.isEditableIndex(this.selection.start-1)&&(this.value[this.selection.start-1]=this.placeholderChar),this.selection.start--,this.selection.end--;else{for(var n=this.selection.end-1;n>=this.selection.start;)this.pattern.isEditableIndex(n)&&(this.value[n]=this.placeholderChar),n--;this.selection.end=this.selection.start}return null!=this._historyIndex&&this._history.splice(this._historyIndex,this._history.length-this._historyIndex),("backspace"!==this._lastOp||e.start!==e.end||null!==this._lastSelection&&e.start!==this._lastSelection.start)&&this._history.push({value:t,selection:e,lastOp:this._lastOp}),this._lastOp="backspace",this._lastSelection=l(this.selection),!0},i.prototype.paste=function(e){var t={value:this.value.slice(),selection:l(this.selection),_lastOp:this._lastOp,_history:this._history.slice(),_historyIndex:this._historyIndex,_lastSelection:l(this._lastSelection)};if(this.selection.start<this.pattern.firstEditableIndex){for(var n=0,o=this.pattern.firstEditableIndex-this.selection.start;n<o;n++)if(e.charAt(n)!==this.pattern.pattern[n])return!1;e=e.substring(this.pattern.firstEditableIndex-this.selection.start),this.selection.start=this.pattern.firstEditableIndex}for(n=0,o=e.length;n<o&&this.selection.start<=this.pattern.lastEditableIndex;n++)if(!this.input(e.charAt(n))){if(this.selection.start>0){var s=this.selection.start-1;if(!this.pattern.isEditableIndex(s)&&e.charAt(n)===this.pattern.pattern[s])continue}return a(this,t),!1}return!0},i.prototype.undo=function(){if(0===this._history.length||0===this._historyIndex)return!1;var e;if(null==this._historyIndex){this._historyIndex=this._history.length-1,e=this._history[this._historyIndex];var t=this.getValue();e.value===t&&e.selection.start===this.selection.start&&e.selection.end===this.selection.end||this._history.push({value:t,selection:l(this.selection),lastOp:this._lastOp,startUndo:!0})}else e=this._history[--this._historyIndex];return this.value=e.value.split(""),this.selection=e.selection,this._lastOp=e.lastOp,!0},i.prototype.redo=function(){if(0===this._history.length||null==this._historyIndex)return!1;var e=this._history[++this._historyIndex];return this._historyIndex===this._history.length-1&&(this._historyIndex=null,e.startUndo&&this._history.pop()),this.value=e.value.split(""),this.selection=e.selection,this._lastOp=e.lastOp,!0},i.prototype.setPattern=function(e,t){t=a({selection:{start:0,end:0},value:""},t),this.pattern=new s(e,this.formatCharacters,this.placeholderChar,t.isRevealingMask),this.setValue(t.value),this.emptyValue=this.pattern.formatValue([]).join(""),this.selection=t.selection,this._resetHistory()},i.prototype.setSelection=function(e){if(this.selection=l(e),this.selection.start===this.selection.end){if(this.selection.start<this.pattern.firstEditableIndex)return this.selection.start=this.selection.end=this.pattern.firstEditableIndex,!0;for(var t=this.selection.start;t>=this.pattern.firstEditableIndex;){if(this.pattern.isEditableIndex(t-1)&&this.value[t-1]!==this.placeholderChar||t===this.pattern.firstEditableIndex){this.selection.start=this.selection.end=t;break}t--}return!0}return!1},i.prototype.setValue=function(e){null==e&&(e=""),this.value=this.pattern.formatValue(e.split(""))},i.prototype.getValue=function(){return this.value.join("")},i.prototype.getRawValue=function(){for(var e=[],t=0;t<this.value.length;t++)!0===this.pattern._editableIndices[t]&&e.push(this.value[t]);return e.join("")},i.prototype._resetHistory=function(){this._history=[],this._historyIndex=null,this._lastOp=null,this._lastSelection=l(this.selection)},i.Pattern=s,e.exports=i},"1nuA":function(e,t,n){"use strict";t.decode=t.parse=n("kMPS"),t.encode=t.stringify=n("xaZU")},"1ptM":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return m});var a=n("Jmof"),l=(n.n(a),n("rEdb")),o=n("lkey"),s=l.a.Group,i=["Apple","Pear","Orange"],r=["Apple","Orange"],c=e=>{console.log(e.target.checked,e.target.value)},m=class extends a.Component{constructor(e){super(e),this.handleToggleDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.handleToggleChecked=(()=>{this.setState({checked:!this.state.checked})}),this.handleChange=(e=>{this.setState({checkedList:e,checkAll:e.length===i.length})}),this.handleAllChange=(e=>{this.setState({checkedList:e.target.checked?i:[],checkAll:e.target.checked})}),this.state={disabled:!1,checked:!0,checkedList:r,checkAll:!1}}render(){var e=this.state,t=e.checked,n=e.disabled,a=e.checkedList,r=e.checkAll;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"全选"),React.createElement("p",null,React.createElement(l.a,{checked:r,disabled:n,onChange:this.handleAllChange}," 全选")),React.createElement(s,{options:i,value:a,disabled:n,onChange:this.handleChange}),React.createElement("h3",null,"一组checkbox"),React.createElement("div",null,React.createElement(s,{onChange:e=>{this.checkValue.innerHTML=e},disabled:n},React.createElement(l.a,{value:"A"}," A"),React.createElement(l.a,{value:"B"}," B"),React.createElement(l.a,{value:"C"}," C"),React.createElement(l.a,{value:"D"}," D"))),React.createElement("p",{ref:e=>{this.checkValue=e}}),React.createElement("h3",null,"受控方式"),React.createElement("p",null,React.createElement(l.a,{checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("p",null,React.createElement(l.a,{checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("p",null,React.createElement(l.a,{name:"my-check",checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("p",null,React.createElement(l.a,{name:"my-check",checked:t,disabled:n,onChange:this.handleToggleChecked}," 受控的CheckBox组件")),React.createElement("h3",null,"非受控方式"),React.createElement("p",null,React.createElement(l.a,{defaultChecked:!0,disabled:n,onChange:c}," 非控的CheckBox组件")),React.createElement(o.a,{onClick:this.handleToggleDisabled},n?"启用":"禁用")," ",React.createElement(o.a,{onClick:this.handleToggleChecked},t?"取消选中":"选中"))}}},"2YTV":function(e,t){e.exports="import { Component } from 'react';\nimport Checkbox from '../Checkbox';\n// import {Checkbox} from 'antd'\nimport Button from '../../button';\n\n\nconst CheckboxGroup = Checkbox.Group;\nconst plainOptions = ['Apple', 'Pear', 'Orange'];\nconst defaultCheckedList = ['Apple', 'Orange'];\nconst onChange = (e) => {\n console.log(e.target.checked, e.target.value);\n};\nexport default class CheckboxDemo extends Component {\n constructor(props) {\n super(props);\n\n this.state = {\n disabled: false,\n checked: true,\n\n checkedList: defaultCheckedList,\n checkAll: false,\n };\n }\n\n handleToggleDisabled=() => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n handleToggleChecked=() => {\n this.setState({\n checked: !this.state.checked,\n });\n }\n\n handleChange=(checkedList) => {\n this.setState({\n checkedList,\n checkAll: checkedList.length === plainOptions.length,\n });\n }\n\n handleAllChange=(e) => {\n // const { checkedList, checkAll } = this.state;\n this.setState({\n checkedList: e.target.checked ? plainOptions : [],\n checkAll: e.target.checked,\n });\n }\n\n\n render() {\n const { checked, disabled, checkedList, checkAll } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>全选</h3>\n <p>\n <Checkbox\n checked={checkAll}\n disabled={disabled}\n onChange={this.handleAllChange}\n >&nbsp;全选</Checkbox>\n </p>\n <CheckboxGroup\n options={plainOptions}\n value={checkedList}\n disabled={disabled}\n onChange={this.handleChange}\n />\n\n <h3>一组checkbox</h3>\n <div>\n <CheckboxGroup onChange={(v) => { this.checkValue.innerHTML = v; }} disabled={disabled}>\n <Checkbox value=\"A\"> A</Checkbox>\n <Checkbox value=\"B\"> B</Checkbox>\n <Checkbox value=\"C\"> C</Checkbox>\n <Checkbox value=\"D\"> D</Checkbox>\n </CheckboxGroup>\n </div>\n <p ref={(v) => { this.checkValue = v; }} />\n <h3>受控方式</h3>\n <p>\n <Checkbox\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n >&nbsp;受控的CheckBox组件</Checkbox>\n </p>\n <p>\n <Checkbox\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n >&nbsp;受控的CheckBox组件</Checkbox>\n </p>\n <p>\n <Checkbox\n name=\"my-check\"\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n >&nbsp;受控的CheckBox组件</Checkbox>\n </p>\n <p>\n <Checkbox\n name=\"my-check\"\n checked={checked}\n disabled={disabled}\n onChange={this.handleToggleChecked}\n >&nbsp;受控的CheckBox组件</Checkbox>\n </p>\n <h3>非受控方式</h3>\n <p>\n <Checkbox\n defaultChecked\n disabled={disabled}\n onChange={onChange}\n >&nbsp;非控的CheckBox组件</Checkbox>\n </p>\n <Button onClick={this.handleToggleDisabled}>{disabled ? '启用' : '禁用'}</Button>&nbsp;\n <Button onClick={this.handleToggleChecked}>{checked ? '取消选中' : '选中'}</Button>\n </div>\n );\n }\n}\n"},"3lqj":function(e,t){e.exports="---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n email: [email protected]\n---\n\n## Menu\n\nMenu Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|String|inline|菜单类型,可选值:horizontal-h(水平菜单,子菜单水平),horizontal-v(水平菜单,子菜单垂直),vertical-h(垂直菜单,子菜单水平向右弹出),vertical-v(垂直菜单,子菜单内嵌在菜单区域)|\n|colorType|String|warm|颜色,可选值:warm(暖色),cold(冷色)|\n|selectedKeys|string[]|[]|选中的菜单项,数组,值为key|\n|defaultOpenKeys|string[]|[]|默认打开的菜单,数组,值为key|\n|onClick|function|null|点击 menuitem 调用此函数,参数为 {item, key, keyPath}|\n|onOpenChange|function|null|点击 menuitem 调用此函数,参数为 {item, key, keyPath}|\n\n### Api"},"5krA":function(e,t){e.exports="import { Component } from 'react';\nimport moment from 'moment';\nimport DatePicker from '../index';\nimport Checkbox from '../../checkbox';\n\nconst { MonthPicker, RangePicker } = DatePicker;\n\nexport default class DatePickerDemo extends Component {\n state = {\n disabled: false,\n date: moment().add(1, 'M'),\n }\n onChange(m) {\n console.log(m);\n }\n changeDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n render() {\n const { date, disabled } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>\n <Checkbox\n checked={disabled}\n onChange={this.changeDisabled}\n >\n 禁用\n </Checkbox>\n </h3>\n \n <h3>日期选择</h3>\n <table>\n <thead>\n <tr>\n <th>非受控方式</th>\n <th>受控方式</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <DatePicker\n disabled={disabled}\n onChange={this.onChange}\n />\n </td>\n <td style={{position: 'relative'}}>\n <DatePicker\n disabled={disabled}\n value={date}\n onChange={(d) => {\n this.setState({\n date: d,\n });\n }}\n />\n <p style={{position: 'absolute', right: '20px', top: '15px'}}>选择时间: {date.format()}</p>\n </td>\n </tr>\n </tbody>\n </table>\n \n <h3>不可选日期</h3>\n <p>可用 disabledDate 禁止选择部分日期</p>\n <DatePicker\n disabled={disabled}\n disabledDate={(current) => {\n return current && current.valueOf() < Date.now();\n }}\n ></DatePicker>\n <h3>月份选择</h3>\n <MonthPicker onChange={this.onChange} disabled={disabled} />\n <h3>预设范围</h3>\n <p>RangePicker 可以设置常用的 预设范围 提高用户体验。</p>\n <RangePicker onChange={this.onChange} disabled={disabled} />\n </div>\n );\n }\n}\n"},"5oN3":function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Dropdown\n\nDropdown Component.\n\n### Props\n\n#### Dropdown\n|name|type|default|description|\n|---|---|---|---|\n|trigger|`hover` or `click`|click|触发方式|\n|overlay|element|-|菜单内容|\n|placement|string|bottomLeft|定位|\n\n#### Dropdown.DropdownButton\n|name|type|default|description|\n|---|---|---|---|\n|type|string|`primary`|按钮类型|\n|trigger|`hover` or `click`|click|触发方式|\n|overlay|element|-|菜单内容|\n|placement|string|bottomRight|定位|\n\n#### Dropdown.Menu\n|name|type|default|description|\n|---|---|---|---|\n\n#### Dropdown.Menu.Item\n|name|type|default|description|\n|---|---|---|---|\n\n### Api"},"5xuW":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return o});var a=n("Jmof"),l=(n.n(a),n("kbwb")),o=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"按钮类型"),React.createElement("p",null,"按钮有四种类型:主按钮、次按钮、虚线按钮、危险按钮。主按钮在同一个操作区域最多出现一次。"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"主按钮"),React.createElement("th",null,"次按钮"),React.createElement("th",null,"虚线按钮"),React.createElement("th",null,"危险按钮"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(l.a,{type:"primary"},"主按钮")),React.createElement("td",null,React.createElement(l.a,{type:"secondary"},"次按钮")),React.createElement("td",null,React.createElement(l.a,{type:"dashed"},"虚线按钮")),React.createElement("td",null,React.createElement(l.a,{type:"danger"},"危险按钮"))))),React.createElement("h3",null,"按钮尺寸"),React.createElement("p",null,"按钮有大、中、小三种尺寸。"),React.createElement("p",null,"通过设置 size 为 large small 分别把按钮设为大、小尺寸。若不设置 size,则尺寸为中。"),React.createElement(l.a,{size:"large"},"主要按钮(大)")," ",React.createElement(l.a,null,"主要按钮(中)")," ",React.createElement(l.a,{size:"small"},"主要按钮(小)"),React.createElement("h3",null,"不可用状态"),React.createElement("p",null,"添加 disabled 属性即可让按钮处于不可用状态,同时按钮样式也会改变。"),React.createElement(l.a,{size:"large",disabled:!0},"不可用按钮")," ",React.createElement(l.a,{disabled:!0},"不可用按钮")," ",React.createElement(l.a,{size:"small",disabled:!0},"不可用按钮"))}}},"6wLY":function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/october-yan/\n---\n\n## Input\n\n通过鼠标或键盘输入内容,是最基础的表单域的包装。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|String|'text'|button type, `text` or `textarea`|\n|value|String||输入框内容|\n|defaultValue|String||输入框默认内容|\n|prefix|string ReactNode||带有前缀图标的 input|\n|suffix|string ReactNode||带有后缀图标的 input|\n|size|String|'normal'|input size, `normal` `large` or `small` |\n|disabled|boolean|'false'|input disabled, `false` or `true` |\n\n##### Input.Search\n|name|type|default|description|\n|---|---|---|---|\n|onSearch|function(value)||点击搜索回调|\n\n\n### Api"},"7Lsv":function(e,t){e.exports="import { Component } from 'react';\nimport Icon from '../Icon';\nimport styles from './index.css';\nimport Icons from '../icons/';\n\nconst IconList = Object.keys(Icons);\n\nexport default class IconDemo extends Component {\n state = {\n color: document.documentElement.style.getPropertyValue('--brand-primary'),\n }\n componentDidMount() {\n if (typeof MutationObserver === 'function') {\n const observer = new MutationObserver((mutations) => {\n mutations.forEach(() => {\n this.setState({\n color: document.documentElement.style.getPropertyValue('--brand-primary'),\n });\n });\n });\n\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['style'],\n });\n }\n }\n render() {\n return (\n <div className={styles.Icon__wrap}>\n {\n IconList.map(name => (\n <div className={styles.Icon__grid} key={name}>\n <Icon size={36} name={name} color={this.state.color} />\n <span className={styles.Icon__name}>{name}</span>\n </div>\n ))\n }\n </div>\n );\n }\n}\n"},"7nwc":function(e,t,n){var a=n("LXsE");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},"8fnD":function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Pagination\n\n采用分页的形式分隔长列表,每次只加载一个页面。\n\n### 何时使用\n\n- 当加载/渲染所有数据将花费很多时间时;\n- 可切换页码浏览数据。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n| current | number | - | 当前页数 |\n| current | number | 1 | 默认当前页数 |\n| total | number | 0 | 总数 |\n| pageSize | number | - | 每页条数 |\n| defaultPageSize | number | 10 | 默认每页条数 |\n| onChange | function(page, pageSize) | noop | 页码改变回调,参数 |\n| showSizeChanger | boolean | false | 显示分页条数选择 |\n| onSizeChange | function(size, current) | noop | pageSize 变化回调 |\n| pageSizeOptions| number[] | [10, 20, 30, 40] | 指定每页可以显示多少条 |\n| showQuickJumper| boolean | false | 是否展示跳转输入框 |\n| size| string | '' | `small` 指定小尺寸分页 |\n| showTotal | boolean | false | 展示总数 |\n\n### Api"},"8ovY":function(e,t){e.exports='import { Component } from \'react\';\nimport Button from \'../Button\';\n\nexport default class ButtonDemo extends Component {\n render() {\n return (\n <div className="markdown-block">\n <h3>按钮类型</h3>\n <p>按钮有四种类型:主按钮、次按钮、虚线按钮、危险按钮。主按钮在同一个操作区域最多出现一次。</p>\n <table>\n <thead>\n <tr>\n <th>主按钮</th>\n <th>次按钮</th>\n <th>虚线按钮</th>\n <th>危险按钮</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td><Button type="primary">主按钮</Button></td>\n <td><Button type="secondary">次按钮</Button></td>\n <td><Button type="dashed">虚线按钮</Button></td>\n <td><Button type="danger">危险按钮</Button></td>\n </tr>\n </tbody>\n </table>\n <h3>按钮尺寸</h3>\n <p>按钮有大、中、小三种尺寸。</p>\n <p>通过设置 size 为 large small 分别把按钮设为大、小尺寸。若不设置 size,则尺寸为中。</p>\n <Button size="large">主要按钮(大)</Button>\n &nbsp;\n <Button>主要按钮(中)</Button>\n &nbsp;\n <Button size="small">主要按钮(小)</Button>\n <h3>不可用状态</h3>\n <p>添加 disabled 属性即可让按钮处于不可用状态,同时按钮样式也会改变。</p>\n <Button size="large" disabled>不可用按钮</Button>\n &nbsp;\n <Button disabled>不可用按钮</Button>\n &nbsp;\n <Button size="small" disabled>不可用按钮</Button>\n </div>\n );\n }\n}\n'},"8wBc":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("tObA")),o=n("o8IH"),s=n("lkey"),i=n("KIYf"),r=n.n(i),c=class extends a.Component{constructor(e){super(e),this.swichHandle1=(()=>{this.setState({isShow1:!this.state.isShow1})}),this.swichHandle2=(()=>{this.setState({isShow2:!this.state.isShow2})}),this.state={isShow1:!0,isShow2:!1}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本用法"),React.createElement(l.a,null),React.createElement("h3",null,"自定义大小"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"小"),React.createElement("th",null,"中"),React.createElement("th",null,"大"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(l.a,{size:"small"})),React.createElement("td",null,React.createElement(l.a,{size:"default"})),React.createElement("td",null,React.createElement(l.a,{size:"large"}))))),React.createElement("h3",null,"自定义描述文案"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"小"),React.createElement("th",null,"中"),React.createElement("th",null,"大"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(l.a,{size:"small",tip:"loading..."})),React.createElement("td",null,React.createElement(l.a,{size:"default",tip:"loading..."})),React.createElement("td",null,React.createElement(l.a,{size:"large",tip:"loading..."}))))),React.createElement("h3",null,"容器中使用"),React.createElement("div",{className:r.a.example1},React.createElement(l.a,null)),React.createElement("div",{className:r.a.example1},React.createElement(l.a,{tip:"loading..."})),React.createElement("h3",null,"提示中使用"),React.createElement("div",null,React.createElement(l.a,{spinning:this.state.isShow1},React.createElement(o.a,{type:"info",message:"警告提示内容",description:`警告提示的辅助性文字介绍警告提示的辅助\n 性文字介绍警告提示的辅助性文字介绍警告提示的辅助性文\n 字介绍警告提示的辅助性文字介绍警告提示的辅助性文字介\n 绍警告提示的辅助性文字介绍警告提示的辅助性文字介绍警\n 告提示的辅助性文字介绍警告提示的辅助性文字介绍`})),React.createElement("p",null,React.createElement(s.a,{type:"primary",onClick:this.swichHandle1},"显示/隐藏"))),React.createElement("h3",null,"延迟"),React.createElement("div",null,React.createElement(l.a,{spinning:this.state.isShow2,delay:600},React.createElement(o.a,{type:"info",message:"警告提示内容",description:`警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍`})),React.createElement("p",null,React.createElement(s.a,{type:"primary",onClick:this.swichHandle2},"显示/隐藏"))))}}},"9aTS":function(e,t){e.exports="import React, { Component } from 'react';\nimport Progress from '../Progress';\n\nexport default class ProgressDemo extends Component {\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>标准进度条</h3>\n <div>\n <Progress percent={30} />\n <Progress percent={70} status=\"exception\" />\n <Progress percent={70} status=\"pause\" />\n <Progress percent={100} status=\"success\" />\n <Progress percent={100} />\n <Progress percent={50} showInfo={false} />\n </div>\n <h3>小型进度条</h3>\n <p>适合放在较狭窄的区域内</p>\n <div style={{ width: 170 }}>\n <Progress percent={30} size={'mini'} />\n <Progress percent={70} size={'mini'} status=\"exception\" />\n <Progress percent={70} size={'mini'} status=\"pause\" />\n <Progress percent={100} size={'mini'} status=\"success\" />\n <Progress percent={100} size={'mini'} />\n </div>\n </div>\n );\n }\n}\n"},AW6G:function(e,t){e.exports="---\nauthor:\n name: lhf\n homepage: https://github.com/lhf/\n email: [email protected]\n---\n\n## Popover\n\nPopover Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|title|string||popover标题|\n|action|hover or click|hover|触发类型|\n|popovers|string or react.element||气泡框内容|\n|placement|string||提示框定位|\n\n### Api"},BtTj:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=(n.n(a),n("lkey")),o=n("WB2H"),s=class extends a.Component{constructor(e){super(e),this.state={}}render(){return o.a.config({top:60,duration:10}),React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"全局提示"),React.createElement("p",null,"各种类型的全局提示,自动消失"),React.createElement(l.a,{onClick:()=>{o.a.info("这是一条提示信息(信息内容)。")}},"info")," ",React.createElement(l.a,{type:"secondary",onClick:()=>{o.a.success("这是一条提示信息(信息内容)。")}},"success")," ",React.createElement(l.a,{type:"secondary",onClick:()=>{o.a.error("这是一条提示信息(信息内容)。")}},"error")," ",React.createElement(l.a,{type:"secondary",onClick:()=>{o.a.warning("这是一条提示信息(信息内容)。")}},"warning"))}}},CKXR:function(e,t){e.exports='import { Component } from \'react\';\nimport Input from \'../Input\';\nimport Icon from \'../../icon\';\nimport Search from \'../Search\';\nimport CardInput from \'../CardInput\';\n\nexport default class InputDemo extends Component {\n\n constructor(props) {\n super(props);\n this.state = { value: \'1234-1234-1234-1234\' };\n }\n\n onChangeCard = (e) => {\n const value = e.target.value;\n this.setState({ value });\n }\n\n render() {\n const prefix = (<Icon size={12} name={\'account\'} />);\n\n return (\n <div className="markdown-block">\n <h3>基本</h3>\n <p>输入框</p>\n <Input placeholder="请输入" defaultValue="12345465" />\n <h3>图标</h3>\n <p>图标输入框</p>\n <Input placeholder="请输入" prefix={prefix} />\n <h3>大小</h3>\n <p>三种大小的数字输入框</p>\n <Input size="large" placeholder="large size" />\n <p />\n <Input size="normal" placeholder="normal size" />\n <p />\n <Input size="small" placeholder="small size" />\n <h3>禁用</h3>\n <p>输入框禁用</p>\n <p>\n <Input placeholder="input disabled" defaultValue="12345465" disabled />\n </p>\n <h3>搜索框</h3>\n <p>带有搜索按钮的输入框</p>\n <Search size="large" placeholder="input search text" style={{ width: 240 }} />\n <p></p>\n <Search placeholder="input search text" style={{ width: 240 }} />\n <p></p>\n <Search size="small" placeholder="input search text" style={{ width: 240 }} />\n <h3>文本域</h3>\n <p>用于多行输入</p>\n <Input type="textarea" placeholder="请输入" autosize rows={1} />\n <Input type="textarea" placeholder="请输入" rows={6} />\n <h3>格式化</h3>\n <p>针对16或多位格式化输入</p>\n <CardInput\n size="large"\n mask="1111-1111-1111-1111"\n placeholder="1234-1234-1234-1234"\n value={this.state.value}\n onChange={this.onChangeCard}\n />\n <p></p>\n <CardInput\n size="normal"\n mask="111111-111111-111111-111111"\n onChange={this.onChangeCard}\n />\n </div>\n );\n }\n}\n'},DAzN:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return o});var a=n("Jmof"),l=(n.n(a),n("IggZ")),o=class extends a.Component{constructor(){var e;return e=super(...arguments),this.onChange=(e=>{console.log("changed",e)}),e}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"数字输入框"),React.createElement(l.a,{style:{width:200},min:1,max:10,defaultValue:3,onChange:this.onChange}),React.createElement("h3",null,"禁用"),React.createElement("p",null,"数字输入框禁用"),React.createElement(l.a,{min:1,max:10,disabled:!0,defaultValue:3}),React.createElement("h3",null,"小数"),React.createElement("p",null,"和原生的数字输入框一样,鼠标离开输入框时自动取值。目前设定小数位两位。"),React.createElement(l.a,{min:0,max:10,defaultValue:3,step:1,onChange:this.onChange}),React.createElement("h3",null,"大小"),React.createElement("p",null,"三种大小的数字输入框。"),React.createElement(l.a,{size:"large",min:1,max:1e5,defaultValue:3,onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{min:1,max:1e5,defaultValue:3,onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{size:"small",min:1,max:1e5,defaultValue:3,onChange:this.onChange}),React.createElement("h3",null,"格式化展示"),React.createElement("p",null,"展示具有具体含义的数据"),React.createElement(l.a,{formatter:e=>`$ ${e.replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,parser:e=>e.replace(/\$\s?|(,*)/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1e3,formatter:e=>`¥ ${e.replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,parser:e=>e.replace(/\¥\s?|(,*)/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} m`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} ㎡`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} t`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} L`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:10,formatter:e=>`${e} min`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}),React.createElement("br",null),React.createElement("br",null),React.createElement(l.a,{defaultValue:1,min:0,max:1e3,formatter:e=>`${e} m³`,parser:e=>e.replace(/[^\d]/g,""),onChange:this.onChange}))}}},"E7M+":function(e,t){e.exports="---\nauthor:\n name: lhf\n homepage: https://github.com/lhf/\n email: [email protected]\n---\n\n## Popconfirm\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|action|hover or click|hover|触发类型|\n|content|string or react.element||气泡确认框内容|\n|placement|string||提示框定位|\n|confirmVisable|bool||确认框是否显示|\n|handleOkClickTrigger|func||确认按钮触发事件|\n\n### Api"},Eiul:function(e,t){e.exports='import { Component } from \'react\';\nimport Spin from \'../Spin\';\nimport Alert from \'../../alert\';\nimport Button from \'../../button\';\nimport style from \'./index.css\';\n\nexport default class SpinDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {\n isShow1: true,\n isShow2: false,\n };\n }\n\n swichHandle1 = () => {\n this.setState({\n isShow1: !this.state.isShow1\n })\n }\n\n swichHandle2 = () => {\n this.setState({\n isShow2: !this.state.isShow2\n })\n }\n\n render() {\n return (\n <div className="markdown-block">\n <h3>基本用法</h3>\n <Spin />\n <h3>自定义大小</h3>\n <table>\n <thead>\n <tr>\n <th>小</th>\n <th>中</th>\n <th>大</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <Spin size="small" />\n </td>\n <td>\n <Spin size="default" />\n </td>\n <td>\n <Spin size="large" />\n </td>\n </tr>\n </tbody>\n </table>\n <h3>自定义描述文案</h3>\n <table>\n <thead>\n <tr>\n <th>小</th>\n <th>中</th>\n <th>大</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <Spin size="small" tip="loading..." />\n </td>\n <td>\n <Spin size="default" tip="loading..." />\n </td>\n <td>\n <Spin size="large" tip="loading..." />\n </td>\n </tr>\n </tbody>\n </table>\n <h3>容器中使用</h3>\n <div className={style.example1}>\n <Spin />\n </div>\n <div className={style.example1}>\n <Spin tip="loading..." />\n </div>\n <h3>提示中使用</h3>\n <div>\n <Spin spinning={this.state.isShow1}>\n <Alert\n type="info"\n message="警告提示内容"\n description={`警告提示的辅助性文字介绍警告提示的辅助\n 性文字介绍警告提示的辅助性文字介绍警告提示的辅助性文\n 字介绍警告提示的辅助性文字介绍警告提示的辅助性文字介\n 绍警告提示的辅助性文字介绍警告提示的辅助性文字介绍警\n 告提示的辅助性文字介绍警告提示的辅助性文字介绍`}\n />\n </Spin>\n <p>\n <Button type="primary" onClick={this.swichHandle1}>显示/隐藏</Button>\n </p>\n </div>\n <h3>延迟</h3>\n <div>\n <Spin spinning={this.state.isShow2} delay={600}>\n <Alert\n type="info"\n message="警告提示内容"\n description={`警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍警告提示的辅助性文字介绍警告提示\n 的辅助性文字介绍`}\n />\n </Spin>\n <p>\n <Button type="primary" onClick={this.swichHandle2}>显示/隐藏</Button>\n </p>\n </div>\n </div>\n );\n }\n}\n'},Ek3L:function(e,t){e.exports="import { Component } from 'react';\nimport Trigger from '../Trigger';\nimport Button from '../../button';\nimport Radio, { RadioGroup } from '../../radio';\n\nconst PLACEMENT_ENUM = {\n left: {\n points: ['cr', 'cl'],\n },\n right: {\n points: ['cl', 'cr'],\n },\n top: {\n points: ['bc', 'tc'],\n },\n bottom: {\n points: ['tc', 'bc'],\n },\n topLeft: {\n points: ['bl', 'tl'],\n },\n topRight: {\n points: ['br', 'tr'],\n },\n bottomRight: {\n points: ['tr', 'br'],\n },\n bottomLeft: {\n points: ['tl', 'bl'],\n },\n};\n\nconst ActionType = [\n 'hover',\n 'click',\n];\n\nexport default class TriggerDemo extends Component {\n state = {\n placement: 'bottom',\n action: 'click',\n visible: false,\n }\n onChangePlacement = (e) => {\n this.setState({\n placement: e.target.value,\n });\n }\n onChangeActionType = (e) => {\n this.setState({\n action: e.target.value,\n });\n }\n onClosePopup = () => {\n this.setState({\n visible: false,\n });\n }\n onPopupVisibleChange = (visible) => {\n console.log('onPopupVisibleChange', visible);\n this.setState({\n visible,\n });\n }\n renderPlacementSelector() {\n const { placement } = this.state;\n return (\n <select value={placement} onChange={this.onChangePlacement}>\n {\n Object.keys(PLACEMENT_ENUM).map(p => (\n <option key={p}>{p}</option>\n ))\n }\n </select>\n );\n }\n render() {\n const {\n placement,\n action,\n } = this.state;\n return (\n <div className=\"markdown-block\">\n <h5>普通用法</h5>\n <label htmlFor=\"placement\">对齐方式</label>\n {\n this.renderPlacementSelector()\n }\n <label htmlFor=\"action\">触发方式</label>\n <RadioGroup value={action} onChange={this.onChangeActionType}>\n {\n ActionType.map(type => (\n <Radio\n value={type}\n key={type}\n >{type}</Radio>\n ))\n }\n </RadioGroup>\n <Trigger\n action={action}\n popup={\n <div style={{ border: '1px solid #000', padding: 10, background: '#fff' }}>popup content</div>\n }\n placement={PLACEMENT_ENUM[placement].points}\n mouseLeaveDelay={100}\n >\n <Button>{`${action} me`}</Button>\n </Trigger>\n <h5>手动控制关闭</h5>\n <Trigger\n action={'click'}\n popupVisible={this.state.visible}\n popup={\n <div onClick={this.onClosePopup}>click me to close</div>\n }\n onPopupVisibleChange={this.onPopupVisibleChange}\n >\n <Button>click</Button>\n </Trigger>\n </div>\n );\n }\n}\n"},FaRr:function(e,t,n){var a=n("V40D");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},Gczl:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,".EQXZMCV,.h85PQ2p{margin-left:110px}button{width:60px}._2t-VUhY{float:left}._3vGiCGW{margin-left:360px}.h85PQ2p{margin-top:10px}.EQXZMCV ._3WixqFJ,.h85PQ2p ._2BepiJ_{display:inline-block;margin-right:10px}._2t-VUhY ._3sQS4SA,._3vGiCGW ._2keCoO8{margin-top:10px}",""]),t.locals={"top-tooltip":"EQXZMCV","bottom-tooltip":"h85PQ2p","left-tooltip":"_2t-VUhY","right-tooltip":"_3vGiCGW","top-tooltip-div":"_3WixqFJ","bottom-tooltip-div":"_2BepiJ_","left-tooltip-div":"_3sQS4SA","right-tooltip-div":"_2keCoO8"}},GuEn:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/october-yan/\n---\n\n## Notification\n\n全局展示通知提醒信息.\n\n### 何时使用\n\n在系统四个角显示通知提醒信息。经常用于以下情况:\n较为复杂的通知内容。\n带有交互的通知,给出用户下一步的行动点。\n系统主动推送。\n\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|message|string||通知提醒标题,必选|\n|description|string||通知提醒内容,必选|\n|duration|number|4.5|默认 4.5 秒后自动关闭,配置为 0 则不自动关闭|\n|icon|ReactNode||自定义图标|\n|btn|ReactNode||自定义关闭按钮|\n|placement|string|topRight|弹出位置,可选 topLeft topRight bottomLeft bottomRight|\n\n\n#### notification.config(options)\n|name|type|default|description|\n|---|---|---|---|\n|placement|string|topRight|弹出位置,可选 topLeft topRight bottomLeft bottomRight|\n|top|number|24|消息从顶部弹出时,距离顶部的位置,单位像素|\n|bottom|number|24|消息从底部弹出时,距离底部的位置,单位像素|\n|duration|number|4.5|默认自动关闭延时,单位秒|\n\n\n### Api"},Hlpk:function(e,t,n){var a=n("Jz/6");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},Hn9c:function(e,t){e.exports="import { Component } from 'react';\nimport Modal from '../Modal';\nimport Button from '../../button';\n\nexport default class ModalDemo extends Component {\n constructor(props) {\n super(props);\n this.openModal = this.openModal.bind(this);\n this.state = {\n visible: false,\n };\n }\n openModal() {\n this.setState({\n visible: true,\n });\n }\n closeModal() {\n this.setState({\n visible: false,\n });\n }\n render() {\n const { visible } = this.state;\n const modalProps = {\n title: '标题',\n visible,\n onOk: () => {\n this.closeModal();\n console.log('onOK');\n },\n onCancel: () => {\n this.closeModal();\n console.log('onCancel');\n },\n afterClose() {\n console.log('afterClose');\n },\n };\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <Button type=\"secondary\" onClick={this.openModal}>open modal</Button>\n <Modal {...modalProps}>\n <p>这是一段信息。</p>\n </Modal>\n <h3>信息提示</h3>\n <p>各种类型的信息提示,只提供一个按钮用于关闭。</p>\n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.info({\n content: '这是提示信息',\n closable: true,\n });\n }}\n >info</Button>&emsp;\n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.success({\n content: '这是成功消息',\n });\n }}\n >success</Button>&emsp;\n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.error({\n content: '这是错误提示',\n });\n }}\n >error</Button>&emsp;\n <Button\n type=\"secondary\"\n onClick={() => {\n Modal.warning({\n content: '这是警告信息',\n });\n }}\n >warning</Button>\n </div>\n );\n }\n}\n"},I045:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Icon\n\n图标。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|name|string|''|图标名称|\n|size|number|32|尺寸|\n|color|string|-|颜色|\n"},IAgb:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,"._10nfZ5r{display:flex;flex-wrap:wrap}.GsIgpmR{display:inline-flex;margin:1px;width:80px;height:80px;border:1px solid var(--border-color);flex-direction:column;justify-content:space-around;text-align:center}.GsIgpmR>svg{margin:0 auto}._25I3NhY{display:block;font-size:12px;line-height:1}",""]),t.locals={Icon__wrap:"_10nfZ5r",Icon__grid:"GsIgpmR",Icon__name:"_25I3NhY"}},IV61:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,".IATVnLg{padding-top:30px}._1gVznGn{margin-top:8px;font-size:12px}",""]),t.locals={"upload-btn":"IATVnLg","upload-text":"_1gVznGn"}},J2TD:function(e,t){e.exports='import Button from \'quark-ui/button\';\nimport Dropdown from \'../Dropdown\';\n\nconst { Menu } = Dropdown;\nconst { Item } = Menu;\n\nconst DropdownDemo = () => {\n const menu = (\n <Menu>\n <Item>\n <a href="https://www.ehuodi.com">易货嘀</a>\n </Item>\n <Item>\n <a href="http://www.lujing56.cn/">陆鲸</a>\n </Item>\n <Item>\n <a href="https://ecargo.ehuodi.com/">加盟车队管理系统</a>\n </Item>\n </Menu>\n );\n return (\n <div className="markdown-block">\n <h3>带下拉框的按钮</h3>\n <Dropdown overlay={menu}>\n <Button>菜单</Button>\n </Dropdown>\n <h3>Dropdown内置按钮</h3>\n <Dropdown.Button type="secondary" overlay={menu} trigger={\'click\'}>\n 菜单\n </Dropdown.Button>\n </div>\n );\n};\n\nexport default DropdownDemo;\n'},JJ4K:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return r});var a=n("JCOr"),l=n("Jmof"),o=(n.n(l),n("kbwb")),s=(n("oiih"),n("7nwc")),i=n.n(s),r=class extends l.Component{render(){var e=React.createElement("div",null,React.createElement("p",null,"top"),React.createElement("p",null,"这是一个气泡框"));return React.createElement("div",null,React.createElement("div",{className:i.a["top-tooltip"]},React.createElement("div",{className:i.a["top-tooltip-div"]},React.createElement(a.a,{title:"标题",popovers:"topLeft",placement:"topLeft"},React.createElement(o.a,{type:"secondary"},"上左"))),React.createElement("div",{className:i.a["top-tooltip-div"]},React.createElement(a.a,{title:"标题",popovers:e,placement:"top",action:"click",hasButton:!0},React.createElement(o.a,{type:"secondary"},"点击"))),React.createElement("div",{className:i.a["top-tooltip-div"]},React.createElement(a.a,{popovers:"topRight",placement:"topRight"},React.createElement(o.a,{type:"secondary"},"上右")))),React.createElement("div",{className:i.a["left-tooltip"]},React.createElement("div",{className:i.a["left-tooltip-div"]},React.createElement(a.a,{popovers:"leftTop",placement:"leftTop"},React.createElement(o.a,{type:"secondary"},"左上"))),React.createElement("div",{className:i.a["left-tooltip-div"]},React.createElement(a.a,{popovers:"left",placement:"left"},React.createElement(o.a,{type:"secondary"},"左"))),React.createElement("div",{className:i.a["left-tooltip-div"]},React.createElement(a.a,{popovers:"leftBottom",placement:"leftBottom"},React.createElement(o.a,{type:"secondary"},"左下")))),React.createElement("div",{className:i.a["right-tooltip"]},React.createElement("div",{className:i.a["right-tooltip-div"]},React.createElement(a.a,{popovers:"rightTop",placement:"rightTop"},React.createElement(o.a,{type:"secondary"},"右上"))),React.createElement("div",{className:i.a["right-tooltip-div"]},React.createElement(a.a,{popovers:"right",placement:"right"},React.createElement(o.a,{type:"secondary"},"右"))),React.createElement("div",{className:i.a["right-tooltip-div"]},React.createElement(a.a,{popovers:"rightBottom",placement:"rightBottom"},React.createElement(o.a,{type:"secondary"},"左下")))),React.createElement("div",{className:i.a["bottom-tooltip"]},React.createElement("div",{className:i.a["bottom-tooltip-div"]},React.createElement(a.a,{popovers:"bottomLeft",placement:"bottomLeft"},React.createElement(o.a,{type:"secondary"},"下左"))),React.createElement("div",{className:i.a["bottom-tooltip-div"]},React.createElement(a.a,{popovers:"bottom",placement:"bottom"},React.createElement(o.a,{type:"secondary"},"下"))),React.createElement("div",{className:i.a["bottom-tooltip-div"]},React.createElement(a.a,{popovers:"bottomRight",placement:"bottomRight"},React.createElement(o.a,{type:"secondary"},"下右")))))}}},"Jz/6":function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,"._1flgiXF,._10xN1Sm{margin-left:110px}button{min-width:60px}._1Vbw0S8{float:left}._2mQ-n0v{margin-left:360px}._10xN1Sm{margin-top:10px}._1flgiXF ._2_Km13b,._10xN1Sm ._3VxyDZX{display:inline-block;margin-right:10px}._1Vbw0S8 ._3HC8bgS,._2mQ-n0v ._3Wtmrxa{margin-top:10px}",""]),t.locals={"top-tooltip":"_1flgiXF","bottom-tooltip":"_10xN1Sm","left-tooltip":"_1Vbw0S8","right-tooltip":"_2mQ-n0v","top-tooltip-div":"_2_Km13b","bottom-tooltip-div":"_3VxyDZX","left-tooltip-div":"_3HC8bgS","right-tooltip-div":"_3Wtmrxa"}},KIYf:function(e,t,n){var a=n("SdPj");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},KOED:function(e,t){e.exports='import { Component } from \'react\';\nimport Breadcrumb from \'../index\';\n\nexport default class BreadcrumbDemo extends Component {\n render() {\n return (\n <div className="markdown-block">\n <h3>基本面包屑</h3>\n <p><Breadcrumb>\n <Breadcrumb.Item>home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb></p>\n\n <Breadcrumb separator=">">\n <Breadcrumb.Item>home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb>\n\n <h3>带返回的面包屑</h3>\n <p><Breadcrumb hasBackIcon >\n <Breadcrumb.Item href="/">home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb></p>\n\n <Breadcrumb hasBackIcon separator=">">\n <Breadcrumb.Item href="/">home</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/button">Button</Breadcrumb.Item>\n <Breadcrumb.Item href="/component/steps">Steps</Breadcrumb.Item>\n <Breadcrumb.Item>bbb</Breadcrumb.Item>\n </Breadcrumb>\n </div>\n );\n }\n}\n'},KOOh:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Button\n\n按钮用于开始一个即时操作。\n\n### 何时使用\n\n标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|String|'primary'|button type, `primary` `secondary` `dashed` or `danger`|\n|size|String|'normal'|button size, `normal` `large` or `small` |\n\n### Api"},KhAK:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return r});var a=n("JJl7"),l=n("kbwb"),o=n("Jmof"),s=(n.n(o),n("oiih"),n("Q6KC")),i=n.n(s),r=class extends o.Component{render(){var e=React.createElement("div",null,React.createElement("p",null,"1111"),React.createElement("p",null,"222"),React.createElement("p",null,"3333"));return React.createElement("div",null,React.createElement("div",{className:i.a["top-tooltip"]},React.createElement("div",{className:i.a["top-tooltip-div"]},React.createElement(a.a,{tips:"topLeft",placement:"topLeft"},React.createElement(l.a,{type:"secondary"},"上左"))),React.createElement("div",{className:i.a["top-tooltip-div"]},React.createElement(a.a,{tips:"top",placement:"top"},React.createElement(l.a,{type:"secondary"},"上"))),React.createElement("div",{className:i.a["top-tooltip-div"]},React.createElement(a.a,{tips:"topRight",placement:"topRight"},React.createElement(l.a,{type:"secondary"},"上右")))),React.createElement("div",{className:i.a["left-tooltip"]},React.createElement("div",{className:i.a["left-tooltip-div"]},React.createElement(a.a,{tips:e,placement:"leftTop"},React.createElement(l.a,{type:"secondary"},"左上"))),React.createElement("div",{className:i.a["left-tooltip-div"]},React.createElement(a.a,{tips:e,placement:"left"},React.createElement(l.a,{type:"secondary"},"左"))),React.createElement("div",{className:i.a["left-tooltip-div"]},React.createElement(a.a,{tips:e,placement:"leftBottom"},React.createElement(l.a,{type:"secondary"},"左下")))),React.createElement("div",{className:i.a["right-tooltip"]},React.createElement("div",{className:i.a["right-tooltip-div"]},React.createElement(a.a,{tips:"right",placement:"rightTop"},React.createElement(l.a,{type:"secondary"},"右上"))),React.createElement("div",{className:i.a["right-tooltip-div"]},React.createElement(a.a,{tips:"right",placement:"right"},React.createElement(l.a,{type:"secondary"},"右"))),React.createElement("div",{className:i.a["right-tooltip-div"]},React.createElement(a.a,{tips:"right",placement:"rightBottom"},React.createElement(l.a,{type:"secondary"},"左下")))),React.createElement("div",{className:i.a["bottom-tooltip"]},React.createElement("div",{className:i.a["bottom-tooltip-div"]},React.createElement(a.a,{tips:"bottomLeft",placement:"bottomLeft"},React.createElement(l.a,{type:"secondary"},"下左"))),React.createElement("div",{className:i.a["bottom-tooltip-div"]},React.createElement(a.a,{tips:"bottom",placement:"bottom"},React.createElement(l.a,{type:"secondary"},"下"))),React.createElement("div",{className:i.a["bottom-tooltip-div"]},React.createElement(a.a,{tips:"bottomRight",placement:"bottomRight"},React.createElement(l.a,{type:"secondary"},"下右")))))}}},LXsE:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,"._2FzUuhQ,._2TZDyut{margin-left:110px}button{width:60px}._754MSPv{float:left}._2NMzr1M{margin-left:360px}._2FzUuhQ{margin-top:10px}._2FzUuhQ ._2NzOvIh,._2TZDyut ._3PW1L4N{display:inline-block;margin-right:10px}._2NMzr1M .XuVWjWG,._754MSPv ._2YsOB_s{margin-top:10px}",""]),t.locals={"top-tooltip":"_2TZDyut","bottom-tooltip":"_2FzUuhQ","left-tooltip":"_754MSPv","right-tooltip":"_2NMzr1M","top-tooltip-div":"_3PW1L4N","bottom-tooltip-div":"_2NzOvIh","left-tooltip-div":"_2YsOB_s","right-tooltip-div":"XuVWjWG"}},LiML:function(e,t){e.exports='import Tooltip from \'../Tooltip\';\nimport Button from \'../../button/Button\';\nimport { Component } from \'react\';\n// import CSSModules from \'react-css-modules\';\nimport { allowMultiple } from \'../../../constants\';\nimport styles from \'./index.css\';\n\n// @CSSModules(styles, { allowMultiple })\nexport default class TooltipDemo extends Component {\n\n render() {\n \tconst ele = (<div><p>1111</p><p>222</p><p>3333</p></div>);\n\n return (\n <div>\n <div className={styles[\'top-tooltip\']}>\n <div className={styles[\'top-tooltip-div\']}><Tooltip tips="topLeft" placement="topLeft" ><Button type="secondary">上左</Button></Tooltip></div>\n <div className={styles[\'top-tooltip-div\']}><Tooltip tips="top" placement="top" ><Button type="secondary">上</Button></Tooltip></div>\n <div className={styles[\'top-tooltip-div\']}><Tooltip tips="topRight" placement="topRight" ><Button type="secondary">上右</Button></Tooltip></div>\n </div>\n <div className={styles[\'left-tooltip\']} >\n <div className={styles[\'left-tooltip-div\']}><Tooltip tips={ele} placement="leftTop" ><Button type="secondary">左上</Button></Tooltip></div>\n <div className={styles[\'left-tooltip-div\']}><Tooltip tips={ele} placement="left" ><Button type="secondary">左</Button></Tooltip></div>\n <div className={styles[\'left-tooltip-div\']}><Tooltip tips={ele} placement="leftBottom" ><Button type="secondary">左下</Button></Tooltip></div>\n </div>\n <div className={styles[\'right-tooltip\']} >\n <div className={styles[\'right-tooltip-div\']}><Tooltip tips="right" placement="rightTop" ><Button type="secondary">右上</Button></Tooltip></div>\n <div className={styles[\'right-tooltip-div\']}><Tooltip tips="right" placement="right" ><Button type="secondary">右</Button></Tooltip></div>\n <div className={styles[\'right-tooltip-div\']}><Tooltip tips="right" placement="rightBottom" ><Button type="secondary">左下</Button></Tooltip></div>\n </div>\n <div className={styles[\'bottom-tooltip\']}>\n <div className={styles[\'bottom-tooltip-div\']}><Tooltip tips="bottomLeft" placement="bottomLeft" ><Button type="secondary">下左</Button></Tooltip></div>\n <div className={styles[\'bottom-tooltip-div\']}><Tooltip tips="bottom" placement="bottom"><Button type="secondary">下</Button></Tooltip></div>\n <div className={styles[\'bottom-tooltip-div\']}><Tooltip tips="bottomRight" placement="bottomRight"><Button type="secondary">下右</Button></Tooltip></div>\n </div>\n </div>\n \n );\n }\n}\n'},"M1/m":function(e,t){e.exports="import { Component } from 'react';\nimport InputNumber from '../InputNumber';\n\nexport default class InputNumberDemo extends Component {\n onChange = (value) => {\n console.log('changed', value);\n }\n\n render() {\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <p>数字输入框</p>\n <InputNumber style={{ width: 200 }} min={1} max={10} defaultValue={3} onChange={this.onChange} />\n <h3>禁用</h3>\n <p>数字输入框禁用</p>\n <InputNumber min={1} max={10} disabled defaultValue={3} />\n <h3>小数</h3>\n <p>和原生的数字输入框一样,鼠标离开输入框时自动取值。目前设定小数位两位。</p>\n <InputNumber min={0} max={10} defaultValue={3} step={1.00} onChange={this.onChange} />\n <h3>大小</h3>\n <p>三种大小的数字输入框。</p>\n <InputNumber size=\"large\" min={1} max={100000} defaultValue={3} onChange={this.onChange} />\n <br /><br />\n <InputNumber min={1} max={100000} defaultValue={3} onChange={this.onChange} />\n <br /><br />\n <InputNumber size=\"small\" min={1} max={100000} defaultValue={3} onChange={this.onChange} />\n <h3>格式化展示</h3>\n <p>展示具有具体含义的数据</p>\n <InputNumber\n formatter={value => `$ ${value.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')}`}\n parser={value => value.replace(/\\$\\s?|(,*)/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1000}\n formatter={value => `¥ ${value.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')}`}\n parser={value => value.replace(/\\¥\\s?|(,*)/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} m`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} ㎡`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} t`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} L`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={10}\n formatter={value => `${value} min`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n <br /><br />\n <InputNumber\n defaultValue={1}\n min={0}\n max={1000}\n formatter={value => `${value} m³`}\n parser={value => value.replace(/[^\\d]/g, '')}\n onChange={this.onChange}\n />\n </div>\n );\n }\n}\n"},Mdu8:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return o});var a=n("b7MC"),l=n("Jmof"),o=(n.n(l),class extends l.Component{constructor(){var e;return e=super(...arguments),this.state={current:3},e}render(){var e=this.state.current;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"基础分页。"),React.createElement(a.a,{current:e,total:0}),React.createElement(a.a,{current:e,total:50}),React.createElement("h3",null,"更多分页"),React.createElement(a.a,{defaultCurrent:1,total:500,showSizeChanger:!0,onSizeChange:(e,t)=>{console.log(`size: ${e} current: ${t}`)}}),React.createElement("h3",null,"跳转"),React.createElement("p",null,"快速跳转到某一页。"),React.createElement(a.a,{showTotal:!0,total:5e5,showQuickJumper:!0}),React.createElement("h3",null,"迷你"),React.createElement("p",null,"用于弹窗等页面展示区域狭小的场景。"),React.createElement("h3",null,"受控方式"),React.createElement("p",null,React.createElement(a.a,{current:e,total:50,onChange:e=>{this.setState({current:e})}})),React.createElement(a.a,{total:100,showQuickJumper:!0,showSizeChanger:!0,size:"small"}),React.createElement("h3",null,"非受控方式"),React.createElement(a.a,{defaultCurrent:1,total:50}))}})},PKY1:function(e,t,n){var a,l,o;!function(n,s){l=[t,e],void 0!==(o="function"==typeof(a=s)?a.apply(t,l):a)&&(e.exports=o)}(0,function(e,t){"use strict";function n(){return"jsonp_"+Date.now()+"_"+Math.ceil(1e5*Math.random())}function a(e){try{delete window[e]}catch(t){window[e]=void 0}}function l(e){var t=document.getElementById(e);t&&document.getElementsByTagName("head")[0].removeChild(t)}var o={timeout:5e3,jsonpCallback:"callback",jsonpCallbackFunction:null};t.exports=function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],s=e,i=t.timeout||o.timeout,r=t.jsonpCallback||o.jsonpCallback,c=void 0;return new Promise(function(o,m){var u=t.jsonpCallbackFunction||n(),p=r+"_"+u;window[u]=function(e){o({ok:!0,json:function(){return Promise.resolve(e)}}),c&&clearTimeout(c),l(p),a(u)},s+=-1===s.indexOf("?")?"?":"&";var d=document.createElement("script");d.setAttribute("src",""+s+r+"="+u),t.charset&&d.setAttribute("charset",t.charset),d.id=p,document.getElementsByTagName("head")[0].appendChild(d),c=setTimeout(function(){m(new Error("JSONP request to "+e+" timed out")),a(u),l(p),window[u]=function(){a(u)}},i),d.onerror=function(){m(new Error("JSONP request to "+e+" failed")),a(u),l(p),c&&clearTimeout(c)}})}})},PXi9:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/ryan.bian/\n email: [email protected]\n---\n\n## Animation\n\nAnimation Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|duration|number|500|持续时间|\n|motion|string|`fade`|效果|\n|timingFunction|string|`linear`|时间函数|\n|in|boolean|false|状态|\n|`...otherProps`|-|-|refer to https://reactcommunity.org/react-transition-group/#Transition|\n\n### Api"},PgBk:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return g});var a=n("Jmof"),l=n.n(a),o=n("xLxO"),s=n("hFTO"),i=n("kbwb"),r=n("WB2H"),c=n("kimJ"),m=n.n(c),u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},p=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e={name:"file",action:"https://jsonplaceholder.typicode.com/posts/",headers:{authorization:"authorization-text"},multiple:!0,disabled:!1,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg},onChange(e){e.file.status,"done"===e.file.status?r.a.success(`${e.file.name} 文件上传成功.`):"error"===e.file.status&&r.a.error(`${e.file.name} 文件上传失败!`)}};return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"1、经典款式,用户点击按钮弹出文件选择框。"),l.a.createElement(o.a,e,l.a.createElement(i.a,{size:"small",type:"secondary",disabled:e.disabled},l.a.createElement(s.a,{size:12,name:"upload"})," 上传文件")))}},d=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e={name:"file",action:"https://jsonplaceholder.typicode.com/posts/",headers:{authorization:"authorization-text"},multiple:!0,disabled:!1,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg},onChange(e){e.file.status,"done"===e.file.status?r.a.success(`${e.file.name} 文件上传成功.`):"error"===e.file.status&&r.a.error(`${e.file.name} 文件上传失败!`)},defaultFileList:[{uid:1,name:"图片1.png",status:"done",url:"https://www.ehuodi.com/module/index/img/index2/line2_bg.png"},{uid:2,name:"图片2.png",status:"done",url:"https://www.ehuodi.com/module/index/img/index2/line2_bg.png"},{uid:3,name:"图片3.png",status:"error",response:"上传失败,图片太大"}]};return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"2、已上传文件的列表"),l.a.createElement("p",null,"使用 defaultFileList 设置已上传的内容。"),l.a.createElement(o.a,e,l.a.createElement(i.a,{size:"small",type:"secondary",disabled:e.disabled},l.a.createElement(s.a,{size:12,name:"upload"})," 上传文件")))}},h=class extends a.Component{constructor(e){super(e),this.state={fileList:[{uid:-1,name:"xxx.png",status:"done",url:"https://www.ehuodi.com/module/index/img/index2/line2_bg.png"}]}}render(){var e=this,t={action:"//jsonplaceholder.typicode.com/posts/",disabled:!1,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg},onChange(t){var n=t.fileList;n=(n=n.slice(-1)).map(e=>(e.response&&(e.url=e.response.url),e)),e.setState({fileList:n})}};return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"3、使用 fileList 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:"),l.a.createElement("p",null,"1) 上传列表数量的限制。"),l.a.createElement("p",null,"2) 读取远程路径并显示链接。"),l.a.createElement("p",null,"3) 按照服务器返回信息筛选成功上传的文件。"),l.a.createElement(o.a,u({},t,{fileList:this.state.fileList}),l.a.createElement(i.a,{size:"small",type:"secondary",disabled:t.disabled},l.a.createElement(s.a,{size:12,name:"upload"})," 上传文件")))}},y=class extends a.Component{constructor(e){super(e),this.handlePreview=(e=>{window.open(e.url)}),this.handleChange=(e=>{this.setState({fileList:e.fileList})}),this.state={fileList:[{uid:-1,name:"xxx.png",status:"done",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}]}}beforeUpload(e){var t="image/png"===e.type;t||r.a.error("请上传.png文件!");var n=e.size<1024e3;return n||r.a.error("图片不能超过1000KB!"),t&&n}render(){var e={action:"//jsonplaceholder.typicode.com/posts/",disabled:!1,listType:"picture-card",fileList:this.state.fileList,onPreview:this.handlePreview,onChange:this.handleChange,beforeUpload:this.beforeUpload,onResponse:e=>"success"===(e={result:"success",msg:"上传成功!",url:"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"}).result?{success:!0,message:"上传成功",url:e.url}:{success:!1,message:e.msg}},t=l.a.createElement("div",{className:m.a["upload-btn"]},l.a.createElement(s.a,{name:"plus",size:25}),l.a.createElement("div",{className:m.a["upload-text"]},"上传"));return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"4、显示上传缩略图"),l.a.createElement("p",null,"点击上传图片,并使用 beforeUpload 限制用户上传的图片格式和大小。"),l.a.createElement(o.a,e,this.state.fileList.length>=3?null:t))}},g=class extends a.Component{render(){return l.a.createElement("div",{className:"markdown-block"},l.a.createElement(p,null),l.a.createElement("br",null),l.a.createElement("br",null),l.a.createElement(d,null),l.a.createElement("br",null),l.a.createElement("br",null),l.a.createElement(h,null),l.a.createElement("br",null),l.a.createElement("br",null),l.a.createElement(y,null))}}},Q6KC:function(e,t,n){var a=n("Gczl");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},RPTQ:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return m});var a=n("Jmof"),l=(n.n(a),n("PJh5")),o=n.n(l),s=n("k44X"),i=n("qoUc"),r=s.a.MonthPicker,c=s.a.RangePicker,m=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={disabled:!1,date:o()().add(1,"M")},this.changeDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),e}onChange(e){console.log(e)}render(){var e=this.state,t=e.date,n=e.disabled;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,React.createElement(i.a,{checked:n,onChange:this.changeDisabled},"禁用")),React.createElement("h3",null,"日期选择"),React.createElement("table",null,React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"非受控方式"),React.createElement("th",null,"受控方式"))),React.createElement("tbody",null,React.createElement("tr",null,React.createElement("td",null,React.createElement(s.a,{disabled:n,onChange:this.onChange})),React.createElement("td",{style:{position:"relative"}},React.createElement(s.a,{disabled:n,value:t,onChange:e=>{this.setState({date:e})}}),React.createElement("p",{style:{position:"absolute",right:"20px",top:"15px"}},"选择时间: ",t.format()))))),React.createElement("h3",null,"不可选日期"),React.createElement("p",null,"可用 disabledDate 禁止选择部分日期"),React.createElement(s.a,{disabled:n,disabledDate:e=>e&&e.valueOf()<Date.now()}),React.createElement("h3",null,"月份选择"),React.createElement(r,{onChange:this.onChange,disabled:n}),React.createElement("h3",null,"预设范围"),React.createElement("p",null,"RangePicker 可以设置常用的 预设范围 提高用户体验。"),React.createElement(c,{onChange:this.onChange,disabled:n}))}}},RZTb:function(e,t){e.exports="import React, { Component } from 'react';\nimport Reactable from '../index';\nimport Button from '../../button';\n\nconst { Table } = Reactable;\nexport default class TableDemo extends Component {\n state= {\n selectedRowKeys: [1, 2],\n dataSource: [\n {\n key: '1',\n name: 'John Brown',\n age: '24 year',\n address: 'New York No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n {\n key: '2',\n name: 'Jim Green',\n age: '24 year',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n {\n key: '3',\n name: 'Jim Green',\n age: '24 year',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n ],\n columns: [\n {\n title: '',\n dataIndex: 'select',\n key: 'select',\n width: 100,\n },\n {\n title: 'Name',\n dataIndex: 'name',\n key: 'name',\n width: 200,\n },\n {\n title: 'Age',\n dataIndex: 'age',\n key: 'age',\n width: 250,\n },\n {\n title: 'Address',\n dataIndex: 'address',\n key: 'address',\n },\n {\n title: 'Work',\n dataIndex: 'work',\n key: 'work',\n },\n {\n title: 'Color',\n dataIndex: 'color',\n key: 'color',\n },\n {\n title: 'Fruit',\n dataIndex: 'fruit',\n key: 'fruit',\n },\n {\n title: 'Action',\n dataIndex: 'action',\n key: 'action',\n width: 100,\n render: () => (\n <div>\n <Button size=\"small\">删除</Button>\n </div>\n ),\n },\n ],\n }\n onChange = (sorter) => {\n this.setState({\n sortedInfo: sorter,\n });\n }\n onSelectChange = (selectedRowKeys) => {\n this.setState({\n selectedRowKeys,\n });\n }\n\n render() {\n const rowSelection = {\n selectedRowKeys: this.state.selectedRowKeys,\n onSelectChange: this.onSelectChange,\n selections: 'all-data',\n };\n let { sortedInfo } = this.state;\n sortedInfo = sortedInfo || {};\n const demo1 = {\n data: [\n {\n key: '1',\n name: 'John Brown',\n age: '20',\n address: 'New York No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n {\n key: '2',\n name: 'Jim Greenss',\n age: '90',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n {\n key: '3',\n name: 'Jim Green',\n age: '70',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n ],\n columns: [\n {\n title: 'Name',\n dataIndex: 'name',\n key: 'name',\n width: 200,\n sorter: (a, b) => a.name.length - b.name.length,\n sortOrder: sortedInfo.columnKey === 'name' && sortedInfo.order,\n },\n {\n title: 'Age',\n dataIndex: 'age',\n key: 'age',\n width: 250,\n sorter: (a, b) => a.age - b.age,\n sortOrder: sortedInfo.columnKey === 'age' && sortedInfo.order,\n },\n {\n title: 'Address',\n dataIndex: 'address',\n key: 'address',\n },\n {\n title: 'Action',\n dataIndex: 'action',\n key: 'action',\n width: 100,\n render: () => (\n <div>\n <Button size=\"small\">删除</Button>\n </div>\n ),\n },\n ],\n };\n const test = {\n data: [\n {\n key: '1',\n name: 'John Brown',\n age: '24 year',\n address: 'New York No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n {\n key: '2',\n name: 'Jim Green',\n age: '24 year',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n {\n key: '3',\n name: 'Jim Green',\n age: '24 year',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my favourite fruits.',\n },\n ],\n columns: [\n {\n title: 'Name',\n dataIndex: 'name',\n key: 'name',\n width: 200,\n },\n {\n title: 'Age',\n dataIndex: 'age',\n key: 'age',\n width: 250,\n },\n {\n title: 'Address',\n dataIndex: 'address',\n key: 'address',\n },\n {\n title: 'Work',\n dataIndex: 'work',\n key: 'work',\n },\n {\n title: 'Color',\n dataIndex: 'color',\n key: 'color',\n },\n {\n title: 'Fruit',\n dataIndex: 'fruit',\n key: 'fruit',\n },\n {\n title: 'Action',\n dataIndex: 'action',\n key: 'action',\n width: 100,\n render: () => (\n <div>\n <Button size=\"small\">删除</Button>\n </div>\n ),\n },\n ],\n };\n\n const demo3 = {\n data: [\n {\n key: '1',\n name: 'John Brown',\n age: '24 year',\n address: 'New York No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my ',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n interest: 'such as climbing mountains, travelling, watching movie...',\n },\n {\n key: '2',\n name: 'Jim Green',\n age: '24 year',\n address: 'London No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n interest: 'such as climbing mountains, travelling, watching movie...',\n },\n {\n key: '3',\n name: 'Joe Black',\n age: '24 year',\n address: 'Sidney No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n interest: 'such as climbing mountains, travelling, watching movie...',\n },\n {\n key: '4',\n name: 'Joe Black',\n age: '24 year',\n address: 'Sidney No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n interest: 'such as climbing mountains, travelling, watching movie...',\n },\n {\n key: '5',\n name: 'Joe Black',\n age: '24 year',\n address: 'Sidney No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n },\n {\n key: '6',\n name: 'Joe Black',\n age: '24 year',\n address: 'Sidney No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n interest: 'such as climbing mountains, travelling, watching movie...',\n },\n {\n key: '7',\n name: 'Joe Black',\n age: '24 year',\n address: 'Sidney No. 1',\n work: 'New York No. 1',\n color: 'New York No. 1',\n fruit: 'Apples and melons are my',\n foods:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n school:\n 'Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.',\n interest: 'such as climbing mountains, travelling, watching movie...',\n },\n ],\n columns: [\n {\n title: 'Name',\n dataIndex: 'name',\n key: 'name',\n width: 200,\n fixed: 'left',\n },\n {\n title: 'Age',\n dataIndex: 'age',\n key: 'age',\n width: 250,\n },\n {\n title: 'Address',\n dataIndex: 'address',\n key: 'address',\n },\n {\n title: 'Work',\n dataIndex: 'work',\n key: 'work',\n },\n {\n title: 'Color',\n dataIndex: 'color',\n key: 'color',\n },\n {\n title: 'Fruit',\n dataIndex: 'fruit',\n key: 'fruit',\n },\n {\n title: 'Action',\n dataIndex: 'action',\n key: 'action',\n width: 100,\n fixed: 'right',\n render: () => (\n <div>\n <Button size=\"small\">删除</Button>\n </div>\n ),\n },\n ],\n };\n\n const getRenderTable = {\n dataSource: test.data,\n columns: test.columns,\n };\n return (\n <div>\n <h3>基本</h3>\n <p>基础表格。</p>\n <Table\n {...getRenderTable}\n />\n <h3>表格固定</h3>\n <p>固定头部和列。</p>\n <Table\n dataSource={demo3.data}\n columns={demo3.columns}\n height=\"300\"\n />\n <h3>带边框</h3>\n <p>添加表格边框线,页头和页脚。</p>\n <Table\n bordered\n {...getRenderTable}\n title={() => 'Header'}\n footer={() => 'Footer'}\n />\n <h3>可选择</h3>\n <p>第一列是联动的选择框。</p>\n <Table\n rowSelection={rowSelection}\n dataSource={this.state.dataSource}\n columns={this.state.columns}\n />\n <h3>排序</h3>\n <p>对某一列数据进行排序,通过指定列的 sorter 函数即可启动排序按钮。sorter: function(a, b) { '{...}' } , a、b 为比较的两个列数据。</p>\n <Table\n dataSource={demo1.data}\n columns={demo1.columns}\n onChange={this.onChange}\n />\n </div>\n );\n }\n}\n"},Rloj:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return g});var a=n("Jmof"),l=(n.n(a),n("kbwb")),o=n("HDB8"),s=n("QES8"),i=n("6Fy1"),r=n("1nuA"),c=n.n(r),m=n("PKY1"),u=n.n(m),p=class extends a.Component{constructor(){super(),this.onChange=(e=>{var t=e.text,n=e.value;this.setState({value:n,text:t})}),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.setSelect=(()=>{this.setState({value:"B"})}),this.state={disabled:!1,value:null,text:null}}render(){var e=this.state,t=e.value,n=e.disabled;return React.createElement("div",{className:"markdown-block"},React.createElement(l.a,{onClick:this.setDisabled},n?"启用":"禁用"),"   ",React.createElement(l.a,{onClick:this.setSelect},"选中BB"),React.createElement("h3",null,"受控"),React.createElement("p",null),React.createElement(o.a,{style:{width:250},disabled:n,defaultValue:"C",value:t,onChange:this.onChange,placeholder:"请选择"},React.createElement(i.a,{value:"A"},"AA"),React.createElement(i.a,{value:"B"},"BB"),React.createElement(i.a,{value:"C"},"CC"),React.createElement(i.a,{value:"D"},"DD"),React.createElement(i.a,{value:"E"},"EE"),React.createElement(i.a,{value:"F"},"FF"),React.createElement(i.a,{value:"G"},"GG")),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`),React.createElement("h3",null,"非受控"),React.createElement("p",null),React.createElement(o.a,{style:{width:250},disabled:n,defaultValue:"C",onChange:this.onChange,placeholder:"请选择"},React.createElement(i.a,{value:"A"},"AA"),React.createElement(i.a,{value:"B"},"BB"),React.createElement(i.a,{value:"C"},"CC"),React.createElement(i.a,{value:"D"},"DD"),React.createElement(i.a,{value:"E"},"EE"),React.createElement(i.a,{value:"F"},"FF"),React.createElement(i.a,{value:"G"},"GG")),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`))}},d=class extends a.Component{constructor(){super(),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.setSelect=(()=>{this.setState({value:"B"})}),this.onChange=(e=>{var t=e.text,n=e.value;this.setState({value:n,text:t})}),this.state={disabled:!1,value:null,text:null}}render(){var e=this.state,t=e.value,n=e.disabled;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"分组"),React.createElement("p",null),React.createElement(o.a,{style:{width:250},disabled:n,value:t,onChange:this.onChange,placeholder:"请选择"},React.createElement(s.a,{label:"分组1"},React.createElement(i.a,{value:"A"},"AA"),React.createElement(i.a,{value:"B"},"BB")),React.createElement(s.a,{label:"分组2"},React.createElement(i.a,{value:"C"},"CC"),React.createElement(i.a,{value:"D"},"DD")),React.createElement(s.a,{label:"分组3"},React.createElement(i.a,{value:"E"},"EE"),React.createElement(i.a,{value:"F"},"FF"),React.createElement(i.a,{value:"G"},"GG"))),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`),React.createElement("h3",null,"复杂选项。"),React.createElement("p",null),React.createElement(o.a,{style:{width:250},disabled:n,value:t,onChange:this.onChange,placeholder:"请选择"},React.createElement(i.a,{value:"A",text:"李大力"},React.createElement("div",null,"李大力"),React.createElement("div",null,"1354534324"),React.createElement("div",null,"杭州萧山区民和路")),React.createElement(i.a,{value:"B",text:"李启"},React.createElement("div",null,"李启"),React.createElement("div",null,"1356664324"),React.createElement("div",null,"杭州江干区")),React.createElement(i.a,{value:"C",text:"李宇"},React.createElement("div",null,"李宇"),React.createElement("div",null,"1377534324"),React.createElement("div",null,"杭州富阳")),React.createElement(i.a,{value:"D",text:"李琦"},React.createElement("div",null,"李琦"),React.createElement("div",null,"1354554324"),React.createElement("div",null,"杭州滨江区江")),React.createElement(i.a,{value:"E",text:"李小燕"},React.createElement("div",null,"李小燕"),React.createElement("div",null,"1387564324"),React.createElement("div",null,"上海黄埔区"))),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`))}},h=class extends a.Component{constructor(){super(),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.setDefaultValue=(()=>{this.setState({value:"CPU",text:"CPU"})}),this.onSearch=(e=>{var t=c.a.encode({code:"utf-8",q:e});u()(`https://suggest.taobao.com/sug?${t}`).then(e=>e.json()).then(e=>{var t=[];e.result.forEach(e=>{t.push({value:e[0],text:e[0]})}),this.setState({searchData:t})})}),this.onChange=(e=>{var t=e.value,n=e.text;this.setState({value:t,text:n})}),this.state={disabled:!1,value:null,text:null,searchData:[]}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement(l.a,{onClick:this.setDisabled},this.state.disabled?"启用":"禁用"),"   ",React.createElement(l.a,{onClick:this.setDefaultValue},"设值"),React.createElement("h3",null,"带搜索框。"),React.createElement("p",null),React.createElement(o.a,{style:{width:250},disabled:this.state.disabled,value:this.state.value,text:this.state.text,type:"combobox",onSearch:this.onSearch,onCancelChange:this.onCancelChange,onChange:this.onChange,placeholder:"请输入查询条件"},this.state.searchData.map(e=>React.createElement(i.a,{key:e.value,value:e.value},e.text))),React.createElement("span",null,"选中值:",`${this.state.value},${this.state.text}`))}},y=class extends a.Component{constructor(){super(),this.setDisabled=(()=>{this.setState({disabled:!this.state.disabled})}),this.onChangeProvince=(e=>{var t=e.value,n=e.text;this.setState({province:t,provinceText:n,city:null,cityText:null})}),this.onChangeCity=(e=>{var t=e.value,n=e.text;this.setState({city:t,cityText:n})}),this.getCitysByProvince=(e=>{switch(e){case"1":return[{value:"11",text:"杭州"},{value:"12",text:"湖州"},{value:"13",text:"绍兴"}];case"2":return[{value:"21",text:"广州"},{value:"22",text:"东莞"},{value:"23",text:"中山"}];case"3":return[{value:"31",text:"福州"},{value:"32",text:"泉州"},{value:"33",text:"厦门"}];default:return[]}}),this.state={value:null,text:null,disabled:!1,province:null,city:null}}render(){var e=this.getCitysByProvince(this.state.province).map((e,t)=>React.createElement(i.a,{value:e.value,key:t},e.text));return React.createElement("div",{className:"markdown-block"},React.createElement(l.a,{onClick:this.setDisabled},this.state.disabled?"启用":"禁用"),React.createElement("h3",null,"联动。"),React.createElement("p",null),"省:",React.createElement(o.a,{style:{width:250},disabled:this.state.disabled,value:this.state.province,onChange:this.onChangeProvince},React.createElement(i.a,{value:"1"},"浙江省"),React.createElement(i.a,{value:"2"},"广东省"),React.createElement(i.a,{value:"3"},"福建省")),"市:",React.createElement(o.a,{style:{width:250},disabled:this.state.disabled,value:this.state.city,onChange:this.onChangeCity},e),React.createElement("span",null,"选中值:",`${this.state.province}-${this.state.provinceText},${this.state.city}-${this.state.cityText}`))}},g=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement(p,null),React.createElement("br",null),React.createElement("br",null),React.createElement(d,null),React.createElement("br",null),React.createElement("br",null),React.createElement(h,null),React.createElement("br",null),React.createElement("br",null),React.createElement(y,null))}}},RtOM:function(e,t){e.exports="import { Component } from 'react';\nimport Button from '../../button';\nimport message from '../index';\n\nexport default class MessageDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {};\n }\n\n render() {\n message.config({\n top: 60,\n duration: 10,\n });\n return (\n <div className=\"markdown-block\">\n <h3>全局提示</h3>\n <p>各种类型的全局提示,自动消失</p>\n <Button onClick={() => { message.info('这是一条提示信息(信息内容)。'); }}>info</Button>&emsp;\n <Button type=\"secondary\" onClick={() => { message.success('这是一条提示信息(信息内容)。'); }}>success</Button>&emsp;\n <Button type=\"secondary\" onClick={() => { message.error('这是一条提示信息(信息内容)。'); }}>error</Button>&emsp;\n <Button type=\"secondary\" onClick={() => { message.warning('这是一条提示信息(信息内容)。'); }}>warning</Button>\n </div>\n );\n }\n}\n"},SH3Z:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## DatePicker\n\n输入或选择日期的控件。\n\n### 何时使用\n\n当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。\n\n### Props\n\n#### DatePicker\n\n|name|type|default|description|\n|---|---|---|---|\n|value|[moment](http://momentjs.com/)|无|日期|\n|defaultValue|[moment](http://momentjs.com/)|无|默认日期|\n|disabledDate|func|无|不可选择的日期|\n|disabled|boolean|false|禁用|\n|fieldSize|string|'normal'|'normal', 'large' or 'small',输入框尺寸|\n|fieldWidth|number|220|输入框宽度|\n|format|string|YYYY-MM-DD|展示日期格式,配置参考[moment](http://momentjs.com/)|\n|onChange|func|无|时间发生变化回调|\n\n#### MonthPicker\n|name|type|default|description|\n|---|---|---|---|\n|value|[moment](http://momentjs.com/)|无|日期|\n|defaultValue|[moment](http://momentjs.com/)|无|默认日期|\n|disabled|boolean|false|禁用|\n|fieldSize|string|'normal'|'normal', 'large' or 'small',输入框尺寸|\n|fieldWidth|number|220|输入框宽度|\n|format|string|YYYY-MM|展示日期格式,配置参考[moment](http://momentjs.com/)|\n|onChange|func|无|时间发生变化回调|\n\n#### RangePicker\n|name|type|default|description|\n|---|---|---|---|\n|value|[moment](http://momentjs.com/)[]|无|日期|\n|defaultValue|[moment](http://momentjs.com/)[]|无|默认日期|\n|disabledDate|func|无|不可选择的日期|\n|disabled|boolean|false|禁用|\n|fieldSize|string|'normal'|'normal', 'large' or 'small',输入框尺寸|\n|fieldWidth|number|null|输入框宽度|\n|format|string|YYYY-MM-DD|展示日期格式,配置参考[moment](http://momentjs.com/)|\n|onChange|func|无|时间发生变化回调|\n\n\n### Api"},SdPj:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,"._3jypcj4{text-align:center;background:rgba(0,0,0,.05);border-radius:4px;margin-bottom:20px;padding:30px 50px;margin:20px 0}",""]),t.locals={example1:"_3jypcj4"}},Sf3G:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n("lkey"),l=n("JJqH"),o=l.a.Menu,s=o.Item;t.default=(()=>{var e=React.createElement(o,null,React.createElement(s,null,React.createElement("a",{href:"https://www.ehuodi.com"},"易货嘀")),React.createElement(s,null,React.createElement("a",{href:"http://www.lujing56.cn/"},"陆鲸")),React.createElement(s,null,React.createElement("a",{href:"https://ecargo.ehuodi.com/"},"加盟车队管理系统")));return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"带下拉框的按钮"),React.createElement(l.a,{overlay:e},React.createElement(a.a,null,"菜单")),React.createElement("h3",null,"Dropdown内置按钮"),React.createElement(l.a.Button,{type:"secondary",overlay:e,trigger:"click"},"菜单"))})},SfWF:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return i});var a=n("Jmof"),l=(n.n(a),n("lkey")),o=n("eo4W"),s=o.a.Step,i=class extends a.Component{constructor(e){super(e),this.state={current:0},this.handleNext=this.handleNext.bind(this),this.handlePrev=this.handlePrev.bind(this)}handleNext(){this.setState(e=>e.current<3?{current:e.current+1}:{current:3})}handlePrev(){this.setState(e=>e.current>0?{current:e.current-1}:{current:0})}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,React.createElement(l.a,{disabled:this.state.current<=0,onClick:this.handlePrev},"上一步")," ",React.createElement(l.a,{disabled:this.state.current>=3,onClick:this.handleNext},"下一步")),React.createElement("h3",null,"横向步骤条"),React.createElement(o.a,{current:this.state.current,style:{marginBottom:10}},React.createElement(s,{title:"步骤1"}),React.createElement(s,{title:"步骤2"}),React.createElement(s,{title:"步骤3"}),React.createElement(s,{title:"步骤4"})),React.createElement(o.a,{current:this.state.current,isFinishIcon:!0,style:{marginBottom:10}},React.createElement(s,{title:"已完成"}),React.createElement(s,{title:"进行中"}),React.createElement(s,{title:"未进行"}),React.createElement(s,{title:"未进行"})),React.createElement(o.a,{current:this.state.current,style:{marginBottom:10}},React.createElement(s,{title:"步骤1",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"步骤2",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"步骤3",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"步骤4",description:"这是一段很长很长很长的描述性文字"})),React.createElement("h3",null,"竖向步骤条"),React.createElement("div",{style:{width:400,display:"inline-block"}},React.createElement(o.a,{current:this.state.current,direction:"vertical"},React.createElement(s,{title:"步骤1",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"步骤2",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"步骤3",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"步骤4"}))),React.createElement("div",{style:{display:"inline-block"}},React.createElement(o.a,{current:this.state.current,size:"small",direction:"vertical",isFinishIcon:!0},React.createElement(s,{title:"已完成",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"进行中",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"未进行",description:"这是一段很长很长很长的描述性文字"}),React.createElement(s,{title:"未进行",description:"这是一段很长很长很长的描述性文字"}))))}}},TJ8L:function(e,t){e.exports="import { Component } from 'react';\nimport Button from '../../button';\nimport notification from '../index';\nimport Icon from '../../icon';\nimport message from '../../message';\n\n\nexport default class PopoverDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {};\n }\n\n render() {\n const config = () => {\n notification.config({\n placement: 'bottomRight',\n bottom: 50,\n duration: 0,\n // getContainer: 'App',\n });\n message.success('全局配置成功');\n };\n\n const openNotification = () => {\n notification.open({\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openInfo = () => {\n notification.open({\n type: 'info',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openSuccess = () => {\n notification.open({\n type: 'success',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openError = () => {\n notification.open({\n type: 'error',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openWaring = () => {\n notification.open({\n type: 'warning',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openCaution = () => {\n notification.open({\n type: 'caution',\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n const openNoDuration = () => {\n notification.open({\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n duration: 0,\n });\n };\n\n const openIcon = () => {\n notification.open({\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n duration: 0,\n icon: <Icon\n style={{\n width: '34px',\n height: '34px',\n top: '16px',\n left: '24px',\n position: 'absolute',\n }}\n name={'clock'}\n />,\n });\n };\n\n const openButton = () => {\n const key = `open${Date.now()}`;\n const btnClick = () => {\n notification.close(key);\n };\n const btn = (\n <div>\n <Button type=\"primary\" onClick={btnClick}>\n 立即更新\n </Button>\n &emsp;\n <Button type=\"secondary\" onClick={btnClick}>\n 今晚提醒\n </Button>\n </div>\n );\n\n notification.open({\n type: 'warning',\n message: '请更新系统',\n description: '如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。',\n key,\n btn,\n });\n };\n\n\n const openButtonLink = () => {\n const btnlink = (\n <a href=\"./notification\">查看</a>\n );\n notification.open({\n type: 'warning',\n message: '请更新系统',\n description: '如果描述超过60字,请延长展示时间,一般人的阅读速度为,8-10字每秒。',\n btn: btnlink,\n });\n };\n\n const openPlacement = (placement) => {\n notification.open({\n placement,\n message: '需要及时知道的系统通知',\n description: '文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案',\n });\n };\n\n return (\n <div className=\"markdown-block\">\n <h3>基本使用</h3>\n <p>最简单的用法,4.5 秒后自动关闭</p>\n <Button onClick={openNotification}>显示通知</Button>&emsp;\n <h3>带有图标的通知提醒框</h3>\n <p>通知提醒框左侧有图标</p>\n <Button onClick={openInfo}>消息</Button>&emsp;\n <Button onClick={openSuccess}>成功</Button>&emsp;\n <Button onClick={openError}>错误</Button>&emsp;\n <Button onClick={openWaring}>警告</Button>&emsp;\n {/* <Button onClick={openCaution}>自定义</Button>&emsp; */}\n <h3>自定义图标</h3>\n <p>可自定义图标</p>\n <Button onClick={openIcon}>自定义</Button>&emsp;\n <h3>自动关闭的延时</h3>\n <p>取消4.5秒自动关闭</p>\n <Button onClick={openNoDuration}>显示通知</Button>&emsp;\n <h3>自定义按钮</h3>\n <p>可以置入功能按钮</p>\n <Button onClick={openButton}>按钮功能</Button>&emsp;\n <Button onClick={openButtonLink}>链接功能</Button>&emsp;\n <h3>位置</h3>\n <p>从右上角、右下角、左下角、左上角弹出</p>\n <Button onClick={() => openPlacement('topRight')}>右上角</Button>&emsp;\n <Button onClick={() => openPlacement('topLeft')}>左上角</Button>&emsp;\n <Button onClick={() => openPlacement('bottomLeft')}>左下角</Button>&emsp;\n <Button onClick={() => openPlacement('bottomRight')}>右下角</Button>&emsp;\n <h3>全局配置</h3>\n <p>在调用前提前配置,全局一次生效</p>\n <p>\n {`notification.config({\n placement: 'bottomRight',\n bottom:50,\n duration:0,\n getContainer:'App'\n });`}\n </p>\n <Button onClick={() => config()}>配置</Button>&emsp;\n <Button onClick={openNotification}>显示通知</Button>&emsp;\n </div>\n );\n }\n}\n"},Tmgj:function(e,t){e.exports="---\nauthor:\n name: lhf\n homepage: https://github.com/lhf/\n email: [email protected]\n---\n\n## Tooltip\n\nTooltip提示卡\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|action|hover or click|hover|触发类型|\n|tips|string or react.element|提示内容||\n|placement|string||提示框定位|\n|toolElement|string or react.element||触发提示的内容|\n\n\n### Api"},Uy2q:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("hFTO")),o=n("c+Ev"),s=n.n(o),i=n("Ni2A"),r=Object.keys(i.a),c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={color:document.documentElement.style.getPropertyValue("--brand-primary")},e}componentDidMount(){"function"==typeof MutationObserver&&new MutationObserver(e=>{e.forEach(()=>{this.setState({color:document.documentElement.style.getPropertyValue("--brand-primary")})})}).observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}render(){return React.createElement("div",{className:s.a.Icon__wrap},r.map(e=>React.createElement("div",{className:s.a.Icon__grid,key:e},React.createElement(l.a,{size:36,name:e,color:this.state.color}),React.createElement("span",{className:s.a.Icon__name},e))))}}},V40D:function(e,t,n){(t=e.exports=n("FZ+f")(void 0)).push([e.i,".ZwxVSXL{margin-right:8px}._2aC88hA{float:right;margin-top:16px;transform:scale(.8);transition:transform .3s}.menu-inline .menu-submenu-open>.menu-submenu-title ._2aC88hA{transform:scale(.8) rotate(270deg);transition:transform .3s}",""]),t.locals={"menu--icon":"ZwxVSXL","menu--icon__pullright":"_2aC88hA"}},Vc5Z:function(e,t){e.exports="---\nauthor:\n name: ryan.bian\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Trigger\n\n触发器。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|action| `hover` or `click`|`hover`|触发类型|\n|placement|`array`||弹出层定位|\n|offset|`array`|[0, 0]|定位偏移|\n|popup|`string` or `react.element`|弹出层内容|\n|popupVisible|bool|undefined|控制弹出层visible|\n|mouseEnterDelay|number|0|鼠标进入延时|\n|mouseLeaveDelay|number|100|鼠标移出延时|\n|onPopupVisibleChange|`function`|弹出层visible变化时触发|"},VscV:function(e,t){e.exports="import { Component } from 'react';\nimport Animation from '../Animation';\nimport Select from '../../select';\nimport Button from '../../button';\nimport MOTIONS, { TIMING_FUNCTION } from '../motions';\nconst { Option } = Select;\n\nexport default class AnimationDemo extends Component {\n state = {\n timeFunction: 'ease',\n status: false,\n motion: 'fade',\n };\n render() {\n const TFS = Object.keys(TIMING_FUNCTION);\n return (\n <div>\n <h3>TIME FUNCTION</h3>\n <Select\n value={this.state.timeFunction}\n onChange={({ value }) => {\n this.setState({\n timeFunction: value,\n });\n }}\n >\n {\n TFS.map(name => (\n <Option key={name} value={name}>{name}</Option>\n ))\n }\n </Select>\n <h3>MOTIONS</h3>\n <Select\n value={this.state.motion}\n onChange={({ value }) => {\n this.setState({\n motion: value,\n });\n }}\n >\n {\n MOTIONS.map(name => (\n <Option key={name} value={name}>{name}</Option>\n ))\n }\n </Select>\n <Button\n onClick={() => {\n this.setState({\n status: !this.state.status,\n });\n }}\n >toggle</Button>\n <div>\n <Animation\n in={this.state.status}\n timingFunction={this.state.timeFunction}\n motion={this.state.motion}\n style={{\n marginTop: 20,\n display: 'inline-block',\n }}\n >\n <div style={{\n width: 100,\n height: 100,\n border: '1px solid var(--brand-primary)',\n }}></div>\n </Animation>\n </div>\n </div>\n );\n }\n}\n"},W6RA:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("RfUY")),o=n("lkey"),s=n("TDF1"),i={left:{points:["cr","cl"]},right:{points:["cl","cr"]},top:{points:["bc","tc"]},bottom:{points:["tc","bc"]},topLeft:{points:["bl","tl"]},topRight:{points:["br","tr"]},bottomRight:{points:["tr","br"]},bottomLeft:{points:["tl","bl"]}},r=["hover","click"],c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={placement:"bottom",action:"click",visible:!1},this.onChangePlacement=(e=>{this.setState({placement:e.target.value})}),this.onChangeActionType=(e=>{this.setState({action:e.target.value})}),this.onClosePopup=(()=>{this.setState({visible:!1})}),this.onPopupVisibleChange=(e=>{console.log("onPopupVisibleChange",e),this.setState({visible:e})}),e}renderPlacementSelector(){var e=this.state.placement;return React.createElement("select",{value:e,onChange:this.onChangePlacement},Object.keys(i).map(e=>React.createElement("option",{key:e},e)))}render(){var e=this.state,t=e.placement,n=e.action;return React.createElement("div",{className:"markdown-block"},React.createElement("h5",null,"普通用法"),React.createElement("label",{htmlFor:"placement"},"对齐方式"),this.renderPlacementSelector(),React.createElement("label",{htmlFor:"action"},"触发方式"),React.createElement(s.a,{value:n,onChange:this.onChangeActionType},r.map(e=>React.createElement(s.b,{value:e,key:e},e))),React.createElement(l.a,{action:n,popup:React.createElement("div",{style:{border:"1px solid #000",padding:10,background:"#fff"}},"popup content"),placement:i[t].points,mouseLeaveDelay:100},React.createElement(o.a,null,`${n} me`)),React.createElement("h5",null,"手动控制关闭"),React.createElement(l.a,{action:"click",popupVisible:this.state.visible,popup:React.createElement("div",{onClick:this.onClosePopup},"click me to close"),onPopupVisibleChange:this.onPopupVisibleChange},React.createElement(o.a,null,"click")))}}},"WL//":function(e,t,n){"use strict";function a(e){console.log(`radio checked:${e.target.value}`)}Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return d});var l=n("Jmof"),o=(n.n(l),n("TDF1")),s=n("lkey"),i=n("Cs5U"),r=o.b.Group,c=o.b.Button,m=["Apple","Pear","Orange"],u=[{label:"Apple",value:"Apple"},{label:"Pear",value:"Pear"},{label:"Orange",value:"Orange"}],p=[{label:"Apple",value:"Apple"},{label:"Pear",value:"Pear"},{label:"Orange",value:"Orange",disabled:!1}],d=class extends l.Component{constructor(e){super(e),this.onChange=(e=>{console.log("radio checked",e.target.value),this.setState({value:e.target.value})}),this.onChange1=(e=>{this.setState({value1:e.target.value})}),this.onChange2=(e=>{this.setState({value2:e.target.value})}),this.onChange3=(e=>{this.setState({value3:e.target.value})}),this.handleChange=(()=>{this.setState({checked:!this.state.checked})}),this.handleToggle=(()=>{this.setState({disabled:!this.state.disabled})}),this.state={disabled:!1,checked:!1,value:1,value1:"Apple",value2:"Apple",value3:"Apple"}}render(){var e=this.state,t=e.checked,n=e.disabled,l=e.value1,d=e.value2,h=e.value3,y=e.value;return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"通过配置 options 参数来渲染单选框"),React.createElement("p",null,React.createElement(r,{options:m,onChange:this.onChange1,value:l,disabled:n})),React.createElement("p",null,React.createElement(r,{options:u,onChange:this.onChange2,value:d,disabled:n})),React.createElement("p",null,React.createElement(r,{options:p,onChange:this.onChange3,value:h,disabled:n})),React.createElement("h3",null,"嵌套的RadioGroup"),React.createElement(r,{onChange:this.onChange,value:y,disabled:n},React.createElement(o.b,{value:1},"Option A"),React.createElement(o.b,{value:2},"Option B"),React.createElement(o.b,{value:3},"Option C"),React.createElement(o.b,{value:4},"More...",4==y?React.createElement(i.a,{style:{width:100,marginLeft:10}}):null)),React.createElement("h3",null,"按钮样式的单选组合"),React.createElement(r,{onChange:a,defaultValue:"a",disabled:n},React.createElement(c,{value:"a"},"Hangzhou"),React.createElement(c,{value:"b"},"Shanghai"),React.createElement(c,{value:"c"},"Beijing"),React.createElement(c,{value:"d"},"Chengdu")),React.createElement("h3",null,"非受控方式"),React.createElement("p",null,React.createElement(o.b,{defaultChecked:!0,name:"my-radio",disabled:n}," 默认选中")),React.createElement("p",null,React.createElement(o.b,{name:"my-radio",disabled:n}," 默认")),React.createElement("h3",null,"受控方式"),React.createElement("p",null,React.createElement(o.b,{checked:t,onChange:this.handleChange,disabled:n}," ",t?"选中":"未选中")),React.createElement("p",null,React.createElement(o.b,{checked:t,onChange:this.handleChange,disabled:n}," ",t?"选中":"未选中")),React.createElement(s.a,{onClick:this.handleToggle},n?"启用":"禁用")," ",React.createElement(s.a,{onClick:this.handleChange},t?"取消选中":"选中"))}}},WmOt:function(e,t){e.exports='import { Component } from \'react\';\nimport Popconfirm from \'../Popconfirm\';\nimport Popover from \'../../popover/Popover\';\nimport Icon from \'../../icon/Icon\';\nimport Button from \'../../button/Button\';\nimport { allowMultiple } from \'../../../constants\';\nimport styles from \'./index.css\';\n\nexport default class PopconfirmDemo extends Component {\n state = {visible : false};\n handleOkClickTrigger = () =>{\n this.setState({\n visible: false,\n });\n }\n render() {\n const ele = (<div><p>top</p><p>这是一个气泡确认框</p></div>);\n const warning = (<div><Icon size={15} name=\'warning\' color=\'#f9d900\'></Icon><span>这是一个气泡确认框,确定要这样做吗?</span></div>);\n return (\n <div>\n <div className={styles[\'top-tooltip\']}>\n <div className={styles[\'top-tooltip-div\']}><Popconfirm content={warning} placement="topLeft" handleOkClickTrigger={this.handleOkClickTrigger} ><Button type="secondary">上左,有ok事件</Button></Popconfirm></div>\n <div className={styles[\'top-tooltip-div\']}><Popconfirm content={warning} placement="top" action="click" handleOkClickTrigger={this.handleOkClickTrigger} confirmVisable = {this.state.visible}><Button type="secondary">点击</Button></Popconfirm></div>\n <div className={styles[\'top-tooltip-div\']}><Popconfirm content={ele} placement="topRight" ><Button type="secondary">上右</Button></Popconfirm></div>\n </div>\n <div className={styles[\'left-tooltip\']} >\n <div className={styles[\'left-tooltip-div\']}><Popconfirm content="leftTop" placement="leftTop" ><Button type="secondary">左上</Button></Popconfirm></div>\n <div className={styles[\'left-tooltip-div\']}><Popconfirm content=\'left\' placement="left" ><Button type="secondary">左</Button></Popconfirm></div>\n <div className={styles[\'left-tooltip-div\']}><Popconfirm content=\'leftBottom\' placement="leftBottom" ><Button type="secondary">左下</Button></Popconfirm></div>\n </div>\n <div className={styles[\'right-tooltip\']} >\n <div className={styles[\'right-tooltip-div\']}><Popconfirm content="rightTop" placement="rightTop" ><Button type="secondary">右上</Button></Popconfirm></div>\n <div className={styles[\'right-tooltip-div\']}><Popconfirm content="right" placement="right" ><Button type="secondary">右</Button></Popconfirm></div>\n <div className={styles[\'right-tooltip-div\']}><Popconfirm content="rightBottom" placement="rightBottom" ><Button type="secondary">左下</Button></Popconfirm></div>\n </div>\n <div className={styles[\'bottom-tooltip\']}>\n <div className={styles[\'bottom-tooltip-div\']}><Popconfirm content="bottomLeft" placement="bottomLeft" ><Button type="secondary">下左</Button></Popconfirm></div>\n <div className={styles[\'bottom-tooltip-div\']}><Popconfirm content="bottom" placement="bottom"><Button type="secondary">下</Button></Popconfirm></div>\n <div className={styles[\'bottom-tooltip-div\']}><Popconfirm content="bottomRight" placement="bottomRight"><Button type="secondary">下右</Button></Popconfirm></div>\n </div>\n </div>\n );\n }\n}\n'},Xnxm:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/october-yan/\n---\n\n## Tabs\n\n选项卡切换组件\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|defaultActiveKey|number|第一个面板|初始化选中面板的 key|\n|onClick|Function|无|切换面板的回调|\n|type|String|'line'|页签的基本样式,可选 line、card、button 类型|\n|size|String|'default'|大小,提供 default 和 small 两种大小|\n|tabPosition|String||页签位置,可选值有 left|\n\n### Tabs.Panel\n|name|type|default|description|\n|---|---|---|---|\n|key|String|无|对应 activeKey|\n|title|string|无|选项卡头显示文字|\n\n### Api"},Xrcb:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Checkbox\n\nCheckbox Component.\n\n### Props\n#### Checkbox\n|name|type|default|description|\n|---|---|---|---|\n|checked|boolean|false|指定当前是否选中|\n|defaultChecked|boolean|false|初始是否选中|\n|onChange|Function(e:Event)|-|变化时回调函数|\n\n\n#### CheckboxGroup \n|name|type|default|description|\n|---|---|:---:|:---:|\n|defaultValue|Array|[]|默认选中的选项|\n|value|Array|[]|指定选中的选项|\n|options|Array|[]|指定可选项|\n|onChange|Function|-|变化时回调函数|\n### Api"},YCo2:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=n.n(a),o=n("L2Pg"),s=n("hFTO"),i=n("FaRr"),r=n.n(i),c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={theme:"dark",selectedKeys:[".$.$m0"],openKeys:null},this.handleClick=(e=>{this.setState({selectedKeys:[e.key]})}),this.handleOpenChange=(e=>{this.setState({openKeys:e})}),e}render(){return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("table",{style:{width:"100%"}},l.a.createElement("tbody",null,l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"1、水平菜单,子菜单水平")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",null,l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-h",colorType:"warm"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3"),l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用"))),l.a.createElement("td",null,l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-h",colorType:"cold"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3"),l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")))),l.a.createElement("tr",null,l.a.createElement("td",{style:{height:"30px"}}),l.a.createElement("td",null)),l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"2、水平菜单,子菜单垂直")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",null,l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-v",colorType:"warm"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(o.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(o.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(o.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(o.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(o.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用"))),l.a.createElement("td",null,l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,defaultOpenKeys:null,type:"horizontal-v",colorType:"cold"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(o.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"分组")},l.a.createElement(o.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(o.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(o.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(o.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用")))),l.a.createElement("tr",null,l.a.createElement("td",{style:{height:"30px"}}),l.a.createElement("td",null)),l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"3、垂直菜单,子菜单水平向右弹出")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",null,l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240,height:500},defaultOpenKeys:null,type:"vertical-h",colorType:"warm"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(o.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(o.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(o.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(o.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(o.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮"))),l.a.createElement("td",null,l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240,height:500},defaultOpenKeys:null,type:"vertical-h",colorType:"cold"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(o.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(o.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(o.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.ItemGroup,{key:"m2m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2m2g1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g1i2"},"三级菜单2")),l.a.createElement(o.a.ItemGroup,{key:"m2m2g2",title:"分组2"},l.a.createElement(o.a.Item,{key:"m2m2g2i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2g2i2"},"三级菜单2")))),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮")))),l.a.createElement("tr",null,l.a.createElement("td",{style:{height:"30px"}}),l.a.createElement("td",null)),l.a.createElement("tr",null,l.a.createElement("td",{colSpan:"2"},"4、垂直菜单,子菜单内嵌在菜单区域")),l.a.createElement("tr",null,l.a.createElement("th",{style:{width:"50%"}},"KA"),l.a.createElement("th",{style:{width:"50%"}},"车队加盟")),l.a.createElement("tr",null,l.a.createElement("td",{style:{verticalAlign:"top"}},l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240},defaultOpenKeys:null,selectedKeys:this.state.selectedKeys,openKeys:this.state.openKeys,type:"vertical-v",colorType:"warm"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(o.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(o.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(o.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m2m2i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2i2"},"三级菜单2"),l.a.createElement(o.a.Item,{key:"m2m2i3"},"三级菜单3"),l.a.createElement(o.a.Item,{key:"m2m2i4"},"三级菜单4"))),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮"))),l.a.createElement("td",{style:{verticalAlign:"top"}},l.a.createElement(o.a,{onClick:this.handleClick,onOpenChange:this.handleOpenChange,style:{width:240},defaultOpenKeys:null,selectedKeys:this.state.selectedKeys,openKeys:this.state.openKeys,type:"vertical-v",colorType:"cold"},l.a.createElement(o.a.Item,{key:"m0"},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"菜单按钮"),l.a.createElement(o.a.SubMenu,{key:"m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单")},l.a.createElement(o.a.Item,{key:"m1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m1i3"},"二级菜单3"),l.a.createElement(o.a.SubMenu,{key:"m1m1",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m1m1i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m1m1i2"},"三级菜单2"))),l.a.createElement(o.a.SubMenu,{key:"m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"下拉菜单分组")},l.a.createElement(o.a.ItemGroup,{key:"m2g1",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g1i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g1i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g1i3"},"二级菜单3")),l.a.createElement(o.a.ItemGroup,{key:"m2g2",title:"分组1"},l.a.createElement(o.a.Item,{key:"m2g2i1"},"二级菜单1"),l.a.createElement(o.a.Item,{key:"m2g2i2"},"二级菜单2"),l.a.createElement(o.a.Item,{key:"m2g2i3"},"二级菜单3")),l.a.createElement(o.a.SubMenu,{key:"m2m2",title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"三级菜单")},l.a.createElement(o.a.Item,{key:"m2m2i1"},"三级菜单1"),l.a.createElement(o.a.Item,{key:"m2m2i2"},"三级菜单2"),l.a.createElement(o.a.Item,{key:"m2m2i3"},"三级菜单3"),l.a.createElement(o.a.Item,{key:"m2m2i4"},"三级菜单4"))),l.a.createElement(o.a.SubMenu,{key:"m3",disabled:!0,title:l.a.createElement("span",null,l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),l.a.createElement(s.a,{className:r.a["menu--icon__pullright"],size:12,name:"arrow-right"}),"不可用下拉菜单")},l.a.createElement(o.a.Item,{key:"m3i1"},"二级菜单4"),l.a.createElement(o.a.Item,{key:"m3i2"},"二级菜单5")),l.a.createElement(o.a.Item,{key:"m4",disabled:!0},l.a.createElement(s.a,{className:r.a["menu--icon"],size:14,name:"attachment"}),"不可用菜单按钮")))))))}}},YWGe:function(e,t){e.exports="---\nauthor:\n name: Northerner\n email: [email protected]\n---\n\n## Spin\n\nSpin Component.\n\n### Props\n|name|type|default|description|\n|---|---|:---:|:---:|\n|size|String|'default'|spin size,`default` `large` or `small`|\n|tip|String|-|延迟显示加载效果的时间|\n|spinning|boolean|true|是否旋转|\n|delay|number|-|延迟显示加载效果的时间|\n\n### Api"},ag5k:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Alert\n\nAlert Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|type|string|'info'|指定警告提示的样式,有四种选择 success、info、warning、error|\n|closable|boolean|false|\t显示关闭按钮|\n|showIcon|boolean|true|\t显示图标|\n|closeText|string or ReactNode|无|自定义关闭按钮|\n|message|string or ReactNode|无|警告提示内容|\n|description|string or ReactNode|无|警告提示的辅助性文字介绍|\n|onClose|Function|无|关闭时触发的回调函数|\n### Api"},azB9:function(e,t){e.exports="import { Component } from 'react';\nimport Alert from '../index';\n\nexport default class AlertDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {};\n }\n\n render() {\n const successProps = {\n type: 'success',\n message: '这是一条正确的提示信息(信息内容)。',\n };\n const infoProps = {\n type: 'info',\n message: 'info信息',\n description: 'info描info描述info描述info描述info描述info描述info描述info描述info描述info描述info描述述',\n };\n const errorProps = {\n type: 'error',\n message: '这是一条错误的提示信息(信息内容)。',\n onClose() { console.log('error'); },\n };\n const warnProps = {\n type: 'warning',\n message: '这是一条错误的提示信息(信息内容)。',\n };\n\n return (\n <div className=\"markdown-block\">\n <h3>基本的提示</h3>\n <Alert {...successProps} />\n <h3>可关闭的提示</h3>\n <Alert {...errorProps} closable />\n <Alert type=\"warning\" message=\"这是一条警告的提示信息(信息内容)。\" showIcon closable closeText=\"close me\" />\n <h3>带图标的提示</h3>\n <Alert {...infoProps} showIcon />\n <Alert {...successProps} showIcon />\n <Alert {...errorProps} showIcon />\n <Alert {...warnProps} showIcon />\n <h3>含有辅助性文字介绍的提示</h3>\n <Alert {...infoProps} closable showIcon />\n <Alert type=\"error\" message=\"error信息\" description=\"这是一条错误的提示信息(信息内容)。\" />\n </div>\n );\n }\n}\n"},"c+Ev":function(e,t,n){var a=n("IAgb");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},cJNF:function(e,t){e.exports='import { Component } from \'react\';\nimport Button from \'../../button\';\nimport Steps from \'../Steps\';\n\nconst Step = Steps.Step;\n\nexport default class StepDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {\n current: 0,\n };\n this.handleNext = this.handleNext.bind(this);\n this.handlePrev = this.handlePrev.bind(this);\n }\n\n handleNext() {\n this.setState((preState) => {\n if (preState.current < 3) {\n return { current: preState.current + 1 };\n }\n return { current: 3 };\n });\n }\n\n handlePrev() {\n this.setState((preState) => {\n if (preState.current > 0) {\n return { current: preState.current - 1 };\n }\n return { current: 0 };\n });\n }\n\n render() {\n return (\n <div className="markdown-block">\n <h3><Button disabled={this.state.current <= 0} onClick={this.handlePrev}>上一步</Button>&nbsp;\n <Button disabled={this.state.current >= 3} onClick={this.handleNext}>下一步</Button></h3>\n <h3>横向步骤条</h3>\n <Steps current={this.state.current} style={{ marginBottom: 10 }}>\n <Step title="步骤1" />\n <Step title="步骤2" />\n <Step title="步骤3" />\n <Step title="步骤4" />\n </Steps>\n <Steps current={this.state.current} isFinishIcon style={{ marginBottom: 10 }}>\n <Step title="已完成" />\n <Step title="进行中" />\n <Step title="未进行" />\n <Step title="未进行" />\n </Steps>\n <Steps current={this.state.current} style={{ marginBottom: 10 }}>\n <Step title="步骤1" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤2" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤3" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤4" description="这是一段很长很长很长的描述性文字" />\n </Steps>\n\n <h3>竖向步骤条</h3>\n <div style={{ width: 400, display: \'inline-block\' }}>\n <Steps current={this.state.current} direction="vertical">\n <Step title="步骤1" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤2" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤3" description="这是一段很长很长很长的描述性文字" />\n <Step title="步骤4" />\n </Steps>\n </div>\n <div style={{ display: \'inline-block\' }}>\n <Steps current={this.state.current} size={\'small\'} direction="vertical" isFinishIcon>\n <Step title="已完成" description="这是一段很长很长很长的描述性文字" />\n <Step title="进行中" description="这是一段很长很长很长的描述性文字" />\n <Step title="未进行" description="这是一段很长很长很长的描述性文字" />\n <Step title="未进行" description="这是一段很长很长很长的描述性文字" />\n </Steps>\n </div>\n </div>\n );\n }\n\n}\n'},cjKs:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=(n.n(a),n("o8IH")),o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},s=class extends a.Component{constructor(e){super(e),this.state={}}render(){var e={type:"success",message:"这是一条正确的提示信息(信息内容)。"},t={type:"info",message:"info信息",description:"info描info描述info描述info描述info描述info描述info描述info描述info描述info描述info描述述"},n={type:"error",message:"这是一条错误的提示信息(信息内容)。",onClose(){console.log("error")}},a={type:"warning",message:"这是一条错误的提示信息(信息内容)。"};return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本的提示"),React.createElement(l.a,e),React.createElement("h3",null,"可关闭的提示"),React.createElement(l.a,o({},n,{closable:!0})),React.createElement(l.a,{type:"warning",message:"这是一条警告的提示信息(信息内容)。",showIcon:!0,closable:!0,closeText:"close me"}),React.createElement("h3",null,"带图标的提示"),React.createElement(l.a,o({},t,{showIcon:!0})),React.createElement(l.a,o({},e,{showIcon:!0})),React.createElement(l.a,o({},n,{showIcon:!0})),React.createElement(l.a,o({},a,{showIcon:!0})),React.createElement("h3",null,"含有辅助性文字介绍的提示"),React.createElement(l.a,o({},t,{closable:!0,showIcon:!0})),React.createElement(l.a,{type:"error",message:"error信息",description:"这是一条错误的提示信息(信息内容)。"}))}}},fgYh:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return h});var a=n("Jmof"),l=(n.n(a),n("Pp2j")),o=(n("TDF1"),n("lkey"),n("a8z9")),s=o.a.Panel,i=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"标准线条式页签"),React.createElement(o.a,{activeKey:this.state.activeKey,onClick:this.onClick},this.state.panes.map(e=>React.createElement(s,{title:e.title,key:e.key,closable:e.closable},e.content))))}},r=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"禁用"),React.createElement("p",null,"对某项实行禁用"),React.createElement(o.a,{activeKey:this.state.activeKey,onClick:this.onClick},React.createElement(s,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 1"),key:"1"},"Tab 1"),React.createElement(s,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 2"),key:"2"},"Tab 2"),React.createElement(s,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 3"),key:"3",disabled:!0},"Tab 3")))}},c=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"迷你"),React.createElement("p",null,"用在狭小的区块或子级Tab"),React.createElement(o.a,{size:"small",activeKey:this.state.activeKey,onClick:this.onClick},this.state.panes.map(e=>React.createElement(s,{title:e.title,key:e.key,closable:e.closable},e.content))))}},m=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"带图标"),React.createElement("p",null,"带图标的Tab"),React.createElement(o.a,{activeKey:this.state.activeKey,onClick:this.onClick},React.createElement(s,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 1"),key:"1"},"Tab 1"),React.createElement(s,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 2"),key:"2"},"Tab 2"),React.createElement(s,{title:React.createElement("span",null,React.createElement(l.a,{size:18,name:"account"}),"Tab 3"),key:"3"},"Tab 3")))}},u=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"纵向"),React.createElement("p",null,"纵向的Tab"),React.createElement(o.a,{activeKey:this.state.activeKey,tabPosition:"left",onClick:this.onClick},this.state.panes.map(e=>React.createElement(s,{title:e.title,key:e.key,closable:e.closable},e.content))))}},p=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"卡片式"),React.createElement("p",null,"卡片式的页签,常用于容器顶部"),React.createElement(o.a,{activeKey:this.state.activeKey,type:"card",tabDeleteButton:!0,deleteButton:this.deleteButton,onClick:this.onClick},this.state.panes.map(e=>React.createElement(s,{title:e.title,key:e.key,closable:e.closable},e.content))))}},d=class extends a.Component{constructor(e){super(e),this.deleteButton=(()=>{var e=this.state.panes,t=this.state.activeKey;e.splice(t,1),e.length<=t+1&&(t=e.length-1),this.setState({panes:e,activeKey:t})}),this.onClick=(e=>{this.setState({activeKey:e})});var t=[{title:"Tab 1",content:"Content of Tab 1",key:1,closable:!1},{title:"Tab 2",content:"Content of Tab 2",key:2},{title:"Tab 3",content:"Content of Tab 3",key:3}];this.state={activeKey:t[0].key,panes:t}}render(){return React.createElement("div",{className:"markdown-block"},React.createElement("p",null,"button可作为更次级的页签来使用"),React.createElement(o.a,{activeKey:this.state.activeKey,type:"button",onClick:this.onClick},this.state.panes.map(e=>React.createElement(s,{title:e.title,key:e.key,closable:e.closable},e.content))))}},h=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement(i,null),React.createElement("br",null),React.createElement("br",null),React.createElement(r,null),React.createElement("br",null),React.createElement("br",null),React.createElement(c,null),React.createElement("br",null),React.createElement("br",null),React.createElement(m,null),React.createElement("br",null),React.createElement("br",null),React.createElement(u,null),React.createElement("br",null),React.createElement("br",null),React.createElement(p,null),React.createElement("br",null),React.createElement("br",null),React.createElement(d,null),React.createElement("br",null),React.createElement("br",null))}}},flwl:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=n.n(a),o=n("m1Gx"),s=n("lkey"),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},r=o.a.Table,c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={selectedRowKeys:[1,2],dataSource:[{key:"1",name:"John Brown",age:"24 year",address:"New York No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."},{key:"2",name:"Jim Green",age:"24 year",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."},{key:"3",name:"Jim Green",age:"24 year",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."}],columns:[{title:"",dataIndex:"select",key:"select",width:100},{title:"Name",dataIndex:"name",key:"name",width:200},{title:"Age",dataIndex:"age",key:"age",width:250},{title:"Address",dataIndex:"address",key:"address"},{title:"Work",dataIndex:"work",key:"work"},{title:"Color",dataIndex:"color",key:"color"},{title:"Fruit",dataIndex:"fruit",key:"fruit"},{title:"Action",dataIndex:"action",key:"action",width:100,render:()=>l.a.createElement("div",null,l.a.createElement(s.a,{size:"small"},"删除"))}]},this.onChange=(e=>{this.setState({sortedInfo:e})}),this.onSelectChange=(e=>{this.setState({selectedRowKeys:e})}),e}render(){var e={selectedRowKeys:this.state.selectedRowKeys,onSelectChange:this.onSelectChange,selections:"all-data"},t=this.state.sortedInfo,n={data:[{key:"1",name:"John Brown",age:"20",address:"New York No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."},{key:"2",name:"Jim Greenss",age:"90",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."},{key:"3",name:"Jim Green",age:"70",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."}],columns:[{title:"Name",dataIndex:"name",key:"name",width:200,sorter:(e,t)=>e.name.length-t.name.length,sortOrder:"name"===(t=t||{}).columnKey&&t.order},{title:"Age",dataIndex:"age",key:"age",width:250,sorter:(e,t)=>e.age-t.age,sortOrder:"age"===t.columnKey&&t.order},{title:"Address",dataIndex:"address",key:"address"},{title:"Action",dataIndex:"action",key:"action",width:100,render:()=>l.a.createElement("div",null,l.a.createElement(s.a,{size:"small"},"删除"))}]},a={data:[{key:"1",name:"John Brown",age:"24 year",address:"New York No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."},{key:"2",name:"Jim Green",age:"24 year",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."},{key:"3",name:"Jim Green",age:"24 year",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my favourite fruits."}],columns:[{title:"Name",dataIndex:"name",key:"name",width:200},{title:"Age",dataIndex:"age",key:"age",width:250},{title:"Address",dataIndex:"address",key:"address"},{title:"Work",dataIndex:"work",key:"work"},{title:"Color",dataIndex:"color",key:"color"},{title:"Fruit",dataIndex:"fruit",key:"fruit"},{title:"Action",dataIndex:"action",key:"action",width:100,render:()=>l.a.createElement("div",null,l.a.createElement(s.a,{size:"small"},"删除"))}]},o={data:[{key:"1",name:"John Brown",age:"24 year",address:"New York No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my ",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",interest:"such as climbing mountains, travelling, watching movie..."},{key:"2",name:"Jim Green",age:"24 year",address:"London No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",interest:"such as climbing mountains, travelling, watching movie..."},{key:"3",name:"Joe Black",age:"24 year",address:"Sidney No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",interest:"such as climbing mountains, travelling, watching movie..."},{key:"4",name:"Joe Black",age:"24 year",address:"Sidney No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",interest:"such as climbing mountains, travelling, watching movie..."},{key:"5",name:"Joe Black",age:"24 year",address:"Sidney No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits."},{key:"6",name:"Joe Black",age:"24 year",address:"Sidney No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",interest:"such as climbing mountains, travelling, watching movie..."},{key:"7",name:"Joe Black",age:"24 year",address:"Sidney No. 1",work:"New York No. 1",color:"New York No. 1",fruit:"Apples and melons are my",foods:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",school:"Apples and melons are my favourite fruits.Apples and melons are my favourite fruits.",interest:"such as climbing mountains, travelling, watching movie..."}],columns:[{title:"Name",dataIndex:"name",key:"name",width:200,fixed:"left"},{title:"Age",dataIndex:"age",key:"age",width:250},{title:"Address",dataIndex:"address",key:"address"},{title:"Work",dataIndex:"work",key:"work"},{title:"Color",dataIndex:"color",key:"color"},{title:"Fruit",dataIndex:"fruit",key:"fruit"},{title:"Action",dataIndex:"action",key:"action",width:100,fixed:"right",render:()=>l.a.createElement("div",null,l.a.createElement(s.a,{size:"small"},"删除"))}]},c={dataSource:a.data,columns:a.columns};return l.a.createElement("div",null,l.a.createElement("h3",null,"基本"),l.a.createElement("p",null,"基础表格。"),l.a.createElement(r,c),l.a.createElement("h3",null,"表格固定"),l.a.createElement("p",null,"固定头部和列。"),l.a.createElement(r,{dataSource:o.data,columns:o.columns,height:"300"}),l.a.createElement("h3",null,"带边框"),l.a.createElement("p",null,"添加表格边框线,页头和页脚。"),l.a.createElement(r,i({bordered:!0},c,{title:()=>"Header",footer:()=>"Footer"})),l.a.createElement("h3",null,"可选择"),l.a.createElement("p",null,"第一列是联动的选择框。"),l.a.createElement(r,{rowSelection:e,dataSource:this.state.dataSource,columns:this.state.columns}),l.a.createElement("h3",null,"排序"),l.a.createElement("p",null,"对某一列数据进行排序,通过指定列的 sorter 函数即可启动排序按钮。sorter: function(a, b) ","{...}"," , a、b 为比较的两个列数据。"),l.a.createElement(r,{dataSource:n.data,columns:n.columns,onChange:this.onChange}))}}},frv8:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Message\n\nMessage Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|duration|Number|1.8|message 1.8s之后关闭|\n|onClose|Function|function(){}|message 关闭之后的回调|\n|type|String|'info'|message 提示类型|\n### Api\n组件提供了一些静态方法,使用方式和参数如下:\n\n - message.success(content, duration, onClose)\n - message.error(content, duration, onClose)\n - message.info(content, duration, onClose)\n - message.warning(content, duration, onClose)\n\n\n#### 参数\n|name|type|default|description|\n|---|---|---|---|\n|content|string|''|提示内容\n|duration|Number|1.8|message 默认1.8s之后关闭,可通过config设置|\n|onClose|Function|function(){}|message 关闭之后的回调,可通过config设置|\n\n还提供了全局配置和全局销毁方法:\n\n - message.config(options)\n - message.destroty() \n\n\n#### config方法参数\n|name|type|default|description|\n|---|---|---|---|\n|top|number|50px|消息距离顶部的距离\n|duration|Number|1.8|message 默认1.8s之后关闭,可通过config设置|\n|getContainer|Function|function(){}|配置渲染节点的输出位置|\n\n"},iBQZ:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=n.n(a),o=n("E7AL"),s=class extends a.Component{render(){return l.a.createElement("div",{className:"markdown-block"},l.a.createElement("h3",null,"标准进度条"),l.a.createElement("div",null,l.a.createElement(o.a,{percent:30}),l.a.createElement(o.a,{percent:70,status:"exception"}),l.a.createElement(o.a,{percent:70,status:"pause"}),l.a.createElement(o.a,{percent:100,status:"success"}),l.a.createElement(o.a,{percent:100}),l.a.createElement(o.a,{percent:50,showInfo:!1})),l.a.createElement("h3",null,"小型进度条"),l.a.createElement("p",null,"适合放在较狭窄的区域内"),l.a.createElement("div",{style:{width:170}},l.a.createElement(o.a,{percent:30,size:"mini"}),l.a.createElement(o.a,{percent:70,size:"mini",status:"exception"}),l.a.createElement(o.a,{percent:70,size:"mini",status:"pause"}),l.a.createElement(o.a,{percent:100,size:"mini",status:"success"}),l.a.createElement(o.a,{percent:100,size:"mini"})))}}},iHBT:function(e,t){e.exports='import React, { Component } from \'react\';\nimport Menu from \'../Menu\';\nimport Icon from \'../../icon/Icon\';\nimport styles from \'./index.css\';\n\nexport default class MenuDemo extends Component {\n state = {\n theme: \'dark\',\n selectedKeys: [\'.$.$m0\'],\n openKeys: null,\n }\n\n handleClick = (e) => {\n this.setState({\n selectedKeys: [e.key],\n });\n }\n handleOpenChange = (openKeys) => {\n this.setState({\n openKeys,\n });\n }\n\n render() {\n // const defaultOpenKeys = [\'.$m1\', \'.$.$m2\', \'.$.$m2m2\'];\n const defaultOpenKeys = null;\n\n return (\n <div className="markdown-block">\n <table style={{ width: \'100%\' }}>\n <tbody>\n <tr>\n <td colSpan="2">1、水平菜单,子菜单水平</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-h"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-h"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n <tr><td style={{ height: \'30px\' }} /><td /></tr>\n <tr>\n <td colSpan="2">2、水平菜单,子菜单垂直</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-v"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n defaultOpenKeys={defaultOpenKeys}\n type="horizontal-v"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n <tr><td style={{ height: \'30px\' }} /><td /></tr>\n <tr>\n <td colSpan="2">3、垂直菜单,子菜单水平向右弹出</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240, height: 500 }}\n defaultOpenKeys={defaultOpenKeys}\n type="vertical-h"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n <td>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240, height: 500 }}\n defaultOpenKeys={defaultOpenKeys}\n type="vertical-h"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.ItemGroup key="m2m2g1" title="分组1">\n <Menu.Item key="m2m2g1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g1i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2m2g2" title="分组2">\n <Menu.Item key="m2m2g2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2g2i2">三级菜单2</Menu.Item>\n </Menu.ItemGroup>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n <tr><td style={{ height: \'30px\' }} /><td /></tr>\n <tr>\n <td colSpan="2">4、垂直菜单,子菜单内嵌在菜单区域</td>\n </tr>\n <tr>\n <th style={{ width: \'50%\' }}>KA</th><th style={{ width: \'50%\' }}>车队加盟</th>\n </tr>\n <tr>\n <td style={{ verticalAlign: \'top\' }}>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240 }}\n defaultOpenKeys={defaultOpenKeys}\n selectedKeys={this.state.selectedKeys}\n openKeys={this.state.openKeys}\n type="vertical-v"\n colorType="warm"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m2m2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2i2">三级菜单2</Menu.Item>\n <Menu.Item key="m2m2i3">三级菜单3</Menu.Item>\n <Menu.Item key="m2m2i4">三级菜单4</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n <td style={{ verticalAlign: \'top\' }}>\n <Menu\n onClick={this.handleClick}\n onOpenChange={this.handleOpenChange}\n style={{ width: 240 }}\n defaultOpenKeys={defaultOpenKeys}\n selectedKeys={this.state.selectedKeys}\n openKeys={this.state.openKeys}\n type="vertical-v"\n colorType="cold"\n >\n\n <Menu.Item key="m0">\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />\n 菜单按钮\n </Menu.Item>\n <Menu.SubMenu key="m1" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单</span>}>\n <Menu.Item key="m1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m1i3">二级菜单3</Menu.Item>\n <Menu.SubMenu key="m1m1" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m1m1i1">三级菜单1</Menu.Item>\n <Menu.Item key="m1m1i2">三级菜单2</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m2" title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />下拉菜单分组</span>}>\n <Menu.ItemGroup key="m2g1" title="分组1">\n <Menu.Item key="m2g1i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g1i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g1i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.ItemGroup key="m2g2" title="分组1">\n <Menu.Item key="m2g2i1">二级菜单1</Menu.Item>\n <Menu.Item key="m2g2i2">二级菜单2</Menu.Item>\n <Menu.Item key="m2g2i3">二级菜单3</Menu.Item>\n </Menu.ItemGroup>\n <Menu.SubMenu key="m2m2" title={<span><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />三级菜单</span>}>\n <Menu.Item key="m2m2i1">三级菜单1</Menu.Item>\n <Menu.Item key="m2m2i2">三级菜单2</Menu.Item>\n <Menu.Item key="m2m2i3">三级菜单3</Menu.Item>\n <Menu.Item key="m2m2i4">三级菜单4</Menu.Item>\n </Menu.SubMenu>\n </Menu.SubMenu>\n <Menu.SubMenu key="m3" disabled title={<span><Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} /><Icon className={styles[\'menu--icon__pullright\']} size={12} name={\'arrow-right\'} />不可用下拉菜单</span>}>\n <Menu.Item key="m3i1">二级菜单4</Menu.Item>\n <Menu.Item key="m3i2">二级菜单5</Menu.Item>\n </Menu.SubMenu>\n <Menu.Item key="m4" disabled>\n <Icon className={styles[\'menu--icon\']} size={14} name={\'attachment\'} />不可用菜单按钮\n </Menu.Item>\n </Menu>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n }\n}\n'},jC5m:function(e,t){e.exports='import { Component } from \'react\';\nimport Button from \'../../button/Button\';\nimport Select from \'../Select\';\nimport OptGroup from \'../OptGroup\';\nimport Option from \'../Option\';\nimport querystring from \'querystring\';\nimport jsonp from \'fetch-jsonp\';\n\nclass SelectDemo1 extends Component {\n constructor() {\n super();\n this.state = {\n disabled: false,\n value: null,\n text: null,\n };\n }\n\n onChange = ({ text, value }) => {\n this.setState({\n value,\n text,\n });\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n setSelect = () => {\n this.setState({\n value: \'B\',\n });\n }\n\n render() {\n const { value, disabled } = this.state;\n\n return (\n <div className="markdown-block">\n <Button onClick={this.setDisabled}>{ disabled ? \'启用\' : \'禁用\'}</Button> &nbsp;&nbsp;\n <Button onClick={this.setSelect}>{ \'选中BB\' }</Button>\n <h3>受控</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} defaultValue="C" value={value} onChange={this.onChange} placeholder={"请选择"}>\n <Option value="A">AA</Option>\n <Option value="B">BB</Option>\n <Option value="C">CC</Option>\n <Option value="D">DD</Option>\n <Option value="E">EE</Option>\n <Option value="F">FF</Option>\n <Option value="G">GG</Option>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n\n <h3>非受控</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} defaultValue="C" onChange={this.onChange} placeholder={"请选择"}>\n <Option value="A">AA</Option>\n <Option value="B">BB</Option>\n <Option value="C">CC</Option>\n <Option value="D">DD</Option>\n <Option value="E">EE</Option>\n <Option value="F">FF</Option>\n <Option value="G">GG</Option>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n </div>\n );\n }\n}\n\n\nclass SelectDemo2 extends Component {\n constructor() {\n super();\n this.state = {\n disabled: false,\n value: null,\n text: null,\n };\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n setSelect = () => {\n this.setState({\n value: \'B\',\n });\n }\n\n onChange = ({ text, value }) => {\n this.setState({\n value,\n text,\n });\n }\n\n render() {\n const { value, disabled } = this.state;\n\n return (\n <div className="markdown-block">\n <h3>分组</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} value={value} onChange={this.onChange} placeholder={"请选择"}>\n <OptGroup label="分组1">\n <Option value="A">AA</Option>\n <Option value="B">BB</Option>\n </OptGroup>\n <OptGroup label="分组2">\n <Option value="C">CC</Option>\n <Option value="D">DD</Option>\n </OptGroup>\n <OptGroup label="分组3">\n <Option value="E">EE</Option>\n <Option value="F">FF</Option>\n <Option value="G">GG</Option>\n </OptGroup>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n\n <h3>复杂选项。</h3>\n <p />\n <Select style={{ width: 250 }} disabled={disabled} value={value} onChange={this.onChange} placeholder={"请选择"}>\n <Option value="A" text="李大力">\n <div>李大力</div><div>1354534324</div><div>杭州萧山区民和路</div>\n </Option>\n <Option value="B" text="李启">\n <div>李启</div><div>1356664324</div><div>杭州江干区</div>\n </Option>\n <Option value="C" text="李宇">\n <div>李宇</div><div>1377534324</div><div>杭州富阳</div>\n </Option>\n <Option value="D" text="李琦">\n <div>李琦</div><div>1354554324</div><div>杭州滨江区江</div>\n </Option>\n <Option value="E" text="李小燕">\n <div>李小燕</div><div>1387564324</div><div>上海黄埔区</div>\n </Option>\n </Select>\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n </div>\n );\n }\n}\n\n\nclass SelectDemo3 extends Component {\n constructor() {\n super();\n this.state = {\n disabled: false,\n value: null,\n text: null,\n searchData: [],\n };\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n setDefaultValue = () => {\n this.setState({\n value: \'CPU\',\n text: \'CPU\',\n });\n }\n\n onSearch = (value) => {\n const str = querystring.encode({\n code: \'utf-8\',\n q: value,\n });\n jsonp(`https://suggest.taobao.com/sug?${str}`)\n .then(response => response.json())\n .then((d) => {\n const result = d.result;\n const data = [];\n result.forEach((r) => {\n data.push({\n value: r[0],\n text: r[0],\n });\n });\n this.setState({\n searchData: data,\n });\n });\n }\n\n onChange = ({ value, text }) => {\n this.setState({\n value,\n text,\n });\n }\n\n render() {\n return (\n <div className="markdown-block">\n <Button onClick={this.setDisabled}>{ this.state.disabled ? \'启用\' : \'禁用\'}</Button> &nbsp;&nbsp;\n <Button onClick={this.setDefaultValue}>设值</Button>\n <h3>带搜索框。</h3>\n <p />\n <Select\n style={{ width: 250 }}\n disabled={this.state.disabled}\n value={this.state.value}\n text={this.state.text}\n type="combobox"\n onSearch={this.onSearch}\n onCancelChange={this.onCancelChange}\n onChange={this.onChange}\n placeholder="请输入查询条件"\n >\n {\n this.state.searchData.map(d => <Option key={d.value} value={d.value}>{d.text}</Option>)\n }\n </Select>\n\n <span>选中值:{`${this.state.value},${this.state.text}`}</span>\n </div>\n );\n }\n}\n\nclass SelectDemo4 extends Component {\n constructor() {\n super();\n this.state = {\n value: null,\n text: null,\n disabled: false,\n province: null,\n city: null,\n };\n }\n\n setDisabled = () => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n onChangeProvince = ({ value, text }) => {\n this.setState({\n province: value,\n provinceText: text,\n city: null,\n cityText: null,\n });\n }\n onChangeCity = ({ value, text }) => {\n this.setState({\n city: value,\n cityText: text,\n });\n }\n\n getCitysByProvince = (province) => {\n switch (province) {\n case \'1\':\n return [{ value: \'11\', text: \'杭州\' },\n { value: \'12\', text: \'湖州\' },\n { value: \'13\', text: \'绍兴\' }];\n case \'2\':\n return [{ value: \'21\', text: \'广州\' },\n { value: \'22\', text: \'东莞\' },\n { value: \'23\', text: \'中山\' }];\n case \'3\':\n return [{ value: \'31\', text: \'福州\' },\n { value: \'32\', text: \'泉州\' },\n { value: \'33\', text: \'厦门\' }];\n default:\n return [];\n }\n }\n\n render() {\n const citys = this.getCitysByProvince(this.state.province).map((v, i) => <Option value={v.value} key={i}>{v.text}</Option>);\n\n return (\n <div className="markdown-block">\n <Button onClick={this.setDisabled}>{ this.state.disabled ? \'启用\' : \'禁用\'}</Button>\n <h3>联动。</h3>\n <p />\n 省:\n <Select style={{ width: 250 }} disabled={this.state.disabled} value={this.state.province} onChange={this.onChangeProvince}>\n <Option value="1">浙江省</Option>\n <Option value="2">广东省</Option>\n <Option value="3">福建省</Option>\n </Select>\n 市:\n <Select style={{ width: 250 }} disabled={this.state.disabled} value={this.state.city} onChange={this.onChangeCity}>\n {citys}\n </Select>\n <span>选中值:{`${this.state.province}-${this.state.provinceText},${this.state.city}-${this.state.cityText}`}</span>\n </div>\n );\n }\n}\n\nexport default class SelectDemo extends Component {\n render() {\n return (\n <div className="markdown-block">\n <SelectDemo1 />\n <br /><br />\n <SelectDemo2 />\n <br /><br />\n <SelectDemo3 />\n <br /><br />\n <SelectDemo4 />\n </div>\n );\n }\n}\n'},kMPS:function(e,t,n){"use strict";function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,n,o){t=t||"&",n=n||"=";var s={};if("string"!=typeof e||0===e.length)return s;var i=/\+/g;e=e.split(t);var r=1e3;o&&"number"==typeof o.maxKeys&&(r=o.maxKeys);var c=e.length;r>0&&c>r&&(c=r);for(var m=0;m<c;++m){var u,p,d,h,y=e[m].replace(i,"%20"),g=y.indexOf(n);g>=0?(u=y.substr(0,g),p=y.substr(g+1)):(u=y,p=""),d=decodeURIComponent(u),h=decodeURIComponent(p),a(s,d)?l(s[d])?s[d].push(h):s[d]=[s[d],h]:s[d]=h}return s};var l=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},kimJ:function(e,t,n){var a=n("IV61");"string"==typeof a&&(a=[[e.i,a,""]]);var l={};l.transform=void 0;n("MTIv")(a,l);a.locals&&(e.exports=a.locals)},liFK:function(e,t){e.exports="import React, { Component } from 'react';\nimport Upload from '../Upload';\nimport Icon from '../../icon/Icon';\nimport Button from '../../button/Button';\nimport message from '../../message/index';\nimport styles from './index.css';\n\nclass UploadDemo1 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n };\n }\n render() {\n const props = {\n name: 'file',\n action: 'https://jsonplaceholder.typicode.com/posts/',\n headers: {\n authorization: 'authorization-text',\n },\n multiple: true,\n disabled: false,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' };\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url,\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n onChange(info) {\n if (info.file.status !== 'uploading') {\n // console.log(info.file, info.fileList);\n }\n if (info.file.status === 'done') {\n message.success(`${info.file.name} 文件上传成功.`);\n } else if (info.file.status === 'error') {\n message.error(`${info.file.name} 文件上传失败!`);\n }\n },\n };\n\n return (\n <div className=\"markdown-block\">\n <h3>1、经典款式,用户点击按钮弹出文件选择框。</h3>\n <Upload {...props}>\n <Button size=\"small\" type=\"secondary\" disabled={props.disabled}>\n <Icon size={12} name=\"upload\" /> 上传文件\n </Button>\n </Upload>\n </div>\n );\n }\n}\n\nclass UploadDemo2 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n };\n }\n render() {\n const props = {\n name: 'file',\n action: 'https://jsonplaceholder.typicode.com/posts/',\n headers: {\n authorization: 'authorization-text',\n },\n multiple: true,\n disabled: false,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' };\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url,\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n onChange(info) {\n if (info.file.status !== 'uploading') {\n // console.log(info.file, info.fileList);\n }\n if (info.file.status === 'done') {\n message.success(`${info.file.name} 文件上传成功.`);\n } else if (info.file.status === 'error') {\n message.error(`${info.file.name} 文件上传失败!`);\n }\n },\n defaultFileList: [{\n uid: 1,\n name: '图片1.png',\n status: 'done',\n url: 'https://www.ehuodi.com/module/index/img/index2/line2_bg.png',\n }, {\n uid: 2,\n name: '图片2.png',\n status: 'done',\n url: 'https://www.ehuodi.com/module/index/img/index2/line2_bg.png',\n }, {\n uid: 3,\n name: '图片3.png',\n status: 'error',\n response: '上传失败,图片太大',\n }],\n };\n\n\n return (\n <div className=\"markdown-block\">\n <h3>2、已上传文件的列表</h3>\n <p>使用 defaultFileList 设置已上传的内容。</p>\n <Upload {...props}>\n <Button size=\"small\" type=\"secondary\" disabled={props.disabled}>\n <Icon size={12} name=\"upload\" /> 上传文件\n </Button>\n </Upload>\n </div>\n );\n }\n}\n\nclass UploadDemo3 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n fileList: [{\n uid: -1,\n name: 'xxx.png',\n status: 'done',\n url: 'https://www.ehuodi.com/module/index/img/index2/line2_bg.png',\n }],\n };\n }\n\n render() {\n const I = this;\n const props = {\n action: '//jsonplaceholder.typicode.com/posts/',\n disabled: false,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' };\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url, // 上传成功的图片路径\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n onChange(info) {\n let fileList = info.fileList;\n\n // 最多只留1个文件,前面的将会被替换\n fileList = fileList.slice(-1);\n\n // 读取上传后的文件链接\n fileList = fileList.map((file) => {\n if (file.response) {\n file.url = file.response.url;\n }\n return file;\n });\n\n // // 过滤上传成功的文件\n // fileList = fileList.filter((file) => {\n // if (file.response) {\n // return file.status === 'done';\n // }\n // return true;\n // });\n\n I.setState({ fileList });\n },\n };\n return (\n <div className=\"markdown-block\">\n <h3>3、使用 fileList 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:</h3>\n <p>1) 上传列表数量的限制。</p>\n <p>2) 读取远程路径并显示链接。</p>\n <p>3) 按照服务器返回信息筛选成功上传的文件。</p>\n <Upload {...props} fileList={this.state.fileList}>\n <Button size=\"small\" type=\"secondary\" disabled={props.disabled}>\n <Icon size={12} name=\"upload\" /> 上传文件\n </Button>\n </Upload>\n </div>\n );\n }\n}\n\nclass UploadDemo4 extends Component {\n constructor(props) {\n super(props);\n this.state = {\n fileList: [{\n uid: -1,\n name: 'xxx.png',\n status: 'done',\n url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',\n }],\n };\n }\n // 点击查看源图时触发\n handlePreview = (file) => {\n window.open(file.url);\n }\n\n handleChange = (info) => {\n this.setState({ fileList: info.fileList });\n }\n beforeUpload(file) {\n const isJPG = file.type === 'image/png';\n if (!isJPG) {\n message.error('请上传.png文件!');\n }\n const isLt2M = file.size < 1024 * 1000;\n if (!isLt2M) {\n message.error('图片不能超过1000KB!');\n }\n return isJPG && isLt2M;\n }\n render() {\n const props = {\n action: '//jsonplaceholder.typicode.com/posts/',\n disabled: false,\n listType: 'picture-card',\n fileList: this.state.fileList,\n onPreview: this.handlePreview,\n onChange: this.handleChange,\n beforeUpload: this.beforeUpload,\n onResponse(response) {\n response = { result: 'success', msg: '上传成功!', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' }; // mock数据\n if (response.result === 'success') {\n return {\n success: true,\n message: '上传成功',\n url: response.url, // 上传成功的图片路径\n };\n }\n\n return {\n success: false,\n message: response.msg,\n };\n },\n };\n\n const uploadButton = (\n <div className={styles['upload-btn']}>\n <Icon name=\"plus\" size={25} />\n <div className={styles['upload-text']}>上传</div>\n </div>\n );\n return (\n <div className=\"markdown-block\">\n <h3>4、显示上传缩略图</h3>\n <p>点击上传图片,并使用 beforeUpload 限制用户上传的图片格式和大小。</p>\n <Upload {...props}>\n {this.state.fileList.length >= 3 ? null : uploadButton}\n </Upload>\n </div>\n );\n }\n}\n\nexport default class UploadDemo extends Component {\n render() {\n return (\n <div className=\"markdown-block\">\n <UploadDemo1 />\n <br /><br />\n <UploadDemo2 />\n <br /><br />\n <UploadDemo3 />\n <br /><br />\n <UploadDemo4 />\n </div>\n );\n }\n}\n"},"n+PT":function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Steps\n\nSteps Component.\n\n### Props\n#### Steps 整体步骤条\n|name|type|default|description|\n|---|---|:---:|:---:|\n|current|number|0|指定当前步骤,从 0 开始记数|\n|status|string|process|指定当前步骤的状态,可选 `wait` `process` `finish`|\n|direction|string|horizontal|指定步骤条方向。默认水平|\n|isFinishIcon|boolean|false|指定finish状态的显示方式是否使用Icon|\n\n#### Steps.Step 步骤条内的每一个步骤\n|name|type|default|description|\n|---|---|:---:|:---:|\n|status|string|wait|指定状态。当不配置该属性时,会使用 Steps 的 current 来自动指定状态。|\n|title|string or ReactNode|无|标题|\n|description|string or ReactNode|无|描述,可选|\n### Api"},nYGS:function(e,t){e.exports="---\nauthor:\n name: ryan.bian / lhf-nife\n homepage: https://github.com/macisi/\n email: [email protected]\n---\n\n## Modal\n\n模态对话框。\n\n### 何时使用\n\n需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 Modal 在当前页面正中打开一个浮层,承载相应的操作。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|title|string|--|对话框标题\n|closable|boolean|true|是否显示关闭按钮\n|width|number|520|对话框宽度\n|visible|boolean|false|对话框是否显示\n|footer|element|--|对话框底部按钮\n|onOk|func|--|确认按钮触发事件\n|onCancel|func|--|取消按钮触发事件\n|afterClose|func|--|对话框关闭后事件\n\n### Api\n#### Modal.method()\n\n- 包括:\n - Modal.info\n - Modal.success\n - Modal.error\n - Modal.warning\n- 以上均为一个函数,参数为object,具体属性如下:\n\n|name|type|default|description|\n|---|---|---|---|\n|title|string|info/success/eror/warning|对话框标题\n|content|string|--|对话框内容\n|closable|boolean|false|是否显示关闭按钮"},o3DI:function(e,t){e.exports="class Playground extends React.Component {\n render() {\n return <Button>Button</Button>;\n }\n}\n\nreturn <Playground />;"},pIU7:function(e,t,n){"use strict";function a(e,t){var n={};for(var a in e)t.indexOf(a)>=0||Object.prototype.hasOwnProperty.call(e,a)&&(n[a]=e[a]);return n}function l(e){return(e.ctrlKey||e.metaKey)&&e.keyCode===(e.shiftKey?R:E)}function o(e){return(e.ctrlKey||e.metaKey)&&e.keyCode===(e.shiftKey?E:R)}function s(e){var t=void 0,n=void 0,a=void 0,l=void 0;if(void 0!==e.selectionStart)t=e.selectionStart,n=e.selectionEnd;else try{e.focus(),l=(a=e.createTextRange()).duplicate(),a.moveToBookmark(document.selection.createRange().getBookmark()),l.setEndPoint("EndToStart",a),n=(t=l.text.length)+a.text.length}catch(e){}return{start:t,end:n}}function i(e,t){var n=void 0;try{void 0!==e.selectionStart?(e.focus(),e.setSelectionRange(t.start,t.end)):(e.focus(),(n=e.createTextRange()).collapse(!0),n.moveStart("character",t.start),n.moveEnd("character",t.end-t.start),n.select())}catch(e){}}var r,c,m=n("Jmof"),u=n.n(m),p=n("13mF"),d=n.n(p),h=n("KSGD"),y=n.n(h),g=n("HW6M"),f=n.n(g),v=n("PewI"),b=n.n(v),k=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},E=90,R=89,C=(c=r=class extends m.PureComponent{constructor(){var e;return e=super(...arguments),this.onChange=(e=>{var t=this.mask.getValue();if(e.target.value!==t){if(e.target.value.length<t.length){var n=t.length-e.target.value.length;this.mask.selection=s(this.input),this.mask.selection.end=this.mask.selection.start+n,this.mask.backspace()}var a=this.getDisplayValue();e.target.value=a,a&&i(this.input,this.mask.selection)}this.props.onChange&&this.props.onChange(e)}),this.onKeyPress=(e=>{e.metaKey||e.altKey||e.ctrlKey||"Enter"===e.key||(e.preventDefault(),this.mask.selection=s(this.input),this.mask.input(e.key||e.data)&&(e.target.value=this.mask.getValue(),i(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)))}),this.onKeyDown=(e=>{if(l(e))return e.preventDefault(),void(this.mask.undo()&&(e.target.value=this.getDisplayValue(),i(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)));if(o(e))return e.preventDefault(),void(this.mask.redo()&&(e.target.value=this.getDisplayValue(),i(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)));if("Backspace"===e.key&&(e.preventDefault(),this.mask.selection=s(this.input),this.mask.backspace())){var t=this.getDisplayValue();e.target.value=t,t&&i(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e)}}),this.onPaste=(e=>{e.preventDefault(),this.mask.selection=s(this.input),this.mask.paste(e.clipboardData.getData("Text"))&&(e.target.value=this.mask.getValue(),i(this.input,this.mask.selection),this.props.onChange&&this.props.onChange(e))}),this.getDisplayValue=(()=>{var e=this.mask.getValue();return e===this.mask.emptyValue?"":e}),this.getEventHandlers=(()=>({onChange:this.onChange,onKeyDown:this.onKeyDown,onPaste:this.onPaste,onKeyPress:this.onKeyPress})),e}componentWillMount(){var e={pattern:this.props.mask,value:this.props.value,formatCharacters:this.props.formatCharacters};this.props.placeholderChar&&(e.placeholderChar=this.props.placeholderChar),this.mask=new d.a(e)}render(){var e=this.mask.pattern.length,t=this.getDisplayValue(),n=this.getEventHandlers(),l=this.props,o=l.disabled,s=l.size,i=void 0===s?e:s,r=l.placeholder,c=void 0===r?this.mask.emptyValue:r,m=this.props,p=(m.placeholderChar,m.formatCharacters,a(m,["placeholderChar","formatCharacters"])),d=k({},p,n,{ref:e=>this.input=e,maxLength:e,value:t,size:i,placeholder:c,className:f()(b.a[`${o?"input__disabled":""}`],b.a[`input__${i}`])});return u.a.createElement("input",d)}},r.displayName="CardInput",r.defaultProps={size:"normal",disabled:!1,mask:"1111-1111-1111-1111",value:""},r.propTypes={size:y.a.oneOf(["normal","large","small"]),disabled:y.a.bool,mask:y.a.string.isRequired,formatCharacters:y.a.object,placeholderChar:y.a.string,onChange:y.a.func},c);t.a=C},qeLS:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return r});var a=n("Jmof"),l=(n.n(a),n("XFRO")),o=n("Pp2j"),s=n("mkCw"),i=n("pIU7"),r=class extends a.Component{constructor(e){super(e),this.onChangeCard=(e=>{var t=e.target.value;this.setState({value:t})}),this.state={value:"1234-1234-1234-1234"}}render(){var e=React.createElement(o.a,{size:12,name:"account"});return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement("p",null,"输入框"),React.createElement(l.a,{placeholder:"请输入",defaultValue:"12345465"}),React.createElement("h3",null,"图标"),React.createElement("p",null,"图标输入框"),React.createElement(l.a,{placeholder:"请输入",prefix:e}),React.createElement("h3",null,"大小"),React.createElement("p",null,"三种大小的数字输入框"),React.createElement(l.a,{size:"large",placeholder:"large size"}),React.createElement("p",null),React.createElement(l.a,{size:"normal",placeholder:"normal size"}),React.createElement("p",null),React.createElement(l.a,{size:"small",placeholder:"small size"}),React.createElement("h3",null,"禁用"),React.createElement("p",null,"输入框禁用"),React.createElement("p",null,React.createElement(l.a,{placeholder:"input disabled",defaultValue:"12345465",disabled:!0})),React.createElement("h3",null,"搜索框"),React.createElement("p",null,"带有搜索按钮的输入框"),React.createElement(s.a,{size:"large",placeholder:"input search text",style:{width:240}}),React.createElement("p",null),React.createElement(s.a,{placeholder:"input search text",style:{width:240}}),React.createElement("p",null),React.createElement(s.a,{size:"small",placeholder:"input search text",style:{width:240}}),React.createElement("h3",null,"文本域"),React.createElement("p",null,"用于多行输入"),React.createElement(l.a,{type:"textarea",placeholder:"请输入",autosize:!0,rows:1}),React.createElement(l.a,{type:"textarea",placeholder:"请输入",rows:6}),React.createElement("h3",null,"格式化"),React.createElement("p",null,"针对16或多位格式化输入"),React.createElement(i.a,{size:"large",mask:"1111-1111-1111-1111",placeholder:"1234-1234-1234-1234",value:this.state.value,onChange:this.onChangeCard}),React.createElement("p",null),React.createElement(i.a,{size:"normal",mask:"111111-111111-111111-111111",onChange:this.onChangeCard}))}}},tTp3:function(e,t){e.exports="---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n email: [email protected]\n---\n\n## Button\n\n按钮用于开始一个即时操作。\n\n### 何时使用\n\n标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|placeholder|String|'请选择'|选择框默认文字|\n|type|String|dropdown|单选(dropdown),搜索(combobox)|\n|style|Object|{width: 200}|{width: 100},目录支持宽度|\n|disabled|bool|false|是否禁用|\n|value|String|''|选中的值,与子控件Option的value对应|\n|onSearch|function(value)|null|当type为combobox有效,搜索文本框内容改变时回调,用于过滤数据|\n|onChange|function({value,text})|null|选中项改变时回调|\n|onCancelChange|function()|null|当type为combobox有效,搜索文本框内容取消改变时回调|\n\n### Api"},tsro:function(e,t){e.exports="import { Component } from 'react';\nimport Radio from '../index';\nimport Button from '../../button';\nimport Input from '../../input';\n\nconst RadioGroup = Radio.Group;\nconst RadioButton = Radio.Button;\n\nconst plainOptions = ['Apple', 'Pear', 'Orange'];\nconst options = [\n { label: 'Apple', value: 'Apple' },\n { label: 'Pear', value: 'Pear' },\n { label: 'Orange', value: 'Orange' },\n];\nconst optionsWithDisabled = [\n { label: 'Apple', value: 'Apple' },\n { label: 'Pear', value: 'Pear' },\n { label: 'Orange', value: 'Orange', disabled: false },\n];\n\nfunction onChange(e) {\n console.log(`radio checked:${e.target.value}`);\n}\nexport default class RadioDemo extends Component {\n constructor(props) {\n super(props);\n this.state = {\n disabled: false,\n checked: false,\n\n\n value: 1,\n value1: 'Apple',\n value2: 'Apple',\n value3: 'Apple',\n };\n }\n\n onChange=(e) => {\n console.log('radio checked', e.target.value);\n this.setState({\n value: e.target.value,\n });\n }\n\n onChange1=(e) => {\n this.setState({\n value1: e.target.value,\n });\n }\n\n onChange2=(e) => {\n this.setState({\n value2: e.target.value,\n });\n }\n\n onChange3=(e) => {\n this.setState({\n value3: e.target.value,\n });\n }\n\n handleChange=() => {\n this.setState({\n checked: !this.state.checked,\n });\n }\n\n handleToggle=() => {\n this.setState({\n disabled: !this.state.disabled,\n });\n }\n\n render() {\n const { checked, disabled, value1, value2, value3, value } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>通过配置 options 参数来渲染单选框</h3>\n <p><RadioGroup options={plainOptions} onChange={this.onChange1} value={value1} disabled={disabled} /></p>\n <p><RadioGroup options={options} onChange={this.onChange2} value={value2} disabled={disabled} /></p>\n <p><RadioGroup options={optionsWithDisabled} onChange={this.onChange3} value={value3} disabled={disabled} /></p>\n\n <h3>嵌套的RadioGroup</h3>\n <RadioGroup onChange={this.onChange} value={value} disabled={disabled}>\n <Radio value={1}>Option A</Radio>\n <Radio value={2}>Option B</Radio>\n <Radio value={3}>Option C</Radio>\n <Radio value={4}>\n More...\n {value == 4 ? <Input style={{ width: 100, marginLeft: 10 }} /> : null}\n </Radio>\n </RadioGroup>\n\n <h3>按钮样式的单选组合</h3>\n <RadioGroup onChange={onChange} defaultValue=\"a\" disabled={disabled}>\n <RadioButton value=\"a\">Hangzhou</RadioButton>\n <RadioButton value=\"b\">Shanghai</RadioButton>\n <RadioButton value=\"c\">Beijing</RadioButton>\n <RadioButton value=\"d\">Chengdu</RadioButton>\n </RadioGroup>\n\n <h3>非受控方式</h3>\n <p><Radio defaultChecked name={'my-radio'} disabled={disabled}>&nbsp;默认选中</Radio></p>\n <p>\n <Radio name={'my-radio'} disabled={disabled}>&nbsp;默认</Radio>\n </p>\n <h3>受控方式</h3>\n <p>\n <Radio checked={checked} onChange={this.handleChange} disabled={disabled}>&nbsp;{checked ? '选中' : '未选中'}</Radio></p>\n <p>\n <Radio checked={checked} onChange={this.handleChange} disabled={disabled}>&nbsp;{checked ? '选中' : '未选中'}</Radio>\n </p>\n <Button onClick={this.handleToggle}>{disabled ? '启用' : '禁用'}</Button>&nbsp;\n <Button onClick={this.handleChange}>{checked ? '取消选中' : '选中'}</Button>\n </div>\n );\n }\n}\n"},vMWu:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Radio\n\nRadio Component.\n\n### Props\n#### Radio\n|name|type|default|description|\n|---|---|---|---|\n|checked|boolean|false|指定当前是否选中|\n|defaultChecked|boolean|false|初始是否选中|\n|value|any|无|根据 value 进行比较,判断是否选中|\n\n#### RadioGroup \n|name|type|default|description|\n|---|---|:---:|:---:|\n|onChange|Function|-|选项变化时的回调函数|\n|value|any|-|用于设置当前选中的值|\n|defaultValue|any|-|默认选中的值|\n|options|string[] or Array|-|以配置形式设置子元素|\n### Api"},"w+gr":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return s});var a=n("Jmof"),l=(n.n(a),n("gPfh")),o=n("lkey"),s=class extends a.Component{constructor(e){super(e),this.openModal=this.openModal.bind(this),this.state={visible:!1}}openModal(){this.setState({visible:!0})}closeModal(){this.setState({visible:!1})}render(){var e={title:"标题",visible:this.state.visible,onOk:()=>{this.closeModal(),console.log("onOK")},onCancel:()=>{this.closeModal(),console.log("onCancel")},afterClose(){console.log("afterClose")}};return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本"),React.createElement(o.a,{type:"secondary",onClick:this.openModal},"open modal"),React.createElement(l.a,e,React.createElement("p",null,"这是一段信息。")),React.createElement("h3",null,"信息提示"),React.createElement("p",null,"各种类型的信息提示,只提供一个按钮用于关闭。"),React.createElement(o.a,{type:"secondary",onClick:()=>{l.a.info({content:"这是提示信息",closable:!0})}},"info")," ",React.createElement(o.a,{type:"secondary",onClick:()=>{l.a.success({content:"这是成功消息"})}},"success")," ",React.createElement(o.a,{type:"secondary",onClick:()=>{l.a.error({content:"这是错误提示"})}},"error")," ",React.createElement(o.a,{type:"secondary",onClick:()=>{l.a.warning({content:"这是警告信息"})}},"warning"))}}},wVe3:function(e,t){e.exports='---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n email: [email protected]\n---\n\n## Upload\n\nUpload Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|name|String|file|发到后台的文件参数名|\n|defaultFileList|object[]|[]|默认已经上传的文件列表|\n|action|String|\'\'|必选参数, 上传的地址|\n|data|object|function(file)|上传所需参数或返回上传参数的方法|\n|headers|object|null|设置上传的请求头部,IE10 以上有效|\n|showUploadList|bool or { showPreviewIcon?: boolean, showRemoveIcon?: boolean }|true|是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIcon|\n|multiple|bool|false|是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。|\n|accept|String|\'\'|接受上传的文件类型|\n|beforeUpload|(file, fileList) => boolean 或 Promise|null|上传文件之前的钩子,参数为上传的文件,若返回 false 或者 Promise 则停止上传。注意:该方法不支持老 IE。|\n|customRequest|Function|null|通过覆盖默认的上传行为,可以自定义自己的上传实现|\n|onChange|Function|null|上传文件改变时的状态,详见 onChange|\n|listType|String|\'text\'|上传列表的内建样式,支持两种基本样式 text or picture-card|\n|onPreview|Function(file)|null|点击文件链接或预览图标时的回调|\n|onRemove|Function(file): boolean 或 Promise|null|点击移除文件时的回调,返回值为 false 时不移除。支持返回一个 Promise 对象,Promise 对象 resolve(false) 或 reject 时不移除。|\n|disabled|bool|false|是否禁用|\n|withCredentials|bool|false|上传请求时是否携带 cookie|\n|onResponse|Function(response)|默认根据下面结构处理:{"result":"success","msg":"上传成功", url:"http://abc.jpg"}|根据服务端返回的内容,判断是否上传成功|\n\n\n\n### Api'},whSr:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/october-yan/\n---\n\n## InputNumber\n\n通过鼠标或键盘,输入范围内的数值\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|min|number||最小值|\n|max|number||最大值|\n|value|number||当前值|\n|step|number,string|1|每次改变步数,可以为小数|\n|defaultValue|number||初始值|\n|onChange|Function(value)||变化回调|\n|disabled|boolean|false|禁用|\n|formatter|function(value)||指定输入框展示值的格式|\n|parser|function( string): number||指定从 formatter 里转换回数字的方式,和 formatter 搭配使用|\n|style|CSSProperties||||\n\n### Api"},xaZU:function(e,t,n){"use strict";function a(e,t){if(e.map)return e.map(t);for(var n=[],a=0;a<e.length;a++)n.push(t(e[a],a));return n}var l=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?a(s(e),function(s){var i=encodeURIComponent(l(s))+n;return o(e[s])?a(e[s],function(e){return i+encodeURIComponent(l(e))}).join(t):i+encodeURIComponent(l(e[s]))}).join(t):i?encodeURIComponent(l(i))+n+encodeURIComponent(l(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},s=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},xiJQ:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return o});var a=n("Jmof"),l=(n.n(a),n("WG9z")),o=class extends a.Component{render(){return React.createElement("div",{className:"markdown-block"},React.createElement("h3",null,"基本面包屑"),React.createElement("p",null,React.createElement(l.a,null,React.createElement(l.a.Item,null,"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb"))),React.createElement(l.a,{separator:">"},React.createElement(l.a.Item,null,"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb")),React.createElement("h3",null,"带返回的面包屑"),React.createElement("p",null,React.createElement(l.a,{hasBackIcon:!0},React.createElement(l.a.Item,{href:"/"},"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb"))),React.createElement(l.a,{hasBackIcon:!0,separator:">"},React.createElement(l.a.Item,{href:"/"},"home"),React.createElement(l.a.Item,{href:"/component/button"},"Button"),React.createElement(l.a.Item,{href:"/component/steps"},"Steps"),React.createElement(l.a.Item,null,"bbb")))}}},"y/Xd":function(e,t){e.exports="---\nauthor:\n name: heifade\n homepage: https://github.com/heifade/\n---\n\n## Progress\n\nProgress Component.\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n|status|string|normal|`normal` `exception` `pause` or `success`|\n|percent|number|0|进度百分比|\n|showInfo|true|boolean|是否显示进度数值或状态图标|\n|size|string|normal|进度条尺寸,`normal` or `mini`|\n\n### Api"},yHpG:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("9q7S")),o=n("2tft"),s=n("lkey"),i=n("YSWR"),r=o.a.Option,c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={timeFunction:"ease",status:!1,motion:"fade"},e}render(){var e=Object.keys(i.a);return React.createElement("div",null,React.createElement("h3",null,"TIME FUNCTION"),React.createElement(o.a,{value:this.state.timeFunction,onChange:e=>{var t=e.value;this.setState({timeFunction:t})}},e.map(e=>React.createElement(r,{key:e,value:e},e))),React.createElement("h3",null,"MOTIONS"),React.createElement(o.a,{value:this.state.motion,onChange:e=>{var t=e.value;this.setState({motion:t})}},i.b.map(e=>React.createElement(r,{key:e,value:e},e))),React.createElement(s.a,{onClick:()=>{this.setState({status:!this.state.status})}},"toggle"),React.createElement("div",null,React.createElement(l.a,{in:this.state.status,timingFunction:this.state.timeFunction,motion:this.state.motion,style:{marginTop:20,display:"inline-block"}},React.createElement("div",{style:{width:100,height:100,border:"1px solid var(--brand-primary)"}}))))}}},yL0p:function(e,t){e.exports="---\nauthor:\n name: grootfish\n homepage: https://github.com/grootfish/\n email: [email protected]\n---\n\n## Breadcrumb\n\nBreadcrumb Component.\n\n### Props\n|name|type|default|description|\n|---|---|:---:|---|\n|prefixCls|String|'breadcrumb'|预先定义的样式前缀|\n|separator|String|'/'|面包屑的分隔符|\n|hasBackIcon|Boolean|false|是否显示回退按钮|\n### Api\n"},yPNB:function(e,t){e.exports="import Pagination from '../Pagination';\nimport { Component } from 'react';\n\nexport default class PaginationDemo extends Component {\n state = {\n current: 3,\n };\n render() {\n const { current } = this.state;\n return (\n <div className=\"markdown-block\">\n <h3>基本</h3>\n <p>基础分页。</p>\n <Pagination current={current} total={0} />\n <Pagination current={current} total={50} />\n <h3>更多分页</h3>\n <Pagination\n defaultCurrent={1}\n total={500}\n showSizeChanger\n onSizeChange={(size, cur) => {\n console.log(`size: ${size} current: ${cur}`);\n }}\n />\n <h3>跳转</h3>\n <p>快速跳转到某一页。</p>\n <Pagination showTotal total={500000} showQuickJumper />\n <h3>迷你</h3>\n <p>用于弹窗等页面展示区域狭小的场景。</p>\n <h3>受控方式</h3>\n <p><Pagination\n current={current}\n total={50}\n onChange={(c) => {\n this.setState({\n current: c,\n });\n }}\n /></p>\n <Pagination total={100} showQuickJumper showSizeChanger size=\"small\" />\n <h3>非受控方式</h3>\n <Pagination defaultCurrent={1} total={50} />\n </div>\n );\n }\n}\n"},yniO:function(e,t){e.exports="---\nauthor:\n name: yan\n homepage: https://github.com/october-yan/\n email: [email protected]\n---\n\n## Table\n\n展示行列数据。\n\n### Props\n|name|type|default|description|\n|---|---|---|---|\n| bordered | boolean | false | 是否展示外边框和列边框 |\n| width | number | - | 表格的宽度 |\n| height | number | - | 表格的高度(除去表头) |\n| emptyText | string | 暂无数据 | 表格暂无数据 |\n\n### 列配置项(jsxcolumns)\n|name|type|default|description|\n|---|---|---|---|\n| title | string | - | 列头标题 |\n| dataIndex | string | - | 表格的数据中用于查看模式展示的字段 |\n| width | number | - | 列宽 |\n| fixed | string | - | 固定位置,固定在左侧还是右侧,包含‘left’,'right' |\n| render | function | - | 在查看模式下,用户定制渲染的方式,返回一个 jsx 格式|\n| sorter | Function\\boolean | - | 排序函数,本地排序使用一个函数(参考 Array.sort 的 compareFunction),需要服务端排序可设为 true|\n| sortOrder | boolean\\string | - | 排序的受控属性,外界可用此控制列的排序,可设置为 'ascend' 'descend' false|\n\n### 选择功能的配置(rowSelection)\n|name|type|default|description|\n|---|---|---|---|\n| selectedRowKeys | string[] | [] | 指定选中项的 key 数组,需要和 onChange 进行配合 |\n| onSelectChange | Function(selectedRowKeys) | [] | 用户手动选择/取消选择某列的回调 |\n| selections | 'all-data' | - | 配置头部全选 |\n\n\n### Api"},zACC:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"default",function(){return c});var a=n("Jmof"),l=(n.n(a),n("7l3d")),o=(n("JCOr"),n("hFTO")),s=n("kbwb"),i=(n("oiih"),n("Hlpk")),r=n.n(i),c=class extends a.Component{constructor(){var e;return e=super(...arguments),this.state={visible:!1},this.handleOkClickTrigger=(()=>{this.setState({visible:!1})}),e}render(){var e=React.createElement("div",null,React.createElement("p",null,"top"),React.createElement("p",null,"这是一个气泡确认框")),t=React.createElement("div",null,React.createElement(o.a,{size:15,name:"warning",color:"#f9d900"}),React.createElement("span",null,"这是一个气泡确认框,确定要这样做吗?"));return React.createElement("div",null,React.createElement("div",{className:r.a["top-tooltip"]},React.createElement("div",{className:r.a["top-tooltip-div"]},React.createElement(l.a,{content:t,placement:"topLeft",handleOkClickTrigger:this.handleOkClickTrigger},React.createElement(s.a,{type:"secondary"},"上左,有ok事件"))),React.createElement("div",{className:r.a["top-tooltip-div"]},React.createElement(l.a,{content:t,placement:"top",action:"click",handleOkClickTrigger:this.handleOkClickTrigger,confirmVisable:this.state.visible},React.createElement(s.a,{type:"secondary"},"点击"))),React.createElement("div",{className:r.a["top-tooltip-div"]},React.createElement(l.a,{content:e,placement:"topRight"},React.createElement(s.a,{type:"secondary"},"上右")))),React.createElement("div",{className:r.a["left-tooltip"]},React.createElement("div",{className:r.a["left-tooltip-div"]},React.createElement(l.a,{content:"leftTop",placement:"leftTop"},React.createElement(s.a,{type:"secondary"},"左上"))),React.createElement("div",{className:r.a["left-tooltip-div"]},React.createElement(l.a,{content:"left",placement:"left"},React.createElement(s.a,{type:"secondary"},"左"))),React.createElement("div",{className:r.a["left-tooltip-div"]},React.createElement(l.a,{content:"leftBottom",placement:"leftBottom"},React.createElement(s.a,{type:"secondary"},"左下")))),React.createElement("div",{className:r.a["right-tooltip"]},React.createElement("div",{className:r.a["right-tooltip-div"]},React.createElement(l.a,{content:"rightTop",placement:"rightTop"},React.createElement(s.a,{type:"secondary"},"右上"))),React.createElement("div",{className:r.a["right-tooltip-div"]},React.createElement(l.a,{content:"right",placement:"right"},React.createElement(s.a,{type:"secondary"},"右"))),React.createElement("div",{className:r.a["right-tooltip-div"]},React.createElement(l.a,{content:"rightBottom",placement:"rightBottom"},React.createElement(s.a,{type:"secondary"},"左下")))),React.createElement("div",{className:r.a["bottom-tooltip"]},React.createElement("div",{className:r.a["bottom-tooltip-div"]},React.createElement(l.a,{content:"bottomLeft",placement:"bottomLeft"},React.createElement(s.a,{type:"secondary"},"下左"))),React.createElement("div",{className:r.a["bottom-tooltip-div"]},React.createElement(l.a,{content:"bottom",placement:"bottom"},React.createElement(s.a,{type:"secondary"},"下"))),React.createElement("div",{className:r.a["bottom-tooltip-div"]},React.createElement(l.a,{content:"bottomRight",placement:"bottomRight"},React.createElement(s.a,{type:"secondary"},"下右")))))}}}}); //# sourceMappingURL=0.6d3799bc16004a89cfb9.js.map
src/components/CodeEditor/__tests__/CodeEditor.spec.js
thangngoc89/react-code-playground
import React from 'react' import $ from 'teaspoon' import CodeEditor from '../CodeEditor' import CodeMirror from 'react-codemirror' const render = props => $(<CodeEditor {...props} />).render() const shallowRender = props => $(<CodeEditor {...props} />).shallowRender() describe('(component) CodeEditor', () => { let $element, _props, _spy beforeEach(() => { _spy = sinon.spy() _props = { code: 'foo', onChange: _spy, options: { foo: 'bar' } } }) it('render a <CodeMirror> tag with options', () => { $element = shallowRender(_props) const $codeMirror = $element.single($.s`${CodeMirror}`) expect($codeMirror.props().value).to.eql('foo') expect($codeMirror.props().options).to.eql({ lineNumbers: true, mode: 'javascript', foo: 'bar' }) }) it('dispatch onChange event when content changed', () => { $element = shallowRender(_props) const $codeMirror = $element.single($.s`${CodeMirror}`) _spy.should.have.not.been.called $codeMirror.trigger('change') _spy.should.have.been.calledOnce }) })
react_ui/components/SubjectView/RecordPanel/PDSRecordGroup/index.js
chop-dbhi/biorepo-portal
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import FloatingActionButton from '@material-ui/core/Button'; import RaisedButton from '@material-ui/core/Button'; import Icon from '@material-ui/core/Icon'; import NewRecordLabelSelect from './NewRecordLabelSelect'; import * as SubjectActions from '../../../../actions/subject'; import * as RecordActions from '../../../../actions/record'; import * as PDSActions from '../../../../actions/pds'; import AddButton from '../../../addButton' class PDSRecordGroup extends React.Component { constructor(props) { super(props); this.handleViewRecordClick = this.handleViewRecordClick.bind(this); this.handleLinkRecordClick = this.handleLinkRecordClick.bind(this); this.handleEditRecordClick = this.handleEditRecordClick.bind(this); this.handleNewRecordClick = this.handleNewRecordClick.bind(this); } componentDidMount() { const { dispatch } = this.props; if (this.props.records.length === 0) { dispatch(PDSActions.fetchPDSLinks(this.props.pds.id)); } } componentWillUnmount() { // Make sure that record state returns to its initialState once this view unmounts const { dispatch } = this.props; dispatch(RecordActions.clearRecordState()); } handleRecordClick(record, pds) { const dispatch = this.props.dispatch; if (this.props.linkMode) { if (this.props.activeRecord.id === record.id) { dispatch(SubjectActions.setLinkMode()); return; } dispatch(RecordActions.setPendingLinkedRecord(record)); } else { dispatch(RecordActions.fetchRecordLinks(pds.id, this.props.subject.id, record.id)); dispatch(RecordActions.setActiveRecord(record)); dispatch(PDSActions.setActivePDS(pds)); } } handleViewRecordClick() { const url = `/dataentry/protocoldatasource/${this.props.pds.id}/subject/` + `${this.props.subject.id}/record/${this.props.activeRecord.id}/start/` + `?p=${this.props.protocol.activeProtocolId}`; window.location.href = url; } handleLinkRecordClick() { const { dispatch } = this.props; dispatch(SubjectActions.setLinkMode()); } handleEditRecordClick() { const { dispatch } = this.props; dispatch(RecordActions.setEditLabelMode()); } handleNewRecordClick(pds) { const { dispatch } = this.props; dispatch(PDSActions.setActivePDS(pds)); dispatch(RecordActions.setAddRecordMode(true)); } isLinked(record) { let linked = false; this.props.activeLinks.forEach((link) => { if (link.external_record.id === record.id) { linked = true; } }, this); return linked; } Icons(props) { const { classes } = props; } renderRecords(recordNodes) { return ( recordNodes ? <table className="table"> <thead> <tr><th>Record ID</th><th>Record</th><th>Created</th><th>Modified</th></tr> </thead> <tbody> {recordNodes} </tbody> </table> : <div>No Records</div> ); } render() { const pds = this.props.pds; const records = this.props.subject.external_records.filter((record) => { if (pds.id === record.pds) { return record; } return null; }); let recordNodes = null; const activeLinks = this.props.activeLinks; if (records.length !== 0) { recordNodes = records.map((record, i) => { let linkIcon = null; // TODO: Factor out these record lines into their own components. if (this.props.activeRecord != null && (this.props.activeRecord.id === record.id)) { return ( <tr key={i} onClick={() => this.handleRecordClick(record, this.props.pds)} className="ex-rec-style" > <td>{record.id}</td> <td>{record.label_desc}</td> <td>{record.created}</td> <td>{record.modified}</td> <td className="row-action" onClick={this.handleEditRecordClick}>Label</td> <td className="row-action" onClick={this.handleLinkRecordClick}>Link</td> <td className="row-action" onClick={this.handleViewRecordClick}>View</td> </tr> ); } if (activeLinks != null) { if (this.isLinked(record)) { linkIcon = <i className="ti-link"></i>; } } return ( <tr key={i} onClick={() => this.handleRecordClick(record, this.props.pds)} className="ExternalRecord" > <td>{record.id}</td> <td>{linkIcon} {record.label_desc}</td> <td>{record.created}</td> <td>{record.modified}</td> </tr>); }, this); } const addButtonStyle = { marginLeft: '10px', marginTop: '10px', float: 'right', }; return ( <div> <NewRecordLabelSelect pds={this.props.pds} /> <h5 className="category">{this.props.pds.display_label} {this.props.pds.authorized ? <div className="font-icon-wrapper" onClick={() => this.handleNewRecordClick(this.props.pds)}> <AddButton/> </div> : <div/> } </h5> <div className="PDSRecords"> {this.props.pds.authorized ? this.renderRecords(recordNodes) : <div> Not authorized for this Protocol Data Source </div> } </div> </div> ); } } PDSRecordGroup.contextTypes = { history: PropTypes.object, }; PDSRecordGroup.propTypes = { dispatch: PropTypes.func, protocol: PropTypes.object, pds: PropTypes.object, record: PropTypes.object, records: PropTypes.array, subject: PropTypes.object, activeRecord: PropTypes.object, activeLinks: PropTypes.array, linkMode: PropTypes.bool, selectedLabel: PropTypes.number, }; function mapStateToProps(state) { return { protocol: { items: state.protocol.items, activeProtocolId: state.protocol.activeProtocolId, }, record: { isFetching: state.record.isFetching, }, subject: state.subject.activeSubject, activeRecord: state.record.activeRecord, activeLinks: state.record.activeLinks, linkMode: state.subject.linkMode, selectedLabel: state.record.selectedLabel, }; } export default connect(mapStateToProps)(PDSRecordGroup);
src/component/post-list-container/index.js
arn1313/kritter-frontend
import React from 'react'; import * as utils from '../../lib/utils'; import PostItem from '../post-item'; import { postFetchAllRequest } from '../../action/post-actions.js'; import { connect } from 'react-redux'; class PostList extends React.Component { constructor(props) { super(props); this.state = { sortedArray: this.props.post, }; } render() { let sorted = this.props.post.sort(function (a, b) { return b.exactTime - a.exactTime; }); console.log('====>THIS IS SORTED', this.props.post); return ( <div> {utils.renderIf(this.props.post, sorted.map(post => <div key={post._id}>{ <PostItem key={post._id} post={post} /> }<br /></div> ))} </div> ); } } //testing let mapStateToProps = state => ({ auth: state.auth, user: state.user, post: state.post, }); let mapDispatchToProps = dispatch => ({ postFetch: () => dispatch(postFetchAllRequest()), }); export default connect(mapStateToProps, mapDispatchToProps)(PostList);
src/index.js
Hurtak/finances
import React from 'react' import ReactDOM from 'react-dom' import App from './App.js' import './index.css' ReactDOM.render(<App />, document.getElementById('root'))
src/routes/error/index.js
shayan786/gexercise
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import App from '../../components/App'; import ErrorPage from './ErrorPage'; export default { path: '/error', action({ render, context, error }) { return render( <App context={context} error={error}> <ErrorPage error={error} /> </App>, error.status || 500 ); }, };
source/components/main-navigation.js
Aokibi/Regents-Navigation
import React from 'react' import MenuBar from './menu-bar' import NavigationArea from './navigation-area' import MainMenuButton from './main-menu-button' import HelpButton from './help-button' import BackButton from './back-button' /* Screen for displaying the 3D model and/or the 2D floor map*/ class MainNavigation extends React.Component { render() { return ( <div> <MenuBar/> <NavigationArea/> <div> <BackButton link_to='/createnewnavigation'/> <MainMenuButton/> <HelpButton link_to='/mainnavigationhelp'/> </div> </div> ) } } export default MainNavigation