code
stringlengths
2
1.05M
/*! * ui-grid - v4.10.1 - 2021-05-28 * Copyright (c) 2021 ; License: MIT */ (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 object * @name isFocused * @propertyOf ui.grid.selection.api:GridRow * @description Focused state of row. Should be readonly. Make any changes to focused state using setFocused(). * <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 {Boolean} selected value to set */ $delegate.prototype.setSelected = function (selected) { if (selected !== this.isSelected) { this.isSelected = selected; this.grid.selection.selectedCount += selected ? 1 : -1; } }; /** * @ngdoc function * @name setFocused * @methodOf ui.grid.selection.api:GridRow * @description Sets the isFocused property * Changes to isFocused state should only be made via this function * @param {Boolean} val value to set */ $delegate.prototype.setFocused = function(val) { if (val !== this.isFocused) { this.grid.selection.focusedRow && (this.grid.selection.focusedRow.isFocused = false); this.grid.selection.focusedRow = val ? this : null; this.isFocused = val; } }; return $delegate; }]); }]); /** * @ngdoc service * @name ui.grid.selection.service:uiGridSelectionService * * @description Services for selection features */ module.service('uiGridSelectionService', function () { 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 = { lastSelectedRow: null, /** * @ngdoc object * @name focusedRow * @propertyOf ui.grid.selection.grid:selection * @description Focused row. */ focusedRow: null, 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 rowFocusChanged * @eventOf ui.grid.selection.api:PublicApi * @description is raised after the row.isFocused state is changed * @param {object} scope the scope associated with the grid * @param {GridRow} row the row that was focused/unfocused * @param {Event} evt object if raised from an event */ rowFocusChanged: function (scope, row, evt) {}, /** * @ngdoc event * @name rowSelectionChanged * @eventOf ui.grid.selection.api:PublicApi * @description is raised after the row.isSelected state is changed * @param {object} scope the scope associated with the grid * @param {GridRow} row the row that was selected/deselected * @param {Event} evt 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 {object} scope the scope associated with the grid * @param {array} rows the rows that were selected/deselected * @param {Event} evt 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} evt 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} evt 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} rowNum index within the rowsVisible array * @param {Event} evt 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} evt 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 unSelectRowByVisibleIndex * @methodOf ui.grid.selection.api:PublicApi * @description Unselect the specified row by visible index (i.e. if you * specify row 0 you'll get the first visible row unselected). 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} rowNum index within the rowsVisible array * @param {Event} evt object if raised from an event */ unSelectRowByVisibleIndex: 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 selectAllRows * @methodOf ui.grid.selection.api:PublicApi * @description Selects all rows. Does nothing if multiSelect = false * @param {Event} evt object if raised from an event */ selectAllRows: function (evt) { if (grid.options.multiSelect !== false) { var changedRows = []; grid.rows.forEach(function (row) { if (!row.isSelected && row.enableSelection !== false && grid.options.isRowSelectable(row) !== false) { row.setSelected(true); service.decideRaiseSelectionEvent(grid, row, changedRows, evt); } }); grid.selection.selectAll = true; service.decideRaiseSelectionBatchEvent(grid, changedRows, evt); } }, /** * @ngdoc function * @name selectAllVisibleRows * @methodOf ui.grid.selection.api:PublicApi * @description Selects all visible rows. Does nothing if multiSelect = false * @param {Event} evt object if raised from an event */ selectAllVisibleRows: function (evt) { if (grid.options.multiSelect !== false) { var changedRows = []; grid.rows.forEach(function(row) { if (row.visible) { if (!row.isSelected && row.enableSelection !== false && grid.options.isRowSelectable(row) !== false) { row.setSelected(true); service.decideRaiseSelectionEvent(grid, row, changedRows, evt); } } else if (row.isSelected) { row.setSelected(false); service.decideRaiseSelectionEvent(grid, row, changedRows, evt); } }); grid.selection.selectAll = true; service.decideRaiseSelectionBatchEvent(grid, changedRows, evt); } }, /** * @ngdoc function * @name clearSelectedRows * @methodOf ui.grid.selection.api:PublicApi * @description Unselects all rows * @param {Event} evt 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; }).filter(function (entity) { return entity.hasOwnProperty('$$hashKey') || !angular.isObject(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 getSelectedCount * @methodOf ui.grid.selection.api:PublicApi * @description returns the number of rows selected */ getSelectedCount: function () { return grid.selection.selectedCount; }, /** * @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 true. */ if (typeof (gridOptions.enableFullRowSelection) === 'undefined') { gridOptions.enableFullRowSelection = !gridOptions.enableRowHeaderSelection; } /** * @ngdoc object * @name enableFocusRowOnRowHeaderClick * @propertyOf ui.grid.selection.api:GridOptions * @description Enable focuse row by clicking on the row header. Defaults to * true if `enableRowHeaderSelection` is true, otherwise defaults to false. */ gridOptions.enableFocusRowOnRowHeaderClick = (gridOptions.enableFocusRowOnRowHeaderClick !== false) || !gridOptions.enableRowHeaderSelection; /** * @ngdoc object * @name enableSelectRowOnFocus * @propertyOf ui.grid.selection.api:GridOptions * @description Enable focuse row by clicking on the row anywhere. Defaults true. */ gridOptions.enableSelectRowOnFocus = (gridOptions.enableSelectRowOnFocus !== false); /** * @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} evt 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) { if ( row.enableSelection === false ) { return; } var selected = row.isSelected, selectedRows; if (!multiSelect) { if (!selected) { service.clearSelectedRows(grid, evt); } else { selectedRows = service.getSelectedRows(grid); if (selectedRows.length > 1) { selected = false; // Enable reselect of the row service.clearSelectedRows(grid, evt); } } } // only select row in this case if (!(selected && noUnselect)) { row.setSelected(!selected); if (row.isSelected === true) { grid.selection.lastSelectedRow = row; } selectedRows = service.getSelectedRows(grid); grid.selection.selectAll = grid.rows.length === selectedRows.length; 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} row clicked row * @param {Event} evt 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} evt object if raised from an event */ clearSelectedRows: function (grid, evt) { var changedRows = []; service.getSelectedRows(grid).forEach(function (row) { if (row.isSelected && row.enableSelection !== false && grid.options.isRowSelectable(row) !== false) { row.setSelected(false); service.decideRaiseSelectionEvent(grid, row, changedRows, evt); } }); grid.selection.selectAll = false; grid.selection.selectedCount = 0; service.decideRaiseSelectionBatchEvent(grid, changedRows, evt); }, /** * @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} evt 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} evt 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', 'uiGridConstants', function (uiGridSelectionConstants, uiGridSelectionService, 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, 0); } 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; $scope.selectButtonKeyDown = selectButtonKeyDown; // 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 selectButtonKeyDown(row, evt) { if (evt.keyCode === 32 || evt.keyCode === 13) { evt.preventDefault(); selectButtonClick(row, evt); } } 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 if (row.groupHeader) { uiGridSelectionService.toggleRowSelection(self, row, evt, self.options.multiSelect, self.options.noUnselect); for (var i = 0; i < row.treeNode.children.length; i++) { uiGridSelectionService.toggleRowSelection(self, row.treeNode.children[i].row, evt, self.options.multiSelect, self.options.noUnselect); } } else { uiGridSelectionService.toggleRowSelection(self, row, evt, (self.options.multiSelect && !self.options.modifierKeysToMultiSelect), self.options.noUnselect); } self.options.enableFocusRowOnRowHeaderClick && row.setFocused(!row.isFocused) && self.api.selection.raise.rowFocusChanged(row, evt); } function selectButtonMouseDown(evt) { if (evt.ctrlKey || evt.shiftKey) { evt.target.onselectstart = function () { return false; }; window.setTimeout(function () { evt.target.onselectstart = null; }, 0); } } $scope.$on('$destroy', function unbindEvents() { $elm.off(); }); } }; }]); module.directive('uiGridSelectionSelectAllButtons', ['$templateCache', 'uiGridSelectionService', function ($templateCache, uiGridSelectionService) { return { replace: true, restrict: 'E', template: $templateCache.get('ui-grid/selectionSelectAllButtons'), scope: false, link: function ($scope) { var self = $scope.col.grid; $scope.headerButtonKeyDown = function (evt) { if (evt.keyCode === 32 || evt.keyCode === 13) { evt.preventDefault(); $scope.headerButtonClick(evt); } }; $scope.headerButtonClick = function (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', function () { return { priority: -200, // run after default directive scope: false, compile: function ($elm) { var rowRepeatDiv = angular.element($elm[0].querySelector('.ui-grid-canvas:not(.ui-grid-empty-base-layer-container)').children[0]), newNgClass = "'ui-grid-row-selected': row.isSelected, 'ui-grid-row-focused': row.isFocused}", existingNgClass = rowRepeatDiv.attr('ng-class'); if (existingNgClass) { newNgClass = existingNgClass.slice(0, -1) + ',' + newNgClass; } else { newNgClass = '{' + newNgClass; } 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', ['uiGridConstants', 'uiGridSelectionService', function (uiGridConstants, uiGridSelectionService) { return { priority: -200, // run after default uiGridCell directive restrict: 'A', require: '?^uiGrid', scope: false, link: function ($scope, $elm, $attrs, uiGridCtrl) { var touchStartTime = 0, touchStartPos = {}, touchTimeout = 300, touchPosDiff = 100; // 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 === uiGridConstants.keymap.SPACE && $scope.col.colDef.name === 'selectionRowHeaderCol') { evt.preventDefault(); 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 you click on expandable icon doesn't trigger selection if (evt.target.className === "ui-grid-icon-minus-squared" || evt.target.className === "ui-grid-icon-plus-squared") { return; } // 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 if ($scope.grid.options.enableSelectRowOnFocus) { uiGridSelectionService.toggleRowSelection($scope.grid, $scope.row, evt, ($scope.grid.options.multiSelect && !$scope.grid.options.modifierKeysToMultiSelect), $scope.grid.options.noUnselect); } $scope.row.setFocused(!$scope.row.isFocused); $scope.grid.api.selection.raise.rowFocusChanged($scope.row, evt); $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 window.setTimeout(function () { $elm.on('touchend', touchEnd); }, touchTimeout); }; var touchStart = function (evt) { touchStartTime = (new Date()).getTime(); touchStartPos = evt.changedTouches[0]; // 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 touchEndPos = evt.changedTouches[0]; var touchTime = touchEndTime - touchStartTime; var touchXDiff = Math.abs(touchStartPos.clientX - touchEndPos.clientX) var touchYDiff = Math.abs(touchStartPos.clientY - touchEndPos.clientY) if (touchXDiff < touchPosDiff && touchYDiff < touchPosDiff) { 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 window.setTimeout(function () { $elm.on('click', selectCells); }, touchTimeout); }; function registerRowSelectionEvents() { if ($scope.grid.options.enableRowSelection && $scope.grid.options.enableFullRowSelection && $scope.col.colDef.name !== 'selectionRowHeaderCol') { $elm.addClass('ui-grid-disable-selection'); $elm.on('touchstart', touchStart); $elm.on('touchend', touchEnd); $elm.on('click', selectCells); $scope.registered = true; } } function unregisterRowSelectionEvents() { 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 dataChangeUnreg = $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) { unregisterRowSelectionEvents(); } }, [uiGridConstants.dataChange.OPTIONS]); $elm.on('$destroy', dataChangeUnreg); } }; }]); module.directive('uiGridGridFooter', ['$compile', 'gridUtil', function ($compile, gridUtil) { return { restrict: 'EA', replace: true, priority: -1000, require: '^uiGrid', scope: true, compile: function () { 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) { } }; } }; }]); })(); angular.module('ui.grid.selection').run(['$templateCache', function($templateCache) { 'use strict'; $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\" role=\"checkbox\" ng-model=\"grid.selection.selectAll\"></ui-grid-selection-select-all-buttons></div></div>" ); $templateCache.put('ui-grid/selectionRowHeader', "<div class=\"ui-grid-cell-contents ui-grid-disable-selection clickable\"><ui-grid-selection-row-header-buttons></ui-grid-selection-row-header-buttons></div>" ); $templateCache.put('ui-grid/selectionRowHeaderButtons', "<div class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok clickable\" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" tabindex=\"0\" ng-click=\"selectButtonClick(row, $event)\" ng-keydown=\"selectButtonKeyDown(row, $event)\" role=\"checkbox\" ng-model=\"row.isSelected\">&nbsp;</div>" ); $templateCache.put('ui-grid/selectionSelectAllButtons', "<div role=\"checkbox\" tabindex=\"0\" class=\"ui-grid-selection-row-header-buttons ui-grid-icon-ok\" ui-grid-one-bind-aria-label=\"'selection.selectAll' | t\" aria-checked=\"{{grid.selection.selectAll}}\" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-click=\"headerButtonClick($event)\" ng-keydown=\"headerButtonKeyDown($event)\"></div>" ); }]);
/*global define*/ /////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define({ "units": { "miles": "Milles", "kilometers": "Quilòmetres", "feet": "Peus", "meters": "Metres" }, "layerSetting": { "layerSettingTabTitle": "Configuració de cerca", "buttonSet": "Defineix", "selectLayersLabel": "Seleccioneu la capa", "selectLayersHintText": "Suggeriment: s'utilitza per seleccionar la capa del polígon i la seva capa de punts relacionada.", "selectPrecinctSymbolLabel": "Seleccioneu el símbol per ressaltar el polígon", "selectGraphicLocationSymbol": "Símbol d'adreça o ubicació", "graphicLocationSymbolHintText": "Suggeriment: símbol de l'adreça que s'ha cercat o la ubicació on s'ha fet clic", "precinctSymbolHintText": "Suggeriment: s'utilitza per mostrar el símbol del polígon seleccionat", "selectColorForPoint": "Trieu el color per marcar el punt", "selectColorForPointHintText": "Suggeriment: s'utilitza per mostrar el color de marcatge del punt seleccionat" }, "searchSourceSetting": { "searchSourceSettingTabTitle": "Configuració de l'origen de la cerca", "searchSourceSettingTitle": "Configuració de l'origen de la cerca", "searchSourceSettingTitleHintText": "Afegiu i configureu serveis de geocodificació o capes d'entitats com a orígens de cerca. Aquests orígens especificats determinen què es pot cercar al quadre de cerca.", "addSearchSourceLabel": "Afegeix un origen de cerca", "featureLayerLabel": "Capa d'entitats", "geocoderLabel": "Geocodificador", "nameTitle": "Nom", "generalSettingLabel": "Configuració general", "allPlaceholderLabel": "Text del marcador de posició per cercar-ho tot:", "allPlaceholderHintText": "Suggeriment: introduïu el text que es mostrarà com a marcador de posició mentre cerqueu totes les capes i el geocodificador", "generalSettingCheckboxLabel": "Mostra la finestra emergent de l'entitat o la ubicació trobada", "countryCode": "Codis de país o regió", "countryCodeEg": "per exemple, ", "countryCodeHint": "Si aquest valor es deixa en blanc, la cerca es farà en tots els països i regions", "questionMark": "?", "searchInCurrentMapExtent": "Cerca només a l'extensió de mapa actual", "zoomScale": "Escala de zoom", "locatorUrl": "URL del geocodificador", "locatorName": "Nom del geocodificador", "locatorExample": "Exemple", "locatorWarning": "Aquesta versió del servei de geocodificació no s'admet. El widget admet el servei de geocodificació 10.0 i versions posteriors.", "locatorTips": "Els suggeriments no estan disponibles perquè el servei de geocodificació no admet la funció de suggeriments.", "layerSource": "Origen de la capa", "setLayerSource": "Defineix l'origen de la capa", "setGeocoderURL": "Defineix la URL del geocodificador", "searchLayerTips": "Els suggeriments no estan disponibles perquè el servei d'entitats no admet la funció de paginació.", "placeholder": "Text del marcador de posició", "searchFields": "Camps de cerca", "displayField": "Camp que es mostra", "exactMatch": "Coincidència exacta", "maxSuggestions": "Màxim de suggeriments", "maxResults": "Màxim de resultats", "enableLocalSearch": "Habilita la cerca local", "minScale": "Escala mínima", "minScaleHint": "Si l'escala del mapa és més gran que aquesta escala, s'aplicarà la cerca local", "radius": "Radi", "radiusHint": "Permet especificar el radi d'una àrea al voltant del centre del mapa actual que s'utilitzarà per millorar la classificació dels candidats de geocodificació per tal que es retornin primer aquells més propers a la ubicació", "meters": "Metres", "setSearchFields": "Defineix els camps de cerca", "set": "Defineix", "fieldName": "Nom", "invalidUrlTip": "L'adreça URL ${URL} no és vàlida o no s'hi pot accedir.", "invalidSearchSources": "Configuració de l'origen de la cerca no vàlida" }, "layerSelector": { "selectPolygonLayerLabel": "Seleccioneu la capa de polígon", "selectPolygonLayerHintText": "Suggeriment: s'utilitza per seleccionar la capa de polígon.", "selectRelatedPointLayerLabel": "Seleccioneu la capa de punts relacionada amb la capa de polígon", "selectRelatedPointLayerHintText": "Suggeriment: s'utilitza per seleccionar la capa de punts relacionada amb la capa de polígon", "polygonLayerNotHavingRelatedLayer": "Seleccioneu una capa de polígon que tingui una capa de punts relacionada.", "errorInSelectingPolygonLayer": "Seleccioneu una capa de polígon que tingui una capa de punts relacionada.", "errorInSelectingRelatedLayer": "Seleccioneu una capa de punts relacionada amb la capa de polígon." }, "routeSetting": { "routeSettingTabTitle": "Configuració d'indicacions", "routeServiceUrl": "Servei d'assignació de rutes", "buttonSet": "Defineix", "routeServiceUrlHintText": "Suggeriment: feu clic a \"Defineix\" per examinar i seleccionar un servei d'assignació de rutes per a l'anàlisi de xarxa", "directionLengthUnit": "Unitats de longitud d'indicació", "unitsForRouteHintText": "Suggeriment: s'utilitza per visualitzar les unitats indicades per a la ruta", "selectRouteSymbol": "Seleccioneu el símbol per visualitzar la ruta", "routeSymbolHintText": "Suggeriment: s'utilitza per visualitzar el símbol de línia de la ruta", "routingDisabledMsg": "Per habilitar les indicacions, assegureu-vos que l'assignació de rutes estigui habilitada a l'element de l'ArcGIS Online.", "enableDirectionLabel": "Habilita les indicacions", "enableDirectionText": "Suggeriment: activeu aquesta opció per habilitar les indicacions al widget" }, "networkServiceChooser": { "arcgislabel": "Afegeix des de l'ArcGIS Online", "serviceURLabel": "Afegeix una URL de servei", "routeURL": "URL de la ruta", "validateRouteURL": "Valida", "exampleText": "Exemple", "hintRouteURL1": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/", "hintRouteURL2": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World", "invalidRouteServiceURL": "Especifiqueu un servei de rutes vàlid.", "rateLimitExceeded": "S'ha superat el límit de velocitat. Torneu a intentar-ho més tard.", "errorInvokingService": "El nom d'usuari o la contrasenya són incorrectes." }, "symbolPickerPreviewText": "Visualització prèvia:", "showToolToSelectLabel": "Botó Defineix la ubicació", "showToolToSelectHintText": "Suggeriment: proporciona un botó per definir la ubicació al mapa en lloc de definir sempre la ubicació quan es fa clic al mapa" });
/*! * jQuery JavaScript Library v2.1.1 -deprecated,-event-alias,-css/hiddenVisibleSelectors,-effects/animatedSelector * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-09-28T03:03Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.1 -deprecated,-event-alias,-css/hiddenVisibleSelectors,-effects/animatedSelector", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // 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 ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, 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: arr.sort, splice: arr.splice }; 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; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // 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 ( i === length ) { 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({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // 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, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, 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 || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } /* * Optional (non-Sizzle) selector module for custom builds. * * Note that this DOES NOT SUPPORT many documented jQuery * features in exchange for its smaller size: * * Attribute not equal selector * Positional selectors (:first; :eq(n); :odd; etc.) * Type selectors (:input; :checkbox; :button; etc.) * State-based selectors (:animated; :visible; :hidden; etc.) * :has(selector) * :not(complex selector) * custom selectors via Sizzle extensions * Leading combinators (e.g., $collection.find("> *")) * Reliable functionality on XML fragments * Requiring all parts of a selector to match elements under context * (e.g., $div.find("div > *") now matches children of $div) * Matching against non-elements * Reliable sorting of disconnected nodes * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) * * If any of these are unacceptable tradeoffs, either use Sizzle or * customize this stub for the project's specific needs. */ var docElem = window.document.documentElement, selector_hasDuplicate, matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector, selector_sortOrder = function( a, b ) { // Flag for duplicate removal if ( a === b ) { selector_hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 ) { // Choose the first element that is related to our document if ( a === document || jQuery.contains(document, a) ) { return -1; } if ( b === document || jQuery.contains(document, b) ) { return 1; } // Maintain original order return 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; }; jQuery.extend({ find: function( selector, context, results, seed ) { var elem, nodeType, i = 0; results = results || []; context = context || document; // Same basic safeguard as Sizzle if ( !selector || typeof selector !== "string" ) { return results; } // Early return if context is not an element or document if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( seed ) { while ( (elem = seed[i++]) ) { if ( jQuery.find.matchesSelector(elem, selector) ) { results.push( elem ); } } } else { jQuery.merge( results, context.querySelectorAll(selector) ); } return results; }, unique: function( results ) { var elem, duplicates = [], i = 0, j = 0; selector_hasDuplicate = false; results.sort( selector_sortOrder ); if ( selector_hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }, text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements return elem.textContent; } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, contains: function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) ); }, isXMLDoc: function( elem ) { return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML"; }, expr: { attrHandle: {}, match: { bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i, needsContext: /^[\x20\t\r\n\f]*[>+~]/ } } }); jQuery.extend( jQuery.find, { matches: function( expr, elements ) { return jQuery.find( expr, null, null, elements ); }, matchesSelector: function( elem, expr ) { return matches.call( elem, expr ); }, attr: function( elem, name ) { return elem.getAttribute( name ); } }); var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // 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 ) { // 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: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // 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.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // #11217 - WebKit loses check when the name is after the checked attribute // Support: Windows Web Apps (WWA) // `name` and `type` need .setAttribute for WWA input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = 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 !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // 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: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } 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; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // 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; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.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 ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // 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 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // 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 ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && 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) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === 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( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { 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 ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent 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( 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // 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 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, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, 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(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; 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.defaultPrevented === undefined && // Support: Android < 4.0 src.returnValue === false ? 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; }; // 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 = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // 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; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } 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 = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-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"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.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; }; var // 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 = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } 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; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } 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 = jQuery.css( elem, "boxSizing", false, styles ) === "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 = curCSS( elem, name, styles ); 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 && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": 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": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== 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"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } 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, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.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 ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // 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; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !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 default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, 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 ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } 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 ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion 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 ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, 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 ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // 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 ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // 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 * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": 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: { url: true, context: true } }, // 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 ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, 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 transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // 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 == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // 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 Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { 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( isSuccess ? "ajaxSuccess" : "ajaxError", [ 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"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); 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({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; 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 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.firstElementChild ) { elem = elem.firstElementChild; } 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(); } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // 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({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via 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. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; const propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ])), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), /** * Title content */ title: React.PropTypes.node, }; const defaultProps = { placement: 'right', }; class Popover extends React.Component { render() { const { placement, positionTop, positionLeft, arrowOffsetTop, arrowOffsetLeft, title, className, style, children, ...props } = this.props; const [bsProps, elementProps] = splitBsProps(props); const classes = { ...getClassSet(bsProps), [placement]: true, }; const outerStyle = { display: 'block', top: positionTop, left: positionLeft, ...style, }; const arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft, }; return ( <div {...elementProps} role="tooltip" className={classNames(className, classes)} style={outerStyle} > <div className="arrow" style={arrowStyle} /> {title && ( <h3 className={prefix(bsProps, 'title')}> {title} </h3> )} <div className={prefix(bsProps, 'content')}> {children} </div> </div> ); } } Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default bsClass('popover', Popover);
// BH adjusted to have only one sort method. // BH 4/7/2017 1:49:45 PM fixing "instanceof Comparable" // BH adding copyOf 7/12/2016 10:35:01 AM Clazz.load(["java.util.AbstractList","$.RandomAccess"],"java.util.Arrays",["java.lang.ArrayIndexOutOfBoundsException","$.IllegalArgumentException","$.NullPointerException"],function(){ c$=Clazz.declareType(java.util,"Arrays"); c$.sort=Clazz.overrideMethod(c$,"sort", function(a,c,d,e){ switch (arguments.length) { case 1: var aux=a.sort(function(o1,o2){ if(typeof o1=="string"||Clazz.instanceOf(o1, Comparable)){ return o1.compareTo(o2); } return o1-o2; }); for(var i=0;i<a.length;i++){ a[i]=aux[i]; } return; case 2: var aux=a.sort(function(o1,o2){ if(c!=null){ return c.compare(o1,o2); }else if(typeof o1=="string"||Clazz.instanceOf(o1, Comparable)){ return o1.compareTo(o2); } return o1-o2; }); for(var i=0;i<a.length;i++){ a[i]=aux[i]; } return; case 3: var fromIndex = c; var toIndex = d; this.rangeCheck(a.length,fromIndex,toIndex); var aux=new Array(); for(var i=fromIndex;i<toIndex;i++){ aux[i-fromIndex]=a[i]; } aux=aux.sort(function(o1,o2){ if(typeof o1=="string"||Clazz.instanceOf(o1, Comparable)){ return o1.compareTo(o2); } return o1-o2; }); for(var i=fromIndex;i<toIndex;i++){ a[i]=aux[i-fromIndex]; } return; case 4: var fromIndex = c; var toIndex = d; c = e; this.rangeCheck(a.length,fromIndex,toIndex); var aux=new Array(); for(var i=fromIndex;i<toIndex;i++){ aux[i-fromIndex]=a[i]; } aux=aux.sort(function(o1,o2){ if(c!=null){ return c.compare(o1,o2); }else if(typeof o1=="string"||Clazz.instanceOf(o1, Comparable)){ return o1.compareTo(o2); } return o1-o2; }); for(var i=fromIndex;i<toIndex;i++){ a[i]=aux[i-fromIndex]; } } }); c$.rangeCheck=Clazz.defineMethod(c$,"rangeCheck", ($fz=function(arrayLen,fromIndex,toIndex){ if(fromIndex>toIndex)throw new IllegalArgumentException("fromIndex("+fromIndex+") > toIndex("+toIndex+")"); if(fromIndex<0)throw new ArrayIndexOutOfBoundsException(fromIndex); if(toIndex>arrayLen)throw new ArrayIndexOutOfBoundsException(toIndex); },$fz.isPrivate=true,$fz),"~N,~N,~N"); c$.binarySearch=Clazz.defineMethod(c$,"binarySearch", function(a,key){ var low=0; var high=a.length-1; while(low<=high){ var mid=(low+high)>>1; var midVal=a[mid]; if(midVal<key)low=mid+1; else if(midVal>key)high=mid-1; else return mid; } return-(low+1); },"~A,~N"); c$.binarySearch=Clazz.defineMethod(c$,"binarySearch", function(a,key){ var low=0; var high=a.length-1; while(low<=high){ var mid=(low+high)>>1; var midVal=a[mid]; var cmp=(midVal).compareTo(key); if(cmp<0)low=mid+1; else if(cmp>0)high=mid-1; else return mid; } return-(low+1); },"~A,~O"); c$.binarySearch=Clazz.defineMethod(c$,"binarySearch", function(a,key,c){ if(c==null)return java.util.Arrays.binarySearch(a,key); var low=0; var high=a.length-1; while(low<=high){ var mid=(low+high)>>1; var midVal=a[mid]; var cmp=c.compare(midVal,key); if(cmp<0)low=mid+1; else if(cmp>0)high=mid-1; else return mid; } return-(low+1); },"~A,~O,java.util.Comparator"); c$.equals=Clazz.defineMethod(c$,"equals", function(a,a2){ if(a===a2)return true; if(a==null||a2==null)return false; var length=a.length; if(a2.length!=length)return false; for(var i=0;i<length;i++){ var o1=a[i]; var o2=a2[i]; { if(!(o1==null?o2==null:(o1.equals==null?o1==o2:o1.equals(o2))))return false; }} return true; },"~A,~A"); c$.fill=Clazz.overrideMethod(c$,"fill", function(a,fromIndex,toIndex,val){ if (arguments.length == 2) { val = fromIndex; fromIndex = 0; toIndex = a.length; } java.util.Arrays.rangeCheck(a.length,fromIndex,toIndex); for(var i=fromIndex;i<toIndex;i++)a[i]=val; }); c$.copyOf=Clazz.overrideMethod(c$,"copyOf", function(a,len){ var b = Clazz.newArray(len,null) for(var i=Math.min(a.length, len);--i >= 0;)b[i]=a[i]; return b; }); c$.asList=Clazz.defineMethod(c$,"asList", function(a){ return new java.util.Arrays.ArrayList(arguments.length == 1 && Clazz.getClassName(a) == "Array" ? a : arguments); // BH must be T... },"~A"); Clazz.pu$h(self.c$); c$=Clazz.decorateAsClass(function(){ this.a=null; Clazz.instantialize(this,arguments); },java.util.Arrays,"ArrayList",java.util.AbstractList,[java.util.RandomAccess,java.io.Serializable]); Clazz.makeConstructor(c$, function(a){ Clazz.superConstructor(this,java.util.Arrays.ArrayList,[]); if(a==null)throw new NullPointerException(); this.a=a; },"~A"); Clazz.overrideMethod(c$,"size", function(){ return this.a.length; }); Clazz.defineMethod(c$,"toArray", function(){ return this.a.clone(); }); Clazz.overrideMethod(c$,"get", function(a){ return this.a[a]; },"~N"); Clazz.overrideMethod(c$,"set", function(a,b){ var c=this.a[a]; this.a[a]=b; return c; },"~N,~O"); Clazz.overrideMethod(c$,"indexOf", function(a){ if(a==null){ for(var b=0;b<this.a.length;b++)if(this.a[b]==null)return b; }else{ for(var b=0;b<this.a.length;b++)if(a.equals(this.a[b]))return b; }return-1; },"~O"); Clazz.overrideMethod(c$,"contains", function(a){ return this.indexOf(a)!=-1; },"~O"); c$=Clazz.p0p(); Clazz.defineStatics(c$, "INSERTIONSORT_THRESHOLD",7); });
import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { TabBar } from './TabBar'; export class RocketChatTabBar { constructor() { this.template = new ReactiveVar(); this.id = new ReactiveVar(); this.group = new ReactiveVar(); this.state = new ReactiveVar(); this.data = new ReactiveVar(); } getTemplate() { return this.template.get(); } getId() { return this.id.get(); } setTemplate(template) { this.template.set(template); } currentGroup() { return this.group.get(); } showGroup(group) { this.group.set(group); } extendsData(data) { this.data.set({ ...this.data.get(), ...data }); } setData(d) { this.data.set(d); } getData() { return this.data.get(); } getButtons() { return TabBar.getButtons(); } getState() { return this.state.get(); } open(button) { this.state.set('opened'); Tracker.afterFlush(() => { $('.contextual-bar__container').scrollTop(0).find('input[type=text]:first').focus(); }); if (!button) { return; } if (typeof button !== 'object' || !button.id) { button = TabBar.getButton(button); } $('.flex-tab, .contextual-bar').css('width', button.width ? `${ button.width }px` : ''); this.template.set(button.template); this.id.set(button.id); return button; } close() { this.state.set(''); $('.flex-tab, .contextual-bar').css('width', ''); this.template.set(); this.id.set(); } }
if ( !window.frameElement && window.location.protocol !== 'file:' ) { // If the page is not yet displayed as an iframe of the index page (navigation panel/working links), // redirect to the index page (using the current URL without extension as the new fragment). // If this URL itself has a fragment, append it with a dot (since '#' in an URL fragment is not allowed). var href = window.location.href; var splitIndex = href.lastIndexOf( '/docs/' ) + 6; var docsBaseURL = href.substr( 0, splitIndex ); var hash = window.location.hash; if ( hash !== '' ) { href = href.replace( hash, '' ); hash = hash.replace( '#', '.' ); } var pathSnippet = href.slice( splitIndex, -5 ); window.location.replace( docsBaseURL + '#' + pathSnippet + hash ); } function onDocumentLoad( event ) { var path; var pathname = window.location.pathname; var section = /\/(manual|api|examples)\//.exec( pathname )[ 1 ].toString().split( '.html' )[ 0 ]; var name = /[\-A-z0-9]+\.html/.exec( pathname ).toString().split( '.html' )[ 0 ]; switch ( section ) { case 'api': path = /\/api\/[A-z0-9\/]+/.exec( pathname ).toString().substr( 5 ); break; case 'examples': path = /\/examples\/[A-z0-9\/]+/.exec( pathname ).toString().substr( 10 ); break; case 'manual': name = name.replace( /\-/g, ' ' ); path = pathname.replace( /\ /g, '-' ); path = /\/manual\/[-A-z0-9\/]+/.exec( path ).toString().substr( 8 ); break; } var text = document.body.innerHTML; text = text.replace( /\[name\]/gi, name ); text = text.replace( /\[path\]/gi, path ); text = text.replace( /\[page:([\w\.]+)\]/gi, "[page:$1 $1]" ); // [page:name] to [page:name title] text = text.replace( /\[page:\.([\w\.]+) ([\w\.\s]+)\]/gi, "[page:" + name + ".$1 $2]" ); // [page:.member title] to [page:name.member title] text = text.replace( /\[page:([\w\.]+) ([\w\.\s]+)\]/gi, "<a onclick=\"window.parent.setUrlFragment('$1')\" title=\"$1\">$2</a>" ); // [page:name title] // text = text.replace( /\[member:.([\w]+) ([\w\.\s]+)\]/gi, "<a onclick=\"window.parent.setUrlFragment('" + name + ".$1')\" title=\"$1\">$2</a>" ); text = text.replace( /\[(member|property|method|param):([\w]+)\]/gi, "[$1:$2 $2]" ); // [member:name] to [member:name title] text = text.replace( /\[(?:member|property|method):([\w]+) ([\w\.\s]+)\]\s*(\(.*\))?/gi, "<a onclick=\"window.parent.setUrlFragment('" + name + ".$2')\" target=\"_parent\" title=\"" + name + ".$2\" class=\"permalink\">#</a> .<a onclick=\"window.parent.setUrlFragment('" + name + ".$2')\" id=\"$2\">$2</a> $3 : <a class=\"param\" onclick=\"window.parent.setUrlFragment('$1')\">$1</a>" ); text = text.replace( /\[param:([\w\.]+) ([\w\.\s]+)\]/gi, "$2 : <a class=\"param\" onclick=\"window.parent.setUrlFragment('$1')\">$1</a>" ); // [param:name title] text = text.replace( /\[link:([\w|\:|\/|\.|\-|\_]+)\]/gi, "[link:$1 $1]" ); // [link:url] to [link:url title] text = text.replace( /\[link:([\w|\:|\/|\.|\-|\_|\(|\)|\#|\=]+) ([\w|\:|\/|\.|\-|\_|\s]+)\]/gi, "<a href=\"$1\" target=\"_blank\">$2</a>" ); // [link:url title] text = text.replace( /\*([\w|\d|\"|\-|\(][\w|\d|\ |\-|\/|\+|\-|\(|\)|\=|\,|\.\"]*[\w|\d|\"|\)]|\w)\*/gi, "<strong>$1</strong>" ); // * text = text.replace( /\[example:([\w\_]+)\]/gi, "[example:$1 $1]" ); // [example:name] to [example:name title] text = text.replace( /\[example:([\w\_]+) ([\w\:\/\.\-\_ \s]+)\]/gi, "<a href=\"../examples/#$1\" target=\"_blank\">$2</a>" ); // [example:name title] text = text.replace( /<a class="param" onclick="window.parent.setUrlFragment\('\w+'\)">(null|this|Boolean|Object|Array|Number|String|Integer|Float|TypedArray|ArrayBuffer)<\/a>/gi, '<span class="param">$1</span>' ); // remove links to primitive types document.body.innerHTML = text; // handle code snippets formatting var elements = document.getElementsByTagName( 'code' ); for ( var i = 0; i < elements.length; i ++ ) { var element = elements[ i ]; text = element.textContent.trim(); text = text.replace( /^\t\t/gm, '' ); element.textContent = text; } // Edit button var button = document.createElement( 'div' ); button.id = 'button'; button.textContent = 'Edit'; button.addEventListener( 'click', function ( event ) { window.open( 'https://github.com/mrdoob/three.js/blob/dev/docs/' + section + '/' + path + '.html' ); }, false ); document.body.appendChild( button ); // Syntax highlighting var styleBase = document.createElement( 'link' ); styleBase.href = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/prettify.css'; styleBase.rel = 'stylesheet'; var styleCustom = document.createElement( 'link' ); styleCustom.href = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/threejs.css'; styleCustom.rel = 'stylesheet'; document.head.appendChild( styleBase ); document.head.appendChild( styleCustom ); var prettify = document.createElement( 'script' ); prettify.src = pathname.substring( 0, pathname.indexOf( 'docs' ) + 4 ) + '/prettify/prettify.js'; prettify.onload = function () { var elements = document.getElementsByTagName( 'code' ); for ( var i = 0; i < elements.length; i ++ ) { var e = elements[ i ]; e.className += ' prettyprint'; } prettyPrint(); }; document.head.appendChild( prettify ); }; document.addEventListener( 'DOMContentLoaded', onDocumentLoad, false );
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Represents the health of the stateful service replica. * Contains the replica aggregated health state, the health events and the * unhealthy evaluations. * * * @extends models['ReplicaHealth'] */ class StatefulServiceReplicaHealth extends models['ReplicaHealth'] { /** * Create a StatefulServiceReplicaHealth. * @member {string} [replicaId] */ constructor() { super(); } /** * Defines the metadata of StatefulServiceReplicaHealth * * @returns {object} metadata of StatefulServiceReplicaHealth * */ mapper() { return { required: false, serializedName: 'Stateful', type: { name: 'Composite', className: 'StatefulServiceReplicaHealth', modelProperties: { aggregatedHealthState: { required: false, serializedName: 'AggregatedHealthState', type: { name: 'String' } }, healthEvents: { required: false, serializedName: 'HealthEvents', type: { name: 'Sequence', element: { required: false, serializedName: 'HealthEventElementType', type: { name: 'Composite', className: 'HealthEvent' } } } }, unhealthyEvaluations: { required: false, serializedName: 'UnhealthyEvaluations', type: { name: 'Sequence', element: { required: false, serializedName: 'HealthEvaluationWrapperElementType', type: { name: 'Composite', className: 'HealthEvaluationWrapper' } } } }, healthStatistics: { required: false, serializedName: 'HealthStatistics', type: { name: 'Composite', className: 'HealthStatistics' } }, partitionId: { required: false, serializedName: 'PartitionId', type: { name: 'String' } }, serviceKind: { required: true, serializedName: 'ServiceKind', type: { name: 'String' } }, replicaId: { required: false, serializedName: 'ReplicaId', type: { name: 'String' } } } } }; } } module.exports = StatefulServiceReplicaHealth;
Clazz.declarePackage ("J.script"); Clazz.load (["J.thread.JmolThread"], "J.script.ScriptDelayThread", null, function () { c$ = Clazz.decorateAsClass (function () { this.millis = 0; this.seconds = 0; this.doPopPush = false; this.isPauseDelay = false; Clazz.instantialize (this, arguments); }, J.script, "ScriptDelayThread", J.thread.JmolThread); Clazz.makeConstructor (c$, function (eval, viewer, millis) { Clazz.superConstructor (this, J.script.ScriptDelayThread, []); this.setViewer (viewer, "ScriptDelayThread"); this.millis = millis; this.setEval (eval); }, "J.api.JmolScriptEvaluator,J.viewer.Viewer,~N"); $_V(c$, "run1", function (mode) { while (true) switch (mode) { case -1: var delayMax; this.doPopPush = (this.millis > 0); this.isPauseDelay = (this.millis == -100); if (!this.doPopPush) this.millis = -this.millis; else if ((delayMax = this.viewer.getDelayMaximumMs ()) > 0 && this.millis > delayMax) this.millis = delayMax; this.millis -= System.currentTimeMillis () - this.startTime; if (this.isJS) { this.seconds = 0; } else { this.seconds = Clazz.doubleToInt (this.millis / 1000); this.millis -= this.seconds * 1000; if (this.millis <= 0) this.millis = 1; }if (this.doPopPush) this.viewer.popHoldRepaint ("scriptDelayThread INIT"); mode = 0; break; case 0: if (this.stopped || this.eval.isStopped ()) { mode = -2; break; }if (!this.runSleep (this.seconds-- > 0 ? 1000 : this.millis, -2)) return; if (this.seconds < 0) this.millis = 0; mode = (this.seconds > 0 || this.millis > 0 ? 0 : -2); break; case -2: if (this.doPopPush) this.viewer.pushHoldRepaint ("delay FINISH"); if (this.isPauseDelay) this.eval.notifyResumeStatus (); this.resumeEval (); return; } }, "~N"); Clazz.defineStatics (c$, "PAUSE_DELAY", -100); });
//jscs:disable maximumLineLength var extraItems = { npc_streetspirit_alchemical_goods: { has_infopage: true, name_single: 'Street Spirit - Alchemical Goods', name_plural: 'Street Spirits - Alchemical Goods', description: 'Fizzling and clinking gently as it bobs up and down, this street spirit (endorsed by all-powerful Tii), is a one-stop shop for all your alchemical needs. From Tongs to Tincturing Kits, Fancy Picks to Firefly Jars, you\'ll find everything Alchemy, Crystalmalizing and Potion-related right here.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_animal_goods: { has_infopage: true, name_single: 'Street Spirit - Animal Goods', name_plural: 'Street Spirits - Animal Goods', description: 'With the ripe smell of Happy Capture branded Piggy Bait wafting from streets away, you can always find a Street Spirit selling Animal Goods if you need one. Specialising in butterfly massage oil, loomers, spindles, and everything you need for a successful home herd.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_gardening_goods: { has_infopage: true, name_single: 'Street Spirit - Gardening Goods', name_plural: 'Street Spirits - Gardening Goods', description: 'Endorsed by Mab herself, if you find a Street Spirit specialising in Gardening Goods, you\'ll find everything necessary for home-grown self-sufficiency.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_groceries: { has_infopage: true, name_single: 'Street Spirit - Groceries', name_plural: 'Street Spirits - Groceries', description: 'Carrying the kind of ingredients necessary for some of your more fancy-pant meals, this Pot-endorsed Street Spirit sells anything delicious that you cannot make at home (like honey, birch syrup and salmon) and a couple of things you can (like buns and garlic). Grocery Street Spirits: The Foodie\'s Friend.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_hardware: { has_infopage: true, name_single: 'Street Spirit - Hardware', name_plural: 'Street Spirits - Hardware', description: 'Clanking almost inaudibly as it bounces gently up and down, you might think the Street Spirit specialising Hardware doesn\'t look like a vendor carrying several tonnes of equipment, but you would be wrong. Bags, Toolboxes, Gassifiers, Fruit-changers and Machine Parts can all be found tucked into invisible pockets of the Alph-endorsed Street Spirit. If you can use it to turn one thing into another, the Hardware vendor probably has it.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_kitchen_tools: { has_infopage: true, name_single: 'Street Spirit - Kitchen Tools', name_plural: 'Street Spirits - Kitchen Tools', description: 'You can\'t make an omlet without making eggs might be true, but you\'d look pretty stupid trying to make one without a frying pan as well. If you need a Frying Pan for frying, a Saucepan for saucing, or an Awesome Pot for general awesomeness, you need to look to the Street Spirit who holds all the Kitchen Tools.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_mining: { has_infopage: true, name_single: 'Street Spirit - Mining', name_plural: 'Street Spirits - Mining', description: 'When you\'re deep in the mining regions and need to load up on equipment, Mining vendors are your best friends. Although they sell their wares at a considerable mark-up, you know you are compensating these Street Spirits well for the difficult task of hauling heavy Smelters and fragile Flaming Humbabas into the depths of Ur.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_produce: { has_infopage: true, name_single: 'Street Spirit - Produce', name_plural: 'Street Spirits - Produce', description: 'For chefs, saucerers and fry-cooks who love to cook but hate to garden, a Street Spirit selling Produce specialises in providing any vegetable you might require for a recipe. Sure, you could grow tomatoes, potatoes, cucumbers or corn in a garden - but why bother, when you could procure them right here in the Produce Aisle.', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} }, npc_streetspirit_toys: { has_infopage: true, name_single: 'Street Spirit - Toys', name_plural: 'Street Spirits - Toys', description: 'Once branded in the age of Tii as The Lord of Misrule, this is a bit unfair for a street spirit who, let\'s face it, mainly specialises in selling dice, party spaces, cubimals, cameras and other things that are fun. If you like fun, seek out a Street Spirit with Toys. And why wouldn\'t you? You don\'t want everyone to think you hate FUN, do you?', parent_classes: ['street_spirit', 'npc_walkable', 'npc'], tags: ['streetspirit', 'no_trade'], classProps: {} } }; //jscs:enable maximumLineLength exports.extra_items = extraItems;
var _ = require('underscore') var low = require('lowdb') var utils = require('./utils') var routes = {} // GET /db routes.db = function(req, res, next) { res.jsonp(low.db) } // GET /:resource // GET /:resource?q= // GET /:resource?attr=&attr= // GET /:parent/:parentId/:resource?attr=&attr= // GET /*?*&_end= // GET /*?*&_start=&_end= routes.list = function(req, res, next) { // Filters list var filters = {} // Result array var array // Remove _start and _end from req.query to avoid filtering using those // parameters var _start = req.query._start var _end = req.query._end var _sort = req.query._sort var _sortDir = req.query._sortDir delete req.query._start delete req.query._end delete req.query._sort delete req.query._sortDir if (req.query.q) { // Full-text search var q = req.query.q.toLowerCase() array = low(req.params.resource).where(function(obj) { for (var key in obj) { var value = obj[key] if (_.isString(value) && value.toLowerCase().indexOf(q) !== -1) { return true } } }).value() } else { // Add :parentId filter in case URL is like /:parent/:parentId/:resource if (req.params.parent) { filters[req.params.parent.slice(0, - 1) + 'Id'] = +req.params.parentId } // Add query parameters filters // Convert query parameters to their native counterparts for (var key in req.query) { if (key !== 'callback') { filters[key] = utils.toNative(req.query[key]) } } // Filter if (_(filters).isEmpty()) { array = low(req.params.resource).value() } else { array = low(req.params.resource).where(filters).value() } } if(_sort) { _sortDir = _sortDir || 'ASC' array = _.sortBy(array, function(element) { return element[_sort]; }) if (_sortDir === 'DESC') { array.reverse(); } } // Slice result if (_end) { res.setHeader('X-Total-Count', array.length) res.setHeader('Access-Control-Expose-Headers', 'X-Total-Count') _start = _start || 0 array = array.slice(_start, _end) } res.jsonp(array) } // GET /:resource/:id routes.show = function(req, res, next) { var resource = low(req.params.resource) .get(+req.params.id) .value() if (resource) { res.jsonp(resource) } else { res.status(404).jsonp({}) } } // POST /:resource routes.create = function(req, res, next) { for (var key in req.body) { req.body[key] = utils.toNative(req.body[key]) } var resource = low(req.params.resource) .insert(req.body) .value() res.jsonp(resource) } // PUT /:resource/:id // PATCH /:resource/:id routes.update = function(req, res, next) { for (var key in req.body) { req.body[key] = utils.toNative(req.body[key]) } var resource = low(req.params.resource) .update(+req.params.id, req.body) .value() if (resource) { res.jsonp(resource) } else { res.status(404).jsonp({}) } } // DELETE /:resource/:id routes.destroy = function(req, res, next) { low(req.params.resource).remove(+req.params.id) // Remove dependents documents var removable = utils.getRemovable(low.db) _(removable).each(function(item) { low(item[0]).remove(item[1]); }) res.status(204).end() } module.exports = routes
'use strict'; var $ = require('jquery'); var App = require('../../app'); var Backbone = require('backbone'); var Marionette = require('backbone.marionette'); var NUSMods = require('../../nusmods'); var _ = require('underscore'); var selectResultTemplate = require('../templates/select_result.hbs'); var template = require('../templates/select.hbs'); require('select2'); module.exports = Marionette.ItemView.extend({ className: 'form-group', template: template, events: { 'select2-selecting': 'onSelect2Selecting' }, ui: { 'input': 'input' }, onMouseenter: function (event) { var button = $(event.currentTarget); button.children('span').hide(); button.children('i').removeClass('hidden'); }, onMouseleave: function (event) { var button = $(event.currentTarget); button.children('span').show(); button.children('i').addClass('hidden'); }, onMouseup: function (event) { event.stopPropagation(); var button = $(event.currentTarget); var add = button.hasClass('add'); App.request((add ? 'add' : 'remove') + 'Module', button.data('semester'), button.data('code')); button .toggleClass('add remove label-default nm-module-added') .prop('title', (add ? 'Add to' : 'Remove from') + 'Timetable') .children('i').toggleClass('fa-plus fa-times'); }, onSelect2Open: function () { $('#select2-drop') .on('mouseenter', 'a', this.onMouseenter) .on('mouseleave', 'a', this.onMouseleave) .on('mouseup', 'a', this.onMouseup); }, onSelect2Selecting: function(event) { event.preventDefault(); Backbone.history.navigate('modules/' + event.val, {trigger: true}); this.ui.input.select2('close'); this.$(':focus').blur(); }, onShow: function () { _.bindAll(this, 'onMouseup', 'onSelect2Open'); var PAGE_SIZE = 50; this.ui.input.select2({ multiple: true, formatResult: function (object) { return selectResultTemplate(object); }, query: function (options) { NUSMods.getCodesAndTitles().then(function (data) { var i, results = [], pushResult = function (i) { var code = data[i].ModuleCode; var semesters = data[i].Semesters; var sems = [{semester: 1}, {semester: 2}]; for (var j = 0; j < semesters.length; j++) { var semester = semesters[j]; if (semester === 1 || semester === 2) { sems[semester - 1].offered = true; sems[semester - 1].selected = App.request('isModuleSelected', semester, code); } } return results.push({ id: code, semesters: sems, text: code + ' ' + data[i].ModuleTitle }); }; var re = new RegExp(options.term, 'i'); for (i = options.context || 0; i < data.length; i++) { if (!options.term || data[i].ModuleCode.search(re) !== -1 || data[i].ModuleTitle.search(re) !== -1) { if (pushResult(i) === PAGE_SIZE) { i++; break; } } } options.callback({ context: i, more: i < data.length, results: results }); }); } }); this.ui.input.one('select2-open', this.onSelect2Open); } });
/* */ define(['exports', 'core-js'], function (exports, _coreJs) { 'use strict'; exports.__esModule = true; exports.json = json; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function json(body) { return new Blob([JSON.stringify(body)], { type: 'application/json' }); } var HttpClientConfiguration = (function () { function HttpClientConfiguration() { _classCallCheck(this, HttpClientConfiguration); this.baseUrl = ''; this.defaults = {}; this.interceptors = []; } HttpClientConfiguration.prototype.withBaseUrl = function withBaseUrl(baseUrl) { this.baseUrl = baseUrl; return this; }; HttpClientConfiguration.prototype.withDefaults = function withDefaults(defaults) { this.defaults = defaults; return this; }; HttpClientConfiguration.prototype.withInterceptor = function withInterceptor(interceptor) { this.interceptors.push(interceptor); return this; }; HttpClientConfiguration.prototype.useStandardConfiguration = function useStandardConfiguration() { var standardConfig = { credentials: 'same-origin' }; Object.assign(this.defaults, standardConfig, this.defaults); return this.rejectErrorResponses(); }; HttpClientConfiguration.prototype.rejectErrorResponses = function rejectErrorResponses() { return this.withInterceptor({ response: rejectOnError }); }; return HttpClientConfiguration; })(); exports.HttpClientConfiguration = HttpClientConfiguration; function rejectOnError(response) { if (!response.ok) { throw response; } return response; } var HttpClient = (function () { function HttpClient() { _classCallCheck(this, HttpClient); this.activeRequestCount = 0; this.isRequesting = false; this.isConfigured = false; this.baseUrl = ''; this.defaults = null; this.interceptors = []; if (typeof fetch === 'undefined') { throw new Error('HttpClient requires a Fetch API implementation, but the current environment doesn\'t support it. You may need to load a polyfill such as https://github.com/github/fetch.'); } } HttpClient.prototype.configure = function configure(config) { var _interceptors; var normalizedConfig = undefined; if (typeof config === 'object') { normalizedConfig = { defaults: config }; } else if (typeof config === 'function') { normalizedConfig = new HttpClientConfiguration(); var c = config(normalizedConfig); if (typeof c === HttpClientConfiguration) { normalizedConfig = c; } } else { throw new Error('invalid config'); } var defaults = normalizedConfig.defaults; if (defaults && defaults.headers instanceof Headers) { throw new Error('Default headers must be a plain object.'); } this.baseUrl = normalizedConfig.baseUrl; this.defaults = defaults; (_interceptors = this.interceptors).push.apply(_interceptors, normalizedConfig.interceptors || []); this.isConfigured = true; return this; }; HttpClient.prototype.fetch = (function (_fetch) { function fetch(_x, _x2) { return _fetch.apply(this, arguments); } fetch.toString = function () { return _fetch.toString(); }; return fetch; })(function (input, init) { var _this = this; trackRequestStart.call(this); var request = Promise.resolve().then(function () { return buildRequest.call(_this, input, init, _this.defaults); }); var promise = processRequest(request, this.interceptors).then(function (result) { var response = null; if (result instanceof Response) { response = result; } else if (result instanceof Request) { response = fetch(result); } else { throw new Error('An invalid result was returned by the interceptor chain. Expected a Request or Response instance, but got [' + result + ']'); } return processResponse(response, _this.interceptors); }); return trackRequestEndWith.call(this, promise); }); return HttpClient; })(); exports.HttpClient = HttpClient; function trackRequestStart() { this.isRequesting = !! ++this.activeRequestCount; } function trackRequestEnd() { this.isRequesting = !! --this.activeRequestCount; } function trackRequestEndWith(promise) { var handle = trackRequestEnd.bind(this); promise.then(handle, handle); return promise; } function parseHeaderValues(headers) { var parsedHeaders = {}; for (var _name in headers || {}) { if (headers.hasOwnProperty(_name)) { parsedHeaders[_name] = typeof headers[_name] === 'function' ? headers[_name]() : headers[_name]; } } return parsedHeaders; } function buildRequest(input) { var init = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var defaults = this.defaults || {}; var source = undefined; var url = undefined; var body = undefined; if (input instanceof Request) { if (!this.isConfigured) { return input; } source = input; url = input.url; body = input.blob(); } else { source = init; url = input; body = init.body; } var parsedDefaultHeaders = parseHeaderValues(defaults.headers); var requestInit = Object.assign({}, defaults, { headers: {} }, source, { body: body }); var request = new Request((this.baseUrl || '') + url, requestInit); setDefaultHeaders(request.headers, parsedDefaultHeaders); return request; } function setDefaultHeaders(headers, defaultHeaders) { for (var _name2 in defaultHeaders || {}) { if (defaultHeaders.hasOwnProperty(_name2) && !headers.has(_name2)) { headers.set(_name2, defaultHeaders[_name2]); } } } function processRequest(request, interceptors) { return applyInterceptors(request, interceptors, 'request', 'requestError'); } function processResponse(response, interceptors) { return applyInterceptors(response, interceptors, 'response', 'responseError'); } function applyInterceptors(input, interceptors, successName, errorName) { return (interceptors || []).reduce(function (chain, interceptor) { var successHandler = interceptor[successName]; var errorHandler = interceptor[errorName]; return chain.then(successHandler && successHandler.bind(interceptor), errorHandler && errorHandler.bind(interceptor)); }, Promise.resolve(input)); } });
function fn() { return <a.b.div id="id" />; }
import Promise from "./promise"; // Wraps our calls to velocity.js so they always return a promise // (there's a PR in velocity upstream to add native promise support -- // once that's ready we can eliminate a lot of this). export function animate(view, props, opts) { return new Promise(function(resolve) { var elt; if (!view || !(elt = view.$())) { resolve(); return; } if (!opts) { opts = {}; } // By default, we ask velocity to reveal the elements at the start // of animation. Our animated divs are all initially rendered at // display:none to prevent a flash of before-animated content. // // At present, velocity's 'auto' just picks a value for the css // display property based on the element type. I have a PR that // would let it defer to the stylesheets instead. if (typeof(opts.display) === 'undefined') { opts.display = 'auto'; } // This is needed for now because velocity doesn't have a callback // that fires after `stop`. if (!view._velocityAnimations) { view._velocityAnimations = []; } view._velocityAnimations.push(resolve); opts.begin = function(elements){ for (var i=0; i<elements.length; i++) { elements[i].style.display = ""; } }; opts.complete = function(){ var i = view._velocityAnimations.indexOf(resolve); if (i >=0 ) { view._velocityAnimations.splice(i, 1); } resolve(); }; elt.velocity(props, opts); }); } export function stop(view) { var elt, animList; if (view && (elt = view.$())) { elt.velocity('stop', true); if (animList = view._velocityAnimations) { for (var i=0; i < animList.length; i++) { animList[i](); } view._velocityAnimations = []; } } } export function setDefaults(props) { /* global $ */ for (var key in props) { if (props.hasOwnProperty(key)) { $.Velocity.defaults[key] = props[key]; } } }
define([ 'client/controllers/services', 'backbone' ], function (ServicesController, Backbone) { describe('Services Controller', function () { var controller, model; beforeEach(function () { model = new Backbone.Model({ filter: '', departmentFilter: '', serviceGroupFilter: '' }); controller = new ServicesController({ model: model, collection: new Backbone.Collection([]) }); controller.unfilteredCollection = { filterServices: jasmine.createSpy() }; }); it('filters when the text filter value changes', function () { model.set('filter', 'baz'); model.trigger('filterChanged'); expect(controller.unfilteredCollection.filterServices) .toHaveBeenCalledWith(jasmine.objectContaining({ text: 'baz' })); }); it('filters when the department filter value changes', function () { model.set('departmentFilter', 'foo'); model.trigger('filterChanged'); expect(controller.unfilteredCollection.filterServices) .toHaveBeenCalledWith(jasmine.objectContaining({ department: 'foo' })); }); it('filters the service when its filter value changes', function () { model.set('serviceGroupFilter', 'bar'); model.trigger('filterChanged'); expect(controller.unfilteredCollection.filterServices) .toHaveBeenCalledWith(jasmine.objectContaining({ serviceGroup: 'bar' })); }); }); });
import Delta from 'quill-delta'; import DeltaOp from 'quill-delta/lib/op'; import Parchment from 'parchment'; import CodeBlock from '../formats/code'; import CursorBlot from '../blots/cursor'; import Block, { bubbleFormats } from '../blots/block'; import clone from 'clone'; import equal from 'deep-equal'; import extend from 'extend'; class Editor { constructor(scroll) { this.scroll = scroll; this.delta = this.getDelta(); } applyDelta(delta) { let consumeNextNewline = false; this.scroll.update(); let scrollLength = this.scroll.length(); this.scroll.batch = true; delta = normalizeDelta(delta); delta.reduce((index, op) => { let length = op.retain || op.delete || op.insert.length || 1; let attributes = op.attributes || {}; if (op.insert != null) { if (typeof op.insert === 'string') { let text = op.insert; if (text.endsWith('\n') && consumeNextNewline) { consumeNextNewline = false; text = text.slice(0, -1); } if (index >= scrollLength && !text.endsWith('\n')) { consumeNextNewline = true; } this.scroll.insertAt(index, text); let [line, offset] = this.scroll.line(index); let formats = extend({}, bubbleFormats(line)); if (line instanceof Block) { let [leaf, ] = line.descendant(Parchment.Leaf, offset); formats = extend(formats, bubbleFormats(leaf)); } attributes = DeltaOp.attributes.diff(formats, attributes) || {}; } else if (typeof op.insert === 'object') { let key = Object.keys(op.insert)[0]; // There should only be one key if (key == null) return index; this.scroll.insertAt(index, key, op.insert[key]); } scrollLength += length; } Object.keys(attributes).forEach((name) => { this.scroll.formatAt(index, length, name, attributes[name]); }); return index + length; }, 0); delta.reduce((index, op) => { if (typeof op.delete === 'number') { this.scroll.deleteAt(index, op.delete); return index; } return index + (op.retain || op.insert.length || 1); }, 0); this.scroll.batch = false; this.scroll.optimize(); return this.update(delta); } deleteText(index, length) { this.scroll.deleteAt(index, length); return this.update(new Delta().retain(index).delete(length)); } formatLine(index, length, formats = {}) { this.scroll.update(); Object.keys(formats).forEach((format) => { if (this.scroll.whitelist != null && !this.scroll.whitelist[format]) return; let lines = this.scroll.lines(index, Math.max(length, 1)); let lengthRemaining = length; lines.forEach((line) => { let lineLength = line.length(); if (!(line instanceof CodeBlock)) { line.format(format, formats[format]); } else { let codeIndex = index - line.offset(this.scroll); let codeLength = line.newlineIndex(codeIndex + lengthRemaining) - codeIndex + 1; line.formatAt(codeIndex, codeLength, format, formats[format]); } lengthRemaining -= lineLength; }); }); this.scroll.optimize(); return this.update(new Delta().retain(index).retain(length, clone(formats))); } formatText(index, length, formats = {}) { Object.keys(formats).forEach((format) => { this.scroll.formatAt(index, length, format, formats[format]); }); return this.update(new Delta().retain(index).retain(length, clone(formats))); } getContents(index, length) { return this.delta.slice(index, index + length); } getDelta() { return this.scroll.lines().reduce((delta, line) => { return delta.concat(line.delta()); }, new Delta()); } getFormat(index, length = 0) { let lines = [], leaves = []; if (length === 0) { this.scroll.path(index).forEach(function(path) { let [blot, ] = path; if (blot instanceof Block) { lines.push(blot); } else if (blot instanceof Parchment.Leaf) { leaves.push(blot); } }); } else { lines = this.scroll.lines(index, length); leaves = this.scroll.descendants(Parchment.Leaf, index, length); } let formatsArr = [lines, leaves].map(function(blots) { if (blots.length === 0) return {}; let formats = bubbleFormats(blots.shift()); while (Object.keys(formats).length > 0) { let blot = blots.shift(); if (blot == null) return formats; formats = combineFormats(bubbleFormats(blot), formats); } return formats; }); return extend.apply(extend, formatsArr); } getText(index, length) { return this.getContents(index, length).filter(function(op) { return typeof op.insert === 'string'; }).map(function(op) { return op.insert; }).join(''); } insertEmbed(index, embed, value) { this.scroll.insertAt(index, embed, value); return this.update(new Delta().retain(index).insert({ [embed]: value })); } insertText(index, text, formats = {}) { text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); this.scroll.insertAt(index, text); Object.keys(formats).forEach((format) => { this.scroll.formatAt(index, text.length, format, formats[format]); }); return this.update(new Delta().retain(index).insert(text, clone(formats))); } isBlank() { if (this.scroll.children.length == 0) return true; if (this.scroll.children.length > 1) return false; let child = this.scroll.children.head; return child.length() <= 1 && Object.keys(child.formats()).length == 0; } removeFormat(index, length) { let text = this.getText(index, length); let [line, offset] = this.scroll.line(index + length); let suffixLength = 0, suffix = new Delta(); if (line != null) { if (!(line instanceof CodeBlock)) { suffixLength = line.length() - offset; } else { suffixLength = line.newlineIndex(offset) - offset + 1; } suffix = line.delta().slice(offset, offset + suffixLength - 1).insert('\n'); } let contents = this.getContents(index, length + suffixLength); let diff = contents.diff(new Delta().insert(text).concat(suffix)); let delta = new Delta().retain(index).concat(diff); return this.applyDelta(delta); } update(change, mutations = [], cursorIndex = undefined) { let oldDelta = this.delta; if (mutations.length === 1 && mutations[0].type === 'characterData' && Parchment.find(mutations[0].target)) { // Optimization for character changes let textBlot = Parchment.find(mutations[0].target); let formats = bubbleFormats(textBlot); let index = textBlot.offset(this.scroll); let oldValue = mutations[0].oldValue.replace(CursorBlot.CONTENTS, ''); let oldText = new Delta().insert(oldValue); let newText = new Delta().insert(textBlot.value()); let diffDelta = new Delta().retain(index).concat(oldText.diff(newText, cursorIndex)); change = diffDelta.reduce(function(delta, op) { if (op.insert) { return delta.insert(op.insert, formats); } else { return delta.push(op); } }, new Delta()); this.delta = oldDelta.compose(change); } else { this.delta = this.getDelta(); if (!change || !equal(oldDelta.compose(change), this.delta)) { change = oldDelta.diff(this.delta, cursorIndex); } } return change; } } function combineFormats(formats, combined) { return Object.keys(combined).reduce(function(merged, name) { if (formats[name] == null) return merged; if (combined[name] === formats[name]) { merged[name] = combined[name]; } else if (Array.isArray(combined[name])) { if (combined[name].indexOf(formats[name]) < 0) { merged[name] = combined[name].concat([formats[name]]); } } else { merged[name] = [combined[name], formats[name]]; } return merged; }, {}); } function normalizeDelta(delta) { return delta.reduce(function(delta, op) { if (op.insert === 1) { let attributes = clone(op.attributes); delete attributes['image']; return delta.insert({ image: op.attributes.image }, attributes); } if (op.attributes != null && (op.attributes.list === true || op.attributes.bullet === true)) { op = clone(op); if (op.attributes.list) { op.attributes.list = 'ordered'; } else { op.attributes.list = 'bullet'; delete op.attributes.bullet; } } if (typeof op.insert === 'string') { let text = op.insert.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); return delta.insert(text, op.attributes); } return delta.push(op); }, new Delta()); } export default Editor;
this.click = function(e) { alert('Hello!') }.bind(this) this.click = function(a,b) { alert('World!') }.bind(this) this.click = function(a) {alert('World!') }.bind(this) this.click = function( a, b) { alert('World!') }.bind(this) this.click = function( a, b) { alert('World!') } .bind(this) this.click = function(a, b ){ alert('World!') }. bind(that) this.click = function(a) { alert('World!') }.bind(this) this.click = function(a){alert('World!')}.bind(this)
var React = require('react-native'); var api = require('./webapi'); var self = this; var { View, TextInput, Text, Image, StyleSheet, PixelRatio, AlertIOS, AsyncStorage, TouchableOpacity, TouchableHighlight } = React; //just do nothing var noop = () => {}; var Login = React.createClass({ getDefaultProps() { return { onLoginSuccess: noop } }, getInitialState() { return { username: '', password: '' } }, render() { return ( <View style={styles.container}> <Image style={styles.img} source={require('image!logo')} /> <TextInput placeholder='用户名' style={styles.input} value={this.state.username} onChangeText={(txt) => this.setState({username: txt})} /> <TextInput password={true} placeholder='密 码' style={styles.input} value={this.state.password} onChangeText={(txt) => this.setState({password: txt})} /> <TouchableOpacity style={styles.btn} onPress={this._handleLogin}> <Text style={styles.btnText}>登 录</Text> </TouchableOpacity> </View> ); }, _handleLogin() { var username = this.state.username; var password = this.state.password; if (!username) { AlertIOS.alert('', '请填写用户名') return; } if (!password) { AlertIOS.alert('', '请填写密码'); return; } api .login(username, password) .then(success, error); //登录成功 var onLoginSuccess = this.props.onLoginSuccess; function success(res) { console.log('token:', res.token); self.token = res.token; AsyncStorage .setItem('freyr_token', res.token || '', (err) => { if (err) { AlertIOS.alert('', '内部错误,请重试'); return; } onLoginSuccess(); }); } //登录失败 function error(err) { if (__DEV__) { console.log(err); } AlertIOS.alert('', '用户名或者密码错误'); } } }); var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 10, }, input: { height: 40, marginTop: 10, borderWidth: 1 / PixelRatio.get(), borderColor: 'lightblue', borderRadius: 3, padding: 10 }, btn: { height: 40, marginTop: 10, backgroundColor: '#43c6a6', alignSelf: 'stretch', alignItems: 'center', justifyContent: 'center', paddingTop: 8, paddingBottom: 8, borderRadius: 3, borderColor: 'green' }, btnText: { color: '#FFF', fontSize: 20 }, img: { height: 110, width: 60, borderRadius: 30, borderWidth: 1 / PixelRatio.get(), borderColor: 'lightblue' } }); module.exports = Login;
version https://git-lfs.github.com/spec/v1 oid sha256:4f1e15b0480d23bc6ef0094219c8d0c92ca712107e58ce44b1307ba2b46b78b0 size 13712
define(function () { function F(){} /** * Do fn.apply on a constructor. */ function ctorApply(ctor, args) { F.prototype = ctor.prototype; var instance = new F(); ctor.apply(instance, args); return instance; } return ctorApply; });
NEJ.define([ 'util/dispatcher/dispatcher?v=123' ],function(){ var a = 'aaaaa'; console.log(a); });
import Backburner from '../lib/backburner'; module('deferOnce'); test('when passed a function', function() { expect(1); var bb = new Backburner(['one']); var functionWasCalled = false; bb.run(function() { bb.deferOnce('one', function() { functionWasCalled = true; }); }); ok(functionWasCalled, 'function was called'); }); test('when passed a target and method', function() { expect(2); var bb = new Backburner(['one']); var functionWasCalled = false; bb.run(function() { bb.deferOnce('one', {zomg: 'hi'}, function() { equal(this.zomg, 'hi', 'the target was properly set'); functionWasCalled = true; }); }); ok(functionWasCalled, 'function was called'); }); test('when passed a target and method name', function() { expect(2); var bb = new Backburner(['one']); var functionWasCalled = false; var targetObject = { zomg: 'hi', checkFunction: function() { equal(this.zomg, 'hi', 'the target was properly set'); functionWasCalled = true; } }; bb.run(function() { bb.deferOnce('one', targetObject, 'checkFunction'); }); ok(functionWasCalled, 'function was called'); }); test('throws when passed a null method', function() { expect(1); function onError(error) { equal('You attempted to schedule an action in a queue (deferErrors) for a method that doesn\'t exist', error.message); } var bb = new Backburner(['deferErrors'], { onError: onError }); bb.run(function() { bb.deferOnce('deferErrors', {zomg: 'hi'}, null); }); }); test('throws when passed an undefined method', function() { expect(1); function onError(error) { equal('You attempted to schedule an action in a queue (deferErrors) for a method that doesn\'t exist', error.message); } var bb = new Backburner(['deferErrors'], { onError: onError }); bb.run(function() { bb.deferOnce('deferErrors', {zomg: 'hi'}, undefined); }); }); test('throws when passed an method name that does not exists on the target', function() { expect(1); function onError(error) { equal('You attempted to schedule an action in a queue (deferErrors) for a method that doesn\'t exist', error.message); } var bb = new Backburner(['deferErrors'], { onError: onError }); bb.run(function() { bb.deferOnce('deferErrors', {zomg: 'hi'}, 'checkFunction'); }); }); test('when passed a target, method, and arguments', function() { expect(5); var bb = new Backburner(['one']); var functionWasCalled = false; bb.run(function() { bb.deferOnce('one', {zomg: 'hi'}, function(a, b, c) { equal(this.zomg, 'hi', 'the target was properly set'); equal(a, 1, 'the first arguments was passed in'); equal(b, 2, 'the second arguments was passed in'); equal(c, 3, 'the third arguments was passed in'); functionWasCalled = true; }, 1, 2, 3); }); ok(functionWasCalled, 'function was called'); }); test('when passed same function twice', function() { expect(2); var bb = new Backburner(['one']); var i = 0; var functionWasCalled=false; var deferMethod = function(){ i++; equal(i, 1, 'Function should be called only once'); functionWasCalled = true; }; bb.run(function() { bb.deferOnce('one', deferMethod); bb.deferOnce('one', deferMethod); }); ok(functionWasCalled, 'function was called only once'); }); test('when passed same function twice with same target', function() { expect(3); var bb = new Backburner(['one']); var i=0; var functionWasCalled=false; var deferMethod = function(){ i++; equal(i, 1, 'Function should be called only once'); equal(this['first'], 1, 'the target property was set'); functionWasCalled = true; }; var argObj = {'first': 1}; bb.run(function() { bb.deferOnce('one', argObj, deferMethod); bb.deferOnce('one', argObj, deferMethod); }); ok(functionWasCalled, 'function was called only once'); }); test('when passed same function twice with different targets', function() { expect(3); var bb = new Backburner(['one']); var i = 0; var deferMethod = function(){ i++; equal(this['first'], 1, 'the target property was set'); }; bb.run(function() { bb.deferOnce('one', {'first': 1}, deferMethod); bb.deferOnce('one', {'first': 1}, deferMethod); }); equal(i, 2, 'function was called twice'); }); test('when passed same function twice with same arguments and same target', function() { expect(4); var bb = new Backburner(['one']); var i = 0; var deferMethod = function(a, b){ i++; equal(a, 1, 'First argument is set only one time'); equal(b, 2, 'Second argument remains same'); equal(this['first'], 1, 'the target property was set'); }; var argObj = {'first': 1}; bb.run(function() { bb.deferOnce('one', argObj, deferMethod, 1, 2); bb.deferOnce('one', argObj, deferMethod, 1, 2); }); equal(i, 1, 'function was called once'); }); test('when passed same function twice with same target and different arguments', function() { expect(4); var bb = new Backburner(['one']); var i=0; var deferMethod = function(a, b){ i++; equal(a, 3, 'First argument of only second call is set'); equal(b, 2, 'Second argument remains same'); equal(this['first'], 1, 'the target property was set'); }; var argObj = {'first': 1}; bb.run(function() { bb.deferOnce('one', argObj, deferMethod, 1, 2); bb.deferOnce('one', argObj, deferMethod, 3, 2); }); equal(i, 1, 'function was called once'); }); test('when passed same function twice with different target and different arguments', function() { expect(7); var bb = new Backburner(['one']); var i = 0; var deferMethod = function(a, b){ i++; if(i === 1){ equal(a, 1, 'First argument set during first call'); } else { equal(a, 3, 'First argument set during second call'); } equal(b, 2, 'Second argument remains same'); equal(this['first'], 1, 'the target property was set'); }; var argObj = {'first': 1}; bb.run(function() { bb.deferOnce('one', {'first': 1}, deferMethod, 1, 2); bb.deferOnce('one', {'first': 1}, deferMethod, 3, 2); }); equal(i, 2, 'function was called twice'); }); test('when passed same function with same target after already triggering in current loop (GUID_KEY)', function() { expect(5); var bb = new Backburner(['one', 'two'], { 'GUID_KEY': 'GUID_KEY' }); var i=0; var deferMethod = function(a){ i++; equal(a, i, 'Correct argument is set'); equal(this['first'], 1, 'the target property was set'); }; var scheduleMethod = function() { bb.deferOnce('one', argObj, deferMethod, 2); }; var argObj = {'first': 1, GUID_KEY: '1'}; bb.run(function() { bb.deferOnce('one', argObj, deferMethod, 1); bb.deferOnce('two', argObj, scheduleMethod); }); equal(i, 2, 'function was called twice'); }); test('onError', function() { expect(1); function onError(error) { equal('test error', error.message); } var bb = new Backburner(['errors'], { onError: onError }); bb.run(function() { bb.deferOnce('errors', function() { throw new Error('test error'); }); }); });
/** @description Check if an object is a Deferred. @function can.isDeferred @parent can.util @signature `can.isDeferred(subject)` @param {*} subject The object to check. @return {Boolean} Whether __subject__ is a Deferred. @body `can.isDeferred` returns if an object is an instance of [can.Deferred]. ## Example Convert any value to a Deferred: @codestart function convertDeferred(dfd) { return can.isDeferred(dfd) ? dfd : can.Deferred(dfd); } @codeend */ // /** @description Trim whitespace off a string. @function can.trim @parent can.util @signature `can.trim(str)` @param {String} str The string to trim. @return {String} The trimmed string. @body `can.trim(str)` removes leading and trailing whitespace from a string. It will also remove all newlines, spaces including non-breaking, and tabs. If these occur in the middle of the string, then they will be persisted. @codestart can.trim(" foo ") // "foo" @codeend */ // /** @description Convert an array-like object to an Array. @function can.makeArray @parent can.util @signature `can.makeArray(arrLike)` @param {Object} arrLike An array-like object. @return {Array} The converted object. @body `can.makeArray(arrLike)` converts an array-like object into a array. @codestart can.makeArray({0 : "zero", 1: "one", length: 2}); // ["zero","one"] @codeend */ // /** @description Check if an object is an array. @function can.isArray @parent can.util @signature `can.isArray(obj)` @param {*} obj The object to check. @return {Boolean} Whether __obj__ is an Array. @body `can.isArray(object)` returns if the object is an Array. @codestart can.isArray([]); // true can.isArray(false); // false @codeend */ // /** @description Iterate through an array or object. @function can.each @parent can.util @signature `can.each(collection, callback)` @param {Object} collection The object to iterate through. @param {Function} callback A function to call for each item in __collection__. __callback__ will recieve the item's value first and its key second. @body `can.each(collection, callback)` iterates through an array or object like like [http://api.jquery.com/jQuery.each/ jQuery.each]. @codestart can.each([{prop: "val1"}, {prop: "val2"}], function( value, index ) { // function called with // index=0 value={prop: "val1"} // index=1 value={prop: "val2"} } ); @codeend */ // /** @description Merge objects together. @function can.extend @parent can.util @signature `can.extend(target, ...obj)` @param {Object} target The object to merge properties into. @param {Object} obj Objects containing properties to merge. @return {Object} __target__, post-merge. @body `can.extend(target, objectN)` merges the contents of two or more objects together into the first object similarly to [http://api.jquery.com/jQuery.extend/ jQuery.extend]. @codestart var first = {}, second = {a: "b"}, third = {c: "d"}; can.extend(first, second, third); //-> first first //-> {a: "b", c: "d"} second //-> {a: "b"} third //-> {c: "d"} @codeend */ // /** @description Serialize an object into a query string. @function can.param @parent can.util @signature `can.param(obj)` @param {Object} obj An array or object to serialize. @return {String} The serialized string. @body Parameterizes an object into a query string like [http://api.jquery.com/jQuery.param/ jQuery.param]. @codestart can.param({a: "b", c: "d"}) //-> "a=b&c=d" @codeend */ // /** @description Check if an object has no properties. @function can.isEmptyObject @parent can.util @signature `can.isEmptyObject(obj)` @param {Object} obj The object to check. @param {Boolean} Whether the object is empty. @body `can.isEmptyObject(obj)` returns if an object has no properties similar to [http://api.jquery.com/jQuery.isEmptyObject/ jQuery.isEmptyObject]. @codestart can.isEmptyObject({}) //-> true can.isEmptyObject({a:"b"}) //-> false @codeend */ // /** @description Bind a function to its context. @function can.proxy @parent can.util @signature `can.proxy(fn, context)` @param {Function} fn The function to bind to a context. @param {Object} context The context to bind the function to. @return {Function} A function that calls __fn__ in the context of __context__. @body `can.proxy(fn, context)` accepts a function and returns a new one that will always have the context from which it was called. This works similar to [http://api.jquery.com/jQuery.proxy/ jQuery.proxy]. @codestart var func = can.proxy(function(one){ return this.a + one }, {a: "b"}); func("two") //-> "btwo" @codeend */ // /** @description Check if an Object is a function. @function can.isFunction @parent can.util @signature `can.isFunction(obj)` @param {Object} obj The object to check. @return {Boolean} Whether __obj__ is a function. @body `can.isFunction(object)` returns if an object is a function similar to [http://api.jquery.com/jQuery.isFunction/ jQuery.isFunction]. @codestart can.isFunction({}) //-> false can.isFunction(function(){}) //-> true @codeend */ // /** @description Listen for events on an object. @function can.bind @parent can.util @signature `can.bind.call(target, eventName, handler)` @param {Object} target The object that emits events. @param {String} eventName The name of the event to listen for. @param {Function} handler The function to execute when the event occurs. @return {Object} The __target__. @body `can.bind(eventName, handler)` binds a callback handler on an object for a given event. It works on: - HTML elements and the window - Objects - Objects with bind / unbind methods The idea is that bind can be used on anything that produces events and it will figure out the appropriate way to bind to it. Typically, `can.bind` is only used internally to CanJS; however, if you are making libraries or extensions, use `can.bind` to listen to events independent of the underlying library. __Binding to an object__ @codestart var obj = {}; can.bind.call(obj,"something", function(ev, arg1, arg){ arg1 // 1 arg2 // 2 }) can.trigger(obj,"something",[1,2]) @codeend __Binding to an HTMLElement__ @codestart var el = document.getElementById('foo') can.bind.call(el, "click", function(ev){ this // el }); @codeend */ // /** @description Stop listening for events on an object. @function can.unbind @parent can.util @signature `can.unbind.call(target, eventName, handler)` @param {Object} target The object that emits events. @param {String} eventName The name of the event to listen for. @param {Function} handler The function to unbind. @return {Object} The __target__. @body `can.unbind(eventName, handler)` unbinds a callback handler from an object for a given event. It works on: - HTML elements and the window - Objects - Objects with bind / unbind methods The idea is that unbind can be used on anything that produces events and it will figure out the appropriate way to unbind to it. Typically, `can.unbind` is only used internally to CanJS; however, if you are making libraries or extensions, use `can.bind` to listen to events independent of the underlying library. __Binding/unbinding to an object__ @codestart var obj = {}, handler = function(ev, arg1, arg){ arg1 // 1 arg2 // 2 }; can.bind.call(obj,"something", handler) can.trigger(obj,"something",[1,2]) can.unbind.call(obj,"something", handler) @codeend __Binding/unbinding to an HTMLElement__ @codestart var el = document.getElementById('foo'), handler = function(ev){ this // el }; can.bind.call(el, "click", handler) can.unbind.call(el, "click", handler) @codeend */ // /** @description Listen for events from the children of an element. @function can.delegate @parent can.util @signature `can.delegate.call(element, selector, eventName, handler)` @param {HTMLElement} element The HTML element to bind to. @param {String} selector A selector for delegating downward. @param {String} eventName The name of the event to listen for. @param {Function} handler The function to execute when the event occurs. @return {Object} The __element__. @body `can.delegate(selector, eventName, handler)` binds a delegate handler on an object for a given event. It works on: - HTML elements and the window The idea is that delegate can be used on anything that produces delegate events and it will figure out the appropriate way to bind to it. Typically, `can.delegate` is only used internally to CanJS; however, if you are making libraries or extensions, use `can.delegate` to listen to events independent of the underlying library. __Delegate binding to an HTMLElement__ @codestart var el = document.getElementById('foo') can.delegate.call(el, ".selector", "click", function(ev){ this // el }) @codeend */ // /** @description Stop listening for events from the children of an element. @function can.undelegate @parent can.util @signature `can.undelegate.call(element, selector, eventName, handler)` @param {HTMLElement} element The HTML element to unbind from. @param {String} selector A selector for delegating downward. @param {String} eventName The name of the event to listen for. @param {Function} handler The function that was bound. @return {Object} The __element__. `can.undelegate(selector, eventName, handler)` unbinds a delegate handler on an object for a given event. It works on: - HTML elements and the window The idea is that undelegate can be used on anything that produces delegate events and it will figure out the appropriate way to bind to it. Typically, `can.undelegate` is only used internally to CanJS; however, if you are making libraries or extensions, use `can.undelegate` to listen to events independent of the underlying library. __Delegate/undelegate binding to an HTMLElement__ @codestart var el = document.getElementById('foo'), handler = function(ev){ this // el }; can.delegate.call(el, ".selector", "click", handler) can.undelegate.call(el, ".selector", "click", handler) @codeend */ // /** @description Trigger an event. @function can.trigger @parent can.util @signature `can.trigger(target, eventName[, args])` @param {Object} target The object to trigger the event on. @param {String} eventName The event to trigger. @param {Array.<*>} [args] The event data. Trigger an event on an element or object. */ // /** @description Make an AJAX request. @function can.ajax @parent can.util @signature `can.ajax(settings)` @param {Object} settings Configuration options for the AJAX request. The list of configuration options is the same as for [jQuery.ajax()](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings). @return {Deferred} A can.Deferred that resolves to the data. @body `can.ajax( settings )` is used to make an asynchronous HTTP (Ajax) request similar to [http://api.jquery.com/jQuery.ajax/ jQuery.ajax]. @codestart can.ajax({ url: 'ajax/farm/animals', success: function(animals) { can.$('.farm').html(animals); } }); @codeend */ // /** @description Make a library's nodelist. @function can.$ @parent can.util @signature `can.$(element)` @param {String|Element|NodeList} element The selector, HTML element, or nodelist to pass to the underlying library. @return {NodeList} The nodelist as constructed by the underlying library. @body `can.$(element)` returns the the underlying library's NodeList. It can be passed a css selector, a HTMLElement or an array of HTMLElements. The following lists how the NodeList is created by each library: - __jQuery__ `jQuery( HTMLElement )` - __Zepto__ `Zepto( HTMLElement )` - __Dojo__ `new dojo.NodeList( HTMLElement )` - __Mootools__ `$$( HTMLElement )` - __YUI__ `Y.all(selector)` or `Y.NodeList` */ // /** @description Make a document fragment. @function can.buildFragment @parent can.util @signature `can.buildFragment(html, node)` @param {String} html A string of HTML. @param {DOM Node} node A node used to access a document to make the fragment with. @return {DocumentFragment} A document fragment made from __html__. @body `can.buildFragment(html, node)` returns a document fragment for the HTML passed. */ // /** @description Append content to elements. @function can.append @parent can.util @signature `can.append(nodeList, html)` @param {NodeList} nodeList A nodelist of the elements to append content to. @param {String} html The HTML to append to the end of the elements in __nodeList__. @body `can.append( wrappedNodeList, html )` inserts content to the end of each wrapped node list item(s) passed. @codestart // Before <div id="demo" /> can.append( can.$('#demo'), 'Demos are fun!' ); // After <div id="demo">Demos are fun!</div> @codeend */ // /** @description Remove elements from the DOM. @function can.remove @parent can.util @signature `can.remode(nodeList)` @param {NodeList} nodeList A nodelist of elements to remove. @body `can.remove( wrappedNodeList )` removes the set of matched element(s) from the DOM. @codestart <div id="wrap"/> can.remove(can.$('#wrap')) //-> removes 'wrap' @codeend */ // /** @description Associate data with or retrieve data from DOM nodes. @function can.data @parent can.util @signature `can.data(nodeList, key, value)` @param {NodeList} nodeList The list of nodes to add this data to. @param {String} key The key to store this data under. @param {*} value The data to store. @signature `can.data(nodeList, key)` @param {NodeList} nodeList The list of nodes data was stored under. @param {String} key The key to retrieve. @return {*} The data stored under __key__. @body `can.data` enables the associatation of arbitrary data with DOM nodes and JavaScript objects. ### Setting Data can.data( can.$('#elm'), key, value ) - __wrappedNodeList__ node list to associate data to. - __key__ string name of the association. - __value__ tdata value; it can be any Javascript type including Array or Object. ### Accessing Data can.data( can.$('#elm'), key ) - __wrappedNodeList__ node list to retrieve association data from. - __key__ string name of the association. Due to the way browsers security restrictions with plugins and external code, the _data_ method cannot be used on `object` (unless it's a Flash plugin), `applet` or `embed` elements. */ // /** @description Add a class to elements. @function can.addClass @parent can.util @signature `can.addClass(nodeList, className)` @param {NodeList} nodeList The list of HTML elements to add the class to. @param {String} className The class to add. @body `can.addClass( nodelist, className )` adds the specified class(es) to nodelist's HTMLElements. It does NOT replace any existing class(es) already defined. @codestart // Before <div id="foo" class="monkey" /> can.addClass(can.$("#foo"),"bar") // After <div id="foo" class="monkey bar" /> @codeend You can also pass multiple class(es) and it will add them to the existing set also. @codestart // Before <div id="foo" class="monkey" /> can.addClass(can.$("#foo"),"bar man") // After <div id="foo" class="monkey bar man" /> @codeend This works similarly to [http://api.jquery.com/addClass/ jQuery.fn.addClass]. */ // /** @description Call a callback when a Deferred resolves. @function can.when @parent can.util @signature `can.when(deferred)` @param {Deferred|Object} deferred The Deferred, AJAX, or normal Objects to call the callback on. @return {Deferred} __deferred__ if __deferred__ is a Deferred, otherwise a Deferred that resolves to __deferred__. @body `can.when(deferred)` provides the ability to execute callback function(s) typically based on a Deferred or AJAX object. @codestart can.when( can.ajax('api/farm/animals') ).then(function(animals){ alert(animals); //-> alerts the ajax response }); @codeend You can also use this for regular JavaScript objects. @codestart $.when( { animals: [ 'cat' ] } ).done(function(animals){ alert(animals[0]); //-> alerts 'cat' }); @codeend */ // /** @constructor can.Deferred @parent canjs `can.Deferred` is a object that allows users to assign and chain callback function(s) for the success or failure state of both asynchronous and synchronous function(s). @signature `can.Deferred()` @return {can.Deferred} A new Deferred object. */ // /* * @prototype */ // /** @description Add callbacks to a Deferred. @function can.Deferred.prototype.pipe @signature `pipe(doneCallback[, failCallback])` @param {Function} doneCallback A function called when the Deferred is resolved. @param {Function} failCallback A function called when the Deferred is rejected. @body `deferred.pipe(doneCallback, failCallback)` is a utility to filter Deferred(s). @codestart var def = can.Deferred(), filtered = def.pipe(function(val) { return val + " is awesome!"; }); def.resolve('Can'); filtered.done(function(value) { alert(value); // Alerts: 'Can is awesome!' }); @codeend */ // /** @description Resolve a Deferred in a particular context. @function can.Deferred.prototype.resolveWith resolveWith @parent can.Deferred.prototype @signature `resolveWith(context[, arguments])` @param {Object} context Context passed to the `doneCallbacks` as the `this` object. @param {Object} [arguments] Array of arguments that are passed to the `doneCallbacks`. @body `deferred.resolveWith(context, arguments)` resolves a Deferred and calls the `doneCallbacks` with the given arguments. @codestart var def = can.Deferred(); def.resolveWith(this, { animals: [ 'cows', 'monkey', 'panda' ] }) @codeend */ // /** @description Reject a Deferred in a particular context. @function can.Deferred.prototype.rejectWith rejectWith @parent can.Deferred.prototype @signature `rejectWith(context[, arguments])` @param {Object} context Context passed to the `failCallbacks` as the `this` object. @param {Object} [arguments] Array of arguments that are passed to the `failCallbacks`. @body `deferred.rejectWith(context, arguments)` rejects a Deferred and calls the `failCallbacks` with the given arguments. @codestart var def = can.Deferred(); def.rejectWith(this, { error: "Animals are gone." }) @codeend */ // /** @description Add a callback to be called when a Deferred is resolved. @function can.Deferred.prototype.done done @parent can.Deferred.prototype @signature `done(doneCallback)` @param {Function} doneCallback A callback to be called when the Deferred is resolved. @body `deferred.done(doneCallback)` adds handler(s) to be called when the Deferred object is resolved. @codestart var def = can.Deferred(); def.done(function(){ //- Deferred is done. }); @codeend */ /** @description Add a callback to be called when a Deferred is rejected. @function can.Deferred.prototype.fail fail @parent can.Deferred.prototype @signature `fail(failCallback)` @param {Function} failCallback A callback to be called when the Deferred is rejected. @body `deferred.fail(failCallback)` adds handler(s) to be called when the Deferred object is rejected. @codestart var def = can.Deferred(); def.fail(function(){ //- Deferred got rejected. }); @codeend */ // /** @description Add a callback to be unconditionally called. @function can.Deferred.prototype.always always @parent can.Deferred.prototype @signature `always(alwaysCallback)` @param {Function} alwaysCallback A callback to be called whether the Deferred is resolved or rejected. @body `deferred.always( alwaysCallbacks )` adds handler(s) to be called when the Deferred object is either resolved or rejected. @codestart var def = can.Deferred(); def.always( function(){ //- Called whether the handler fails or is success. }); @codeend */ // /** @description Add callbacks to a Deferred. @function can.Deferred.prototype.then then @parent can.Deferred.prototype @signature `then(doneCallback[, failCallback])` @param {Function} doneCallback A function called when the Deferred is resolved. @param {Function} [failCallback] A function called when the Deferred is rejected. @body `deferred.then( doneCallback, failCallback )` adds handler(s) to be called when the Deferred object to be called after its resolved. @codestart var def = can.Deferred(); def.then(function(){ //- Called when the deferred is resolved. }, function(){ //- Called when the deferred fails. }) @codeend */ // /** @description Determine whether a Deferred has been resolved. @function can.Deferred.prototype.isResolved isResolved @parent can.Deferred.prototype @signature `isResolved()` @return {Boolean} Whether this Boolean has been resolved. @body `deferred.isResolved()` returns whether a Deferred object has been resolved. @codestart var def = can.Deferred(); var resolved = def.isResolved(); @codeend */ /** @description Determine whether a Deferred has been rejected. @function can.Deferred.prototype.isRejected isRejected @signature `isRejected()` @return {Boolean} Whether this Boolean has been rejected. @body `deferred.isRejected()` returns whether a Deferred object has been rejected. @codestart var def = can.Deferred(); var rejected = def.isRejected() @codeend */ // /** @description Reject a Deferred. @function can.Deferred.prototype.reject reject @parent can.Deferred.prototype @signature `reject([argument])` @param {Object} [argument] The argument to call the `failCallback` with. @body `deferred.reject( args )` rejects the Deferred object and calls the fail callbacks with the given arguments. @codestart var def = can.Deferred(); def.reject({ error: 'Thats not an animal.' }) @codeend */ // /** @description Resolve a Deferred. @function can.Deferred.prototype.resolve resolve @signature `resolve([argument])` @param {Object} [argument] The argument to call the `doneCallback` with. @body `deferred.resolve( args )` resolves a Deferred object and calls the done callbacks with the given arguments. @codestart var def = can.Deferred(); def.resolve({ animals: [ 'pig', 'cow' ] }) @codeend */ var a = function() {};
// Get Programming with JavaScript // Listing 20.03 // A module for loading JS Bin data (function () { "use strict"; function loadData (bin, callback) { var xhr = new XMLHttpRequest(); var url = "http://output.jsbin.com/" + bin + ".json"; xhr.addEventListener("load", function () { var data = JSON.parse(xhr.responseText); callback(data); }); xhr.open("GET", url); xhr.send(); } if (window.gpwj === undefined) { window.gpwj = {}; } gpwj.data = { load: loadData }; })(); gpwj.data.load("qiwizo", console.log); /* Further Adventures * * 1) Run the program. * * 2) Change the bin code to "pobapa" * and run the program again. * * 3) Declare a new function, outside * the IIFE, called numSessions. * * 4) Add statements to the function to * display the number of sessions for * the loaded user: * * "Mahesha has logged 3 sessions." * * 5) Replace console.log with numSessions * as the callback for the load function. * * 6) Run the program. * */
define({ "_widgetLabel": "Vodič za reakciju u hitnom slučaju", "ergMainPageTitle": "Zasnovan na vodiču za reakciju u hitnom slučaju 2016", "coordInputLabelStart": "Lokacija prolivanja", "coordInputLabel": "Lokacija prolivanja", "addPointToolTip": "Dodaj lokaciju prolivanja", "drawPointToolTip": "Kliknite da biste dodali lokaciju prolivanja", "material": "Materijal", "materialPlaceholder": "Počnite upisivanje da biste pretražili materijal", "table3Message": "Materijal koji ste izabrali zahteva dodatne informacije, ako se bavite velikim prolivanjem.\n\nVodite računa da izaberete tačne vrednosti za brzinu vetra i transportni kontejner.", "table2Message": "Materijal koji ste izabrali može da proizvede veliku količinu gasova koji predstavljaju opasnost od trovanja udisanjem, u slučaju prolivanja u vodu.\n\nRazmotrite korišćenje sledećih materijala:\n\n", "spillSize": "Veličina prolivanja", "small": "Malo", "large": "Veliko", "fireLabel": "Prikaži zonu za izolaciju požara", "weatherLabel": "Trenutni vremenski uslovi na lokaciji prolivanja", "weatherIntialText": "<br />Ažuriraju se kada se identifikuje lokacija prolivanja", "temperature": "Temperatura", "wind": "Vetar", "c": "C", "f": "F", "weatherErrorMessage": "Informacije o vremenskim uslovima nisu pribavljene. Ručno ažurirajte vrednosti za brzinu vetra i vreme prolivanja", "windDirection": "Smer vetra (duva ka)", "timeOfSpill": "Vreme prolivanja", "day": "Dan", "night": "Noć", "windSpeed": "Brzina vetra", "low": "Nisko", "moderate": "Umereno", "high": "Visoko", "transportContainer": "Transportni kontejner", "rail": "Vagon cisterna", "semi": "Kamion sa cisternom ili prikolica", "mton": "Višestruki teretni cilindri", "ston": "Višestruki mali cilindri ili jedan teretni cilindar", "ag": "Poljoprivredna cisterna za uzgoj", "msm": "Višestruki mali cilindri", "bleveLabel": "Prikaži BLEVE zonu za izolaciju", "capacity": "Kapacitet kontejnera (litara)", "bleveMessage": "Za materijal koji ste izabrali se može prikazati dodatno rastojanje za evakuaciju za BLEVE.\n\nDa biste to omogućili, uključite BLEVE zonu za izolaciju i izaberite odgovarajući kapacitet zone.", "noPAZoneMessage": "Za ovaj materijal ne postoje rastojanja za zaštitnu radnju. Proračunate su samo zone početne izolacije i evakuacije", "settingsTitle": "Postavke", "spillLocationLabel": "Lokacija prolivanja", "spillLocationButtonLabel": "Konfigurišite postavke za lokaciju prolivanja", "IISettingsLabel": "Zona početne izolacije", "IIButtonLabel": "Konfigurišite postavke za početnu izolaciju", "PASettingsLabel": "Zona zaštitne radnje", "PAButtonLabel": "Konfigurišite postavke za zaštitnu radnju", "downwindSettingsLabel": "Zona niz vetar", "downwindButtonLabel": "Konfigurišite postavke za niz vetar", "fireSettingsLabel": "Zona za izolaciju požara", "fireButtonLabel": "Konfigurišite postavke za izolaciju požara", "bleveSettingsLabel": "BLEVE zona za izolaciju", "bleveButtonLabel": "Konfigurišite BLEVE postavke", "style": "Stil", "lineStyles": { "esriSLSDash": "Crta", "esriSLSDashDot": "Crta tačka", "esriSLSDashDotDot": "Crta tačka tačka", "esriSLSDot": "Tačka", "esriSLSLongDash": "Duga crta", "esriSLSLongDashDot": "Duga crta tačka", "esriSLSNull": "Null", "esriSLSShortDash": "Kratka crta", "esriSLSShortDashDot": "Kratka crta tačka", "esriSLSShortDashDotDot": "Kratka crta tačka tačka", "esriSLSShortDot": "Kratka tačka", "esriSLSSolid": "Neprozirno" }, "fillStyles": { "esriSFSBackwardDiagonal": "Unazad", "esriSFSCross": "Krst", "esriSFSDiagonalCross": "Dijagonalno", "esriSFSForwardDiagonal": "Unapred", "esriSFSHorizontal": "Horizontalno", "esriSFSNull": "Null", "esriSFSSolid": "Neprozirno", "esriSFSVertical": "Vertikalno" }, "resultsTitle": "Rezultati", "publishERGBtn": "Objavi", "ERGLayerName": "Ime sloja objavljenog ERG", "invalidERGLayerName": "Ime sloja sme da sadrži samo alfanumeričke znakove i donje crte", "missingERGLayerName": "Morate da unesete ime za ERG", "publishingFailedLayerExists": "Objavljivanje nije uspelo: Već imate servis geoobjekata sa imenom {0}. Odaberite drugo ime.", "checkService": "Provera servisa: {0}", "createService": "Kreiranje servisa: {0}", "unableToCreate": "Kreiranje nije moguće: {0}", "addToDefinition": "Dodaj u definiciju: {0}", "successfullyPublished": "Uspešno objavljen veb sloj{0}Upravljaj veb slojem", "userRole": "Kreiranje servisa nije moguće, jer korisnik nema dozvole", "publishToNewLayer": "Objavi rezultate u novom sloju geoobjekata", "transparency": "Prozirnost", "outline": "Kontura", "fill": "Popuna (boja se primenjuje samo kada je stil podešen da bude neproziran)", "createERGBtn": "Kreiraj zone", "clearERGBtn": "Obriši", "labelFormat": "Format oznake", "helpIconTooltip": "Prag između male i velike veličine prolivanja iznosi:\nTečnosti – 55 galona (208 litara)\nČvrste materije – 60 funti (300 kilograma)", "cellWidth": "Širina ćelije (x)", "cellHeight": "Visina ćelije (y)", "invalidNumberMessage": "Uneta vrednost nije važeća", "invalidRangeMessage": "Vrednost mora da bude veća od 0", "gridAngleInvalidRangeMessage": "Vrednost mora da bude između -89,9 i 89,9", "formatIconTooltip": "Unos formata", "setCoordFormat": "Postavi nisku formata koordinata", "prefixNumbers": "Dodajte prefiks '+/-' pozitivnim i negativnim brojevima", "cancelBtn": "Otkaži", "applyBtn": "Primeni", "comfirmInputNotation": "Proverite unesenu oznaku", "notationsMatch": "oznake se podudaraju sa unosom potvrdite koje biste želeli da koristite:", "missingLayerNameMessage": "Morate da unesete važeće ime sloja da biste mogli da objavite", "parseCoordinatesError": "Raščlanjivanje koordinata nije moguće. Proverite unos.", "colorPicker": "Birač boja", "DD": "DD", "DDM": "DDM", "DMS": "DMS", "DDRev": "DDRev", "DDMRev": "DDMRev", "DMSRev": "DMSRev", "USNG": "USNG", "MGRS": "MGRS", "UTM_H": "Univerzalni Transverzalni Merkatorov koordinatni sistem (H)", "UTM": "Univerzalni Transverzalni Merkatorov koordinatni sistem (UTM)", "GARS": "GARS", "GEOREF": "GEOREF", "DDLatLongNotation": "Decimalni stepeni – geografska širina/dužina", "DDLongLatNotation": "Decimalni stepeni – geografska dužina/širina", "DDMLatLongNotation": "Decimalni stepeni minuti – geografska širina/dužina", "DDMLongLatNotation": "Decimalni stepeni minuti – geografska dužina/širina", "DMSLatLongNotation": "Decimalni stepeni sekundi – geografska širina/dužina", "DMSLongLatNotation": "Decimalni stepeni sekundi – geografska dužina/širina", "GARSNotation": "GARS", "GEOREFNotation": "GEOREF", "MGRSNotation": "MGRS", "USNGNotation": "USNG", "UTMBandNotation": "UTM – slovo opsega", "UTMHemNotation": "UTM – hemisfera (S/J)" });
version https://git-lfs.github.com/spec/v1 oid sha256:030a547508bd528d7a961986a7a1a199f76fe7f7dc734ddfe0989915501bad56 size 3243
/** * 通过node在电脑上创建一个HTTP的服务器 * 1 HTTP 只能接收HTTP请求 * 2 服务器 能在特定IP特定端口上监听客户端的连接 **/ var fs = require('fs'); // https://www.npmjs.com/package/mime //https://github.com/zhufengnodejs/2016jsnode var mime = require('mime'); var http = require('http');//核心模块,直接加载即可 //创建一个HTTP服务器,并在客户端连接到来的时候执行回应的回调函数 // request 代表客户端的请求,可以从中读取请求中的数据 // response 代表向客户端发的响应 可以通过它向客户端发响应 /** * 不要重复自己 Don't repeat yourself * 1. 代码量会很多 * 2. 如果要修改重构的话修改的地方很多 * 3. 时间多,容易出错 */ /** * 全局安装 一次安装,到处在CMD使用, * 本地安装 一次安装,只能在当前目录下面用,在代码中通过 require加载使用 */ http.createServer(function(request,response){ console.log(request.url); //先对url进行解码,把转义后的中文字符转回中文 request.url = decodeURIComponent(request.url); //如果url等于/content的话 if(request.url == '/content'){ response.end('hello');//在响应体中返回hello }else{ //先判断文件是否存在,如果存在读出来返回给客户端 fs.exists('.'+request.url,function(exists){ if(exists){ //增加响应头,告诉浏览器响应的类型是什么 response.setHeader('Content-Type',mime.lookup(request.url)); //读取文件并且返回写给响应 fs.readFile('.'+request.url,function(err,data){ response.end(data); }) }else{ response.setHeader('Content-Type','text/html;charset=utf-8'); response.statusCode = 404;//设置响应码为404 Not Found response.end('你要的资源不存在');//设置响应体 } }) } //listen EADDRINUSE 端口号被占用 }).listen(9090);//在本机的9090端口上进行监听 /** * 运行在服务器端,就是不发送给客户端浏览器运行的就叫服务器端代码 * 发送给浏览器,在浏览器中运行的代码就叫客户端代码 * **/
'use strict'; const castFilterPath = require('../query/castFilterPath'); const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); const getPath = require('../schema/getPath'); const modifiedPaths = require('./modifiedPaths'); module.exports = function castArrayFilters(query) { const arrayFilters = query.options.arrayFilters; if (!Array.isArray(arrayFilters)) { return; } const update = query.getUpdate(); const schema = query.schema; const strictQuery = schema.options.strictQuery; const updatedPaths = modifiedPaths(update); const updatedPathsByFilter = Object.keys(updatedPaths).reduce((cur, path) => { const matches = path.match(/\$\[[^\]]+\]/g); if (matches == null) { return cur; } for (const match of matches) { const firstMatch = path.indexOf(match); if (firstMatch !== path.lastIndexOf(match)) { throw new Error(`Path '${path}' contains the same array filter multiple times`); } cur[match.substring(2, match.length - 1)] = path. substr(0, firstMatch - 1). replace(/\$\[[^\]]+\]/g, '0'); } return cur; }, {}); for (const filter of arrayFilters) { if (filter == null) { throw new Error(`Got null array filter in ${arrayFilters}`); } const firstKey = Object.keys(filter)[0]; if (filter[firstKey] == null) { continue; } const dot = firstKey.indexOf('.'); let filterPath = dot === -1 ? updatedPathsByFilter[firstKey] + '.0' : updatedPathsByFilter[firstKey.substr(0, dot)] + '.0' + firstKey.substr(dot); if (filterPath == null) { throw new Error(`Filter path not found for ${firstKey}`); } // If there are multiple array filters in the path being updated, make sure // to replace them so we can get the schema path. filterPath = cleanPositionalOperators(filterPath); const schematype = getPath(schema, filterPath); if (schematype == null) { if (!strictQuery) { return; } // For now, treat `strictQuery = true` and `strictQuery = 'throw'` as // equivalent for casting array filters. `strictQuery = true` doesn't // quite work in this context because we never want to silently strip out // array filters, even if the path isn't in the schema. throw new Error(`Could not find path "${filterPath}" in schema`); } if (typeof filter[firstKey] === 'object') { filter[firstKey] = castFilterPath(query, schematype, filter[firstKey]); } else { filter[firstKey] = schematype.castForQuery(filter[firstKey]); } } };
/** * $Id: editor_plugin_src.js 6572 2009-02-25 02:46:35Z Garbin $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { tinymce.create('tinymce.plugins.Save', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceSave', t._save, t); ed.addCommand('mceCancel', t._cancel, t); // Register buttons ed.addButton('save', {title : 'save.save_desc', cmd : 'mceSave'}); ed.addButton('cancel', {title : 'save.cancel_desc', cmd : 'mceCancel'}); ed.onNodeChange.add(t._nodeChange, t); ed.addShortcut('ctrl+s', ed.getLang('save.save_desc'), 'mceSave'); }, getInfo : function() { return { longname : 'Save', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/save', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var ed = this.editor; if (ed.getParam('save_enablewhendirty')) { cm.setDisabled('save', !ed.isDirty()); cm.setDisabled('cancel', !ed.isDirty()); } }, // Private methods _save : function() { var ed = this.editor, formObj, os, i, elementId; formObj = tinymce.DOM.get(ed.id).form || tinymce.DOM.getParent(ed.id, 'form'); if (ed.getParam("save_enablewhendirty") && !ed.isDirty()) return; tinyMCE.triggerSave(); // Use callback instead if (os = ed.getParam("save_onsavecallback")) { if (ed.execCallback('save_onsavecallback', ed)) { ed.startContent = tinymce.trim(ed.getContent({format : 'raw'})); ed.nodeChanged(); } return; } if (formObj) { ed.isNotDirty = true; if (formObj.onsubmit == null || formObj.onsubmit() != false) formObj.submit(); ed.nodeChanged(); } else ed.windowManager.alert("Error: No form element found."); }, _cancel : function() { var ed = this.editor, os, h = tinymce.trim(ed.startContent); // Use callback instead if (os = ed.getParam("save_oncancelcallback")) { ed.execCallback('save_oncancelcallback', ed); return; } ed.setContent(h); ed.undoManager.clear(); ed.nodeChanged(); } }); // Register plugin tinymce.PluginManager.add('save', tinymce.plugins.Save); })();
var fs = require('fs'); var nomnom = require('nomnom'); var Compiler = require('angular-gettext-tools').Compiler; function main(inputs) { var compiler = new Compiler({format: 'json'}); var contents = []; inputs.forEach(function(input) { // ignore un existing files fs.exists(input, function(exists) { if (exists) { fs.readFile(input, {encoding: 'utf-8'}, function(err, content) { if (!err) { contents.push(content); if (contents.length === inputs.length) { process.stdout.write(compiler.convertPo(contents.filter(function (content) { return content.length !== 0; }))); } } }); } else { contents.push("") } }); }); } // If running this module directly then call the main function. if (require.main === module) { var options = nomnom.parse(); var inputs = options._; main(inputs); } module.exports = main;
/** * $Id: editor_template_src.js 6566 2009-02-24 10:44:41Z Garbin $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode; // Tell it to load theme specific language pack(s) tinymce.ThemeManager.requireLangPack('advanced'); tinymce.create('tinymce.themes.AdvancedTheme', { sizes : [8, 10, 12, 14, 18, 24, 36], // Control name lookup, format: title, command controls : { bold : ['bold_desc', 'Bold'], italic : ['italic_desc', 'Italic'], underline : ['underline_desc', 'Underline'], strikethrough : ['striketrough_desc', 'Strikethrough'], justifyleft : ['justifyleft_desc', 'JustifyLeft'], justifycenter : ['justifycenter_desc', 'JustifyCenter'], justifyright : ['justifyright_desc', 'JustifyRight'], justifyfull : ['justifyfull_desc', 'JustifyFull'], bullist : ['bullist_desc', 'InsertUnorderedList'], numlist : ['numlist_desc', 'InsertOrderedList'], outdent : ['outdent_desc', 'Outdent'], indent : ['indent_desc', 'Indent'], cut : ['cut_desc', 'Cut'], copy : ['copy_desc', 'Copy'], paste : ['paste_desc', 'Paste'], undo : ['undo_desc', 'Undo'], redo : ['redo_desc', 'Redo'], link : ['link_desc', 'mceLink'], unlink : ['unlink_desc', 'unlink'], image : ['image_desc', 'mceImage'], cleanup : ['cleanup_desc', 'mceCleanup'], help : ['help_desc', 'mceHelp'], code : ['code_desc', 'mceCodeEditor'], hr : ['hr_desc', 'InsertHorizontalRule'], removeformat : ['removeformat_desc', 'RemoveFormat'], sub : ['sub_desc', 'subscript'], sup : ['sup_desc', 'superscript'], forecolor : ['forecolor_desc', 'ForeColor'], forecolorpicker : ['forecolor_desc', 'mceForeColor'], backcolor : ['backcolor_desc', 'HiliteColor'], backcolorpicker : ['backcolor_desc', 'mceBackColor'], charmap : ['charmap_desc', 'mceCharMap'], visualaid : ['visualaid_desc', 'mceToggleVisualAid'], anchor : ['anchor_desc', 'mceInsertAnchor'], newdocument : ['newdocument_desc', 'mceNewDocument'], blockquote : ['blockquote_desc', 'mceBlockQuote'] }, stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'], init : function(ed, url) { var t = this, s, v, o; t.editor = ed; t.url = url; t.onResolveName = new tinymce.util.Dispatcher(this); // Default settings t.settings = s = extend({ theme_advanced_path : true, theme_advanced_toolbar_location : 'bottom', theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code", theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap", theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6", theme_advanced_toolbar_align : "center", theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats", theme_advanced_more_colors : 1, theme_advanced_row_height : 23, theme_advanced_resize_horizontal : 1, theme_advanced_resizing_use_cookie : 1, theme_advanced_font_sizes : "1,2,3,4,5,6,7", readonly : ed.settings.readonly }, ed.settings); // Setup default font_size_style_values if (!s.font_size_style_values) s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt"; if (tinymce.is(s.theme_advanced_font_sizes, 'string')) { s.font_size_style_values = tinymce.explode(s.font_size_style_values); s.font_size_classes = tinymce.explode(s.font_size_classes || ''); // Parse string value o = {}; ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes; each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) { var cl; if (k == v && v >= 1 && v <= 7) { k = v + ' (' + t.sizes[v - 1] + 'pt)'; if (ed.settings.convert_fonts_to_spans) { cl = s.font_size_classes[v - 1]; v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt'); } } if (/\s*\./.test(v)) cl = v.replace(/\./g, ''); o[k] = cl ? {'class' : cl} : {fontSize : v}; }); s.theme_advanced_font_sizes = o; } if ((v = s.theme_advanced_path_location) && v != 'none') s.theme_advanced_statusbar_location = s.theme_advanced_path_location; if (s.theme_advanced_statusbar_location == 'none') s.theme_advanced_statusbar_location = 0; // Init editor ed.onInit.add(function() { ed.onNodeChange.add(t._nodeChanged, t); if (ed.settings.content_css !== false) ed.dom.loadCSS(ed.baseURI.toAbsolute("themes/advanced/skins/" + ed.settings.skin + "/content.css")); }); ed.onSetProgressState.add(function(ed, b, ti) { var co, id = ed.id, tb; if (b) { t.progressTimer = setTimeout(function() { co = ed.getContainer(); co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild); tb = DOM.get(ed.id + '_tbl'); DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}}); DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}}); }, ti || 0); } else { DOM.remove(id + '_blocker'); DOM.remove(id + '_progress'); clearTimeout(t.progressTimer); } }); DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css"); if (s.skin_variant) DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css"); }, createControl : function(n, cf) { var cd, c; if (c = cf.createControl(n)) return c; switch (n) { case "styleselect": return this._createStyleSelect(); case "formatselect": return this._createBlockFormats(); case "fontselect": return this._createFontSelect(); case "fontsizeselect": return this._createFontSizeSelect(); case "forecolor": return this._createForeColorMenu(); case "backcolor": return this._createBackColorMenu(); } if ((cd = this.controls[n])) return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]}); }, execCommand : function(cmd, ui, val) { var f = this['_' + cmd]; if (f) { f.call(this, ui, val); return true; } return false; }, _importClasses : function(e) { var ed = this.editor, c = ed.controlManager.get('styleselect'); if (c.getLength() == 0) { each(ed.dom.getClasses(), function(o) { c.add(o['class'], o['class']); }); } }, _createStyleSelect : function(n) { var t = this, ed = t.editor, cf = ed.controlManager, c = cf.createListBox('styleselect', { title : 'advanced.style_select', onselect : function(v) { if (c.selectedValue === v) { ed.execCommand('mceSetStyleInfo', 0, {command : 'removeformat'}); c.select(); return false; } else ed.execCommand('mceSetCSSClass', 0, v); } }); if (c) { each(ed.getParam('theme_advanced_styles', '', 'hash'), function(v, k) { if (v) c.add(t.editor.translate(k), v); }); c.onPostRender.add(function(ed, n) { if (!c.NativeListBox) { Event.add(n.id + '_text', 'focus', t._importClasses, t); Event.add(n.id + '_text', 'mousedown', t._importClasses, t); Event.add(n.id + '_open', 'focus', t._importClasses, t); Event.add(n.id + '_open', 'mousedown', t._importClasses, t); } else Event.add(n.id, 'focus', t._importClasses, t); }); } return c; }, _createFontSelect : function() { var c, t = this, ed = t.editor; c = ed.controlManager.createListBox('fontselect', {title : 'advanced.fontdefault', cmd : 'FontName'}); if (c) { each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) { c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''}); }); } return c; }, _createFontSizeSelect : function() { var t = this, ed = t.editor, c, i = 0, cl = []; c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) { if (v.fontSize) ed.execCommand('FontSize', false, v.fontSize); else { each(t.settings.theme_advanced_font_sizes, function(v, k) { if (v['class']) cl.push(v['class']); }); ed.editorCommands._applyInlineStyle('span', {'class' : v['class']}, {check_classes : cl}); } }}); if (c) { each(t.settings.theme_advanced_font_sizes, function(v, k) { var fz = v.fontSize; if (fz >= 1 && fz <= 7) fz = t.sizes[parseInt(fz) - 1] + 'pt'; c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))}); }); } return c; }, _createBlockFormats : function() { var c, fmts = { p : 'advanced.paragraph', address : 'advanced.address', pre : 'advanced.pre', h1 : 'advanced.h1', h2 : 'advanced.h2', h3 : 'advanced.h3', h4 : 'advanced.h4', h5 : 'advanced.h5', h6 : 'advanced.h6', div : 'advanced.div', blockquote : 'advanced.blockquote', code : 'advanced.code', dt : 'advanced.dt', dd : 'advanced.dd', samp : 'advanced.samp' }, t = this; c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', cmd : 'FormatBlock'}); if (c) { each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) { c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v}); }); } return c; }, _createForeColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_text_colors) o.colors = v; if (s.theme_advanced_default_foreground_color) o.default_color = s.theme_advanced_default_foreground_color; o.title = 'advanced.forecolor_desc'; o.cmd = 'ForeColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('forecolor', o); return c; }, _createBackColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_background_colors) o.colors = v; if (s.theme_advanced_default_background_color) o.default_color = s.theme_advanced_default_background_color; o.title = 'advanced.backcolor_desc'; o.cmd = 'HiliteColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('backcolor', o); return c; }, renderUI : function(o) { var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl; n = p = DOM.create('span', {id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '')}); if (!DOM.boxModel) n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'}); n = sc = DOM.add(n, 'table', {id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0}); n = tb = DOM.add(n, 'tbody'); switch ((s.theme_advanced_layout_manager || '').toLowerCase()) { case "rowlayout": ic = t._rowLayout(s, tb, o); break; case "customlayout": ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p); break; default: ic = t._simpleLayout(s, tb, o, p); } n = o.targetNode; // Add classes to first and last TRs nl = DOM.stdMode ? sc.getElementsByTagName('tr') : sc.rows; // Quick fix for IE 8 DOM.addClass(nl[0], 'mceFirst'); DOM.addClass(nl[nl.length - 1], 'mceLast'); // Add classes to first and last TDs each(DOM.select('tr', tb), function(n) { DOM.addClass(n.firstChild, 'mceFirst'); DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast'); }); if (DOM.get(s.theme_advanced_toolbar_container)) DOM.get(s.theme_advanced_toolbar_container).appendChild(p); else DOM.insertAfter(p, n); Event.add(ed.id + '_path_row', 'click', function(e) { e = e.target; if (e.nodeName == 'A') { t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1')); return Event.cancel(e); } }); /* if (DOM.get(ed.id + '_path_row')) { Event.add(ed.id + '_tbl', 'mouseover', function(e) { var re; e = e.target; if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) { re = DOM.get(ed.id + '_path_row'); t.lastPath = re.innerHTML; DOM.setHTML(re, e.parentNode.title); } }); Event.add(ed.id + '_tbl', 'mouseout', function(e) { if (t.lastPath) { DOM.setHTML(ed.id + '_path_row', t.lastPath); t.lastPath = 0; } }); } */ if (!ed.getParam('accessibility_focus') || ed.getParam('tab_focus')) Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();}); if (s.theme_advanced_toolbar_location == 'external') o.deltaHeight = 0; t.deltaHeight = o.deltaHeight; o.targetNode = null; return { iframeContainer : ic, editorContainer : ed.id + '_parent', sizeContainer : sc, deltaHeight : o.deltaHeight }; }, getInfo : function() { return { longname : 'Advanced theme', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', version : tinymce.majorVersion + "." + tinymce.minorVersion } }, resizeBy : function(dw, dh) { var e = DOM.get(this.editor.id + '_tbl'); this.resizeTo(e.clientWidth + dw, e.clientHeight + dh); }, resizeTo : function(w, h) { var ed = this.editor, s = ed.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr'), dh; // Boundery fix box w = Math.max(s.theme_advanced_resizing_min_width || 100, w); h = Math.max(s.theme_advanced_resizing_min_height || 100, h); w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w); h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h); // Calc difference between iframe and container dh = e.clientHeight - ifr.clientHeight; // Resize iframe and container DOM.setStyle(ifr, 'height', h - dh); DOM.setStyles(e, {width : w, height : h}); }, destroy : function() { var id = this.editor.id; Event.clear(id + '_resize'); Event.clear(id + '_path_row'); Event.clear(id + '_external_close'); }, // Internal functions _simpleLayout : function(s, tb, o, p) { var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c; if (s.readonly) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); return ic; } // Create toolbar container at top if (lo == 'top') t._addToolbars(tb, o); // Create external toolbar if (lo == 'external') { n = c = DOM.create('div', {style : 'position:relative'}); n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'}); DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'}); n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0}); etb = DOM.add(n, 'tbody'); if (p.firstChild.className == 'mceOldBoxModel') p.firstChild.appendChild(c); else p.insertBefore(c, p.firstChild); t._addToolbars(etb, o); ed.onMouseUp.add(function() { var e = DOM.get(ed.id + '_external'); DOM.show(e); DOM.hide(lastExtID); var f = Event.add(ed.id + '_external_close', 'click', function() { DOM.hide(ed.id + '_external'); Event.remove(ed.id + '_external_close', 'click', f); }); DOM.show(e); DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1); // Fixes IE rendering bug DOM.hide(e); DOM.show(e); e.style.filter = ''; lastExtID = ed.id + '_external'; e = null; }); } if (sl == 'top') t._addStatusBar(tb, o); // Create iframe container if (!s.theme_advanced_toolbar_container) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); } // Create toolbar container at bottom if (lo == 'bottom') t._addToolbars(tb, o); if (sl == 'bottom') t._addStatusBar(tb, o); return ic; }, _rowLayout : function(s, tb, o) { var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a; dc = s.theme_advanced_containers_default_class || ''; da = s.theme_advanced_containers_default_align || 'center'; each(explode(s.theme_advanced_containers || ''), function(c, i) { var v = s['theme_advanced_container_' + c] || ''; switch (v.toLowerCase()) { case 'mceeditor': n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); break; case 'mceelementpath': t._addStatusBar(tb, o); break; default: a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(tb, 'tr'), 'td', { 'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da }); to = cf.createToolbar("toolbar" + i); t._addControls(v, to); DOM.setHTML(n, to.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } }); return ic; }, _addControls : function(v, tb) { var t = this, s = t.settings, di, cf = t.editor.controlManager; if (s.theme_advanced_disable && !t._disabled) { di = {}; each(explode(s.theme_advanced_disable), function(v) { di[v] = 1; }); t._disabled = di; } else di = t._disabled; each(explode(v), function(n) { var c; if (di && di[n]) return; // Compatiblity with 2.x if (n == 'tablecontrols') { each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) { n = t.createControl(n, cf); if (n) tb.add(n); }); return; } c = t.createControl(n, cf); if (c) tb.add(c); }); }, _addToolbars : function(c, o) { var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a; a = s.theme_advanced_toolbar_align.toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(c, 'tr'), 'td', {'class' : 'mceToolbar ' + a}); if (!ed.getParam('accessibility_focus') || ed.getParam('tab_focus')) h.push(DOM.createHTML('a', {href : '#', onfocus : 'tinyMCE.get(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); h.push(DOM.createHTML('a', {href : '#', accesskey : 'q', title : ed.getLang("advanced.toolbar_focus")}, '<!-- IE -->')); // Create toolbar and add the controls for (i=1; (v = s['theme_advanced_buttons' + i]); i++) { tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i}); if (s['theme_advanced_buttons' + i + '_add']) v += ',' + s['theme_advanced_buttons' + i + '_add']; if (s['theme_advanced_buttons' + i + '_add_before']) v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v; t._addControls(v, tb); //n.appendChild(n = tb.render()); h.push(tb.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); DOM.setHTML(n, h.join('')); }, _addStatusBar : function(tb, o) { var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td; n = DOM.add(tb, 'tr'); n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'}); n = DOM.add(n, 'div', {id : ed.id + '_path_row'}, s.theme_advanced_path ? ed.translate('advanced.path') + ': ' : '&nbsp;'); DOM.add(n, 'a', {href : '#', accesskey : 'x'}); if (s.theme_advanced_resizing && !tinymce.isOldWebKit) { DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize'}); if (s.theme_advanced_resizing_use_cookie) { ed.onPostRender.add(function() { var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl'); if (!o) return; if (s.theme_advanced_resize_horizontal) c.style.width = Math.max(10, o.cw) + 'px'; c.style.height = Math.max(10, o.ch) + 'px'; DOM.get(ed.id + '_ifr').style.height = Math.max(10, parseInt(o.ch) + t.deltaHeight) + 'px'; }); } ed.onPostRender.add(function() { Event.add(ed.id + '_resize', 'mousedown', function(e) { var c, p, w, h, n, pa; // Measure container c = DOM.get(ed.id + '_tbl'); w = c.clientWidth; h = c.clientHeight; miw = s.theme_advanced_resizing_min_width || 100; mih = s.theme_advanced_resizing_min_height || 100; maw = s.theme_advanced_resizing_max_width || 0xFFFF; mah = s.theme_advanced_resizing_max_height || 0xFFFF; // Setup placeholder p = DOM.add(DOM.get(ed.id + '_parent'), 'div', {'class' : 'mcePlaceHolder'}); DOM.setStyles(p, {width : w, height : h}); // Replace with placeholder DOM.hide(c); DOM.show(p); // Create internal resize obj r = { x : e.screenX, y : e.screenY, w : w, h : h, dx : null, dy : null }; // Start listening mf = Event.add(DOM.doc, 'mousemove', function(e) { var w, h; // Calc delta values r.dx = e.screenX - r.x; r.dy = e.screenY - r.y; // Boundery fix box w = Math.max(miw, r.w + r.dx); h = Math.max(mih, r.h + r.dy); w = Math.min(maw, w); h = Math.min(mah, h); // Resize placeholder if (s.theme_advanced_resize_horizontal) p.style.width = w + 'px'; p.style.height = h + 'px'; return Event.cancel(e); }); me = Event.add(DOM.doc, 'mouseup', function(e) { var ifr; // Stop listening Event.remove(DOM.doc, 'mousemove', mf); Event.remove(DOM.doc, 'mouseup', me); c.style.display = ''; DOM.remove(p); if (r.dx === null) return; ifr = DOM.get(ed.id + '_ifr'); if (s.theme_advanced_resize_horizontal) c.style.width = Math.max(10, r.w + r.dx) + 'px'; c.style.height = Math.max(10, r.h + r.dy) + 'px'; ifr.style.height = Math.max(10, ifr.clientHeight + r.dy) + 'px'; if (s.theme_advanced_resizing_use_cookie) { Cookie.setHash("TinyMCE_" + ed.id + "_size", { cw : r.w + r.dx, ch : r.h + r.dy }); } }); return Event.cancel(e); }); }); } o.deltaHeight -= 21; n = tb = null; }, _nodeChanged : function(ed, cm, n, co) { var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn; if (s.readonly) return; tinymce.each(t.stateControls, function(c) { cm.setActive(c, ed.queryCommandState(t.controls[c][1])); }); cm.setActive('visualaid', ed.hasVisual); cm.setDisabled('undo', !ed.undoManager.hasUndo() && !ed.typing); cm.setDisabled('redo', !ed.undoManager.hasRedo()); cm.setDisabled('outdent', !ed.queryCommandState('Outdent')); p = DOM.getParent(n, 'A'); if (c = cm.get('link')) { if (!p || !p.name) { c.setDisabled(!p && co); c.setActive(!!p); } } if (c = cm.get('unlink')) { c.setDisabled(!p && co); c.setActive(!!p && !p.name); } if (c = cm.get('anchor')) { c.setActive(!!p && p.name); if (tinymce.isWebKit) { p = DOM.getParent(n, 'IMG'); c.setActive(!!p && DOM.getAttrib(p, 'mce_name') == 'a'); } } p = DOM.getParent(n, 'IMG'); if (c = cm.get('image')) c.setActive(!!p && n.className.indexOf('mceItem') == -1); if (c = cm.get('styleselect')) { if (n.className) { t._importClasses(); c.select(n.className); } else c.select(); } if (c = cm.get('formatselect')) { p = DOM.getParent(n, DOM.isBlock); if (p) c.select(p.nodeName.toLowerCase()); } if (ed.settings.convert_fonts_to_spans) { ed.dom.getParent(n, function(n) { if (n.nodeName === 'SPAN') { if (!cl && n.className) cl = n.className; if (!fz && n.style.fontSize) fz = n.style.fontSize; if (!fn && n.style.fontFamily) fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase(); } return false; }); if (c = cm.get('fontselect')) { c.select(function(v) { return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn; }); } if (c = cm.get('fontsizeselect')) { c.select(function(v) { if (v.fontSize && v.fontSize === fz) return true; if (v['class'] && v['class'] === cl) return true; }); } } else { if (c = cm.get('fontselect')) c.select(ed.queryCommandValue('FontName')); if (c = cm.get('fontsizeselect')) { v = ed.queryCommandValue('FontSize'); c.select(function(iv) { return iv.fontSize == v; }); } } if (s.theme_advanced_path && s.theme_advanced_statusbar_location) { p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'}); DOM.setHTML(p, ''); ed.dom.getParent(n, function(n) { var na = n.nodeName.toLowerCase(), u, pi, ti = ''; // Ignore non element and hidden elements if (n.nodeType != 1 || n.nodeName === 'BR' || (DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved'))) return; // Fake name if (v = DOM.getAttrib(n, 'mce_name')) na = v; // Handle prefix if (tinymce.isIE && n.scopeName !== 'HTML') na = n.scopeName + ':' + na; // Remove internal prefix na = na.replace(/mce\:/g, ''); // Handle node name switch (na) { case 'b': na = 'strong'; break; case 'i': na = 'em'; break; case 'img': if (v = DOM.getAttrib(n, 'src')) ti += 'src: ' + v + ' '; break; case 'a': if (v = DOM.getAttrib(n, 'name')) { ti += 'name: ' + v + ' '; na += '#' + v; } if (v = DOM.getAttrib(n, 'href')) ti += 'href: ' + v + ' '; break; case 'font': if (s.convert_fonts_to_spans) na = 'span'; if (v = DOM.getAttrib(n, 'face')) ti += 'font: ' + v + ' '; if (v = DOM.getAttrib(n, 'size')) ti += 'size: ' + v + ' '; if (v = DOM.getAttrib(n, 'color')) ti += 'color: ' + v + ' '; break; case 'span': if (v = DOM.getAttrib(n, 'style')) ti += 'style: ' + v + ' '; break; } if (v = DOM.getAttrib(n, 'id')) ti += 'id: ' + v + ' '; if (v = n.className) { v = v.replace(/(webkit-[\w\-]+|Apple-[\w\-]+|mceItem\w+|mceVisualAid)/g, ''); if (v && v.indexOf('mceItem') == -1) { ti += 'class: ' + v + ' '; if (DOM.isBlock(n) || na == 'img' || na == 'span') na += '.' + v; } } na = na.replace(/(html:)/g, ''); na = {name : na, node : n, title : ti}; t.onResolveName.dispatch(t, na); ti = na.title; na = na.name; //u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');"; pi = DOM.create('a', {'href' : "javascript:;", onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na); if (p.hasChildNodes()) { p.insertBefore(DOM.doc.createTextNode(' \u00bb '), p.firstChild); p.insertBefore(pi, p.firstChild); } else p.appendChild(pi); }, ed.getBody()); } }, // Commands gets called by execCommand _sel : function(v) { this.editor.execCommand('mceSelectNodeDepth', false, v); }, _mceInsertAnchor : function(ui, v) { var ed = this.editor; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/anchor.htm', width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)), height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceCharMap : function() { var ed = this.editor; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/charmap.htm', width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceHelp : function() { var ed = this.editor; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/about.htm', width : 480, height : 380, inline : true }, { theme_url : this.url }); }, _mceColorPicker : function(u, v) { var ed = this.editor; v = v || {}; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/color_picker.htm', width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)), close_previous : false, inline : true }, { input_color : v.color, func : v.func, theme_url : this.url }); }, _mceCodeEditor : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/source_editor.htm', width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)), height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)), inline : true, resizable : true, maximizable : true }, { theme_url : this.url }); }, _mceImage : function(ui, val) { var ed = this.editor; // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/image.htm', width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)), height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceLink : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : tinymce.baseURL + '/themes/advanced/link.htm', width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)), height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceNewDocument : function() { var ed = this.editor; ed.windowManager.confirm('advanced.newdocument', function(s) { if (s) ed.execCommand('mceSetContent', false, ''); }); }, _mceForeColor : function() { var t = this; this._mceColorPicker(0, { color: t.fgColor, func : function(co) { t.fgColor = co; t.editor.execCommand('ForeColor', false, co); } }); }, _mceBackColor : function() { var t = this; this._mceColorPicker(0, { color: t.bgColor, func : function(co) { t.bgColor = co; t.editor.execCommand('HiliteColor', false, co); } }); }, _ufirst : function(s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }); tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme); }());
//require('./common'); require("./lib/digest.js"); exports["md5"] = function(test) { test.assert }; var files = ["smalltext", "dictionary", "cat.jpg", "oranga_thumb.jpg"]; files.forEach(function (file) { var disc_filename = path.join(settings.default_host.root, file); var fileText = fs.readFileSync(disc_filename, 'binary'); exports[file] = function(test) { antinode.start(settings, function() { test_http(test, {'method':'GET','pathname':'/'+file}, {'statusCode':200,'body':fileText}, function() { antinode.stop(); test.done(); }); }); }; });
/** * Generated bundle index. Do not edit. */ export * from './index'; export { SpecialCasedStyles as ɵangular_packages_animations_browser_browser_a } from './src/render/special_cased_styles'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnJvd3Nlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2FuaW1hdGlvbnMvYnJvd3Nlci9icm93c2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBRUgsY0FBYyxTQUFTLENBQUM7QUFFeEIsT0FBTyxFQUFDLGtCQUFrQixJQUFJLDhDQUE4QyxFQUFDLE1BQU0sbUNBQW1DLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEdlbmVyYXRlZCBidW5kbGUgaW5kZXguIERvIG5vdCBlZGl0LlxuICovXG5cbmV4cG9ydCAqIGZyb20gJy4vaW5kZXgnO1xuXG5leHBvcnQge1NwZWNpYWxDYXNlZFN0eWxlcyBhcyDJtWFuZ3VsYXJfcGFja2FnZXNfYW5pbWF0aW9uc19icm93c2VyX2Jyb3dzZXJfYX0gZnJvbSAnLi9zcmMvcmVuZGVyL3NwZWNpYWxfY2FzZWRfc3R5bGVzJzsiXX0=
/** * @fileoverview Rule to flag use of an empty block statement * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow empty block statements", category: "Possible Errors", recommended: true }, schema: [ { type: "object", properties: { allowEmptyCatch: { type: "boolean" } }, additionalProperties: false } ] }, create: function(context) { const options = context.options[0] || {}, allowEmptyCatch = options.allowEmptyCatch || false; const sourceCode = context.getSourceCode(); return { BlockStatement: function(node) { // if the body is not empty, we can just return immediately if (node.body.length !== 0) { return; } // a function is generally allowed to be empty if (astUtils.isFunction(node.parent)) { return; } if (allowEmptyCatch && node.parent.type === "CatchClause") { return; } // any other block is only allowed to be empty, if it contains a comment if (sourceCode.getComments(node).trailing.length > 0) { return; } context.report(node, "Empty block statement."); }, SwitchStatement: function(node) { if (typeof node.cases === "undefined" || node.cases.length === 0) { context.report(node, "Empty switch statement."); } } }; } };
module.exports = function allowCrossDomain (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,POST'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); };
angular.module( 'ngbps.shopGateway.checkout', [ 'ui.router' ]) .config(function config( $stateProvider ) { $stateProvider.state( 'checkout', { url: '/checkout', views: { "main": { controller: 'CheckoutCtrl', templateUrl: 'shopGateway/checkout.tpl.html' } } }); }) .controller( 'CheckoutCtrl', function CheckoutController( $scope, $window, Checkout, ShoppingCart, Products, worldPayGateway) { $scope.cart = ShoppingCart; $scope.$watch(Checkout.getItemCount, function(count, lastCount){ if (!count){ $scope.continueShopping(); return; } Checkout.runItems(function(itemId){ return Products.getProduct(itemId).then(function(product){ return { id:itemId, title: product.title, imageUrl: product.imageUrl, price: product.price }; }); }) .then(function(checkoutSlip){ $scope.checkout=checkoutSlip; }); }); $scope.continueShopping = function(){ $window.history.back(); }; $scope.payNow = function(){ $scope.gatewayOpen=true; worldPayGateway.pay($scope.checkout); }; }) ;
Lawnchair.adapter('webkit-sqlite', (function () { // private methods var fail = function (e, i) { console.log('error in sqlite adaptor!', e, i) } , now = function () { return new Date() } // FIXME need to use better date fn // not entirely sure if this is needed... if (!Function.prototype.bind) { Function.prototype.bind = function( obj ) { var slice = [].slice , args = slice.call(arguments, 1) , self = this , nop = function () {} , bound = function () { return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments))) } nop.prototype = self.prototype bound.prototype = new nop() return bound } } // public methods return { valid: function() { return !!(window.openDatabase) }, init: function (options, callback) { var that = this , cb = that.fn(that.name, callback) , create = "CREATE TABLE IF NOT EXISTS " + this.record + " (id NVARCHAR(32) UNIQUE PRIMARY KEY, value TEXT, timestamp REAL)" , win = function(){ return cb.call(that, that); } // open a connection and create the db if it doesn't exist this.db = openDatabase(this.name, '1.0.0', this.name, 65536) this.db.transaction(function (t) { t.executeSql(create, [], win, fail) }) }, keys: function (callback) { var cb = this.lambda(callback) , that = this , keys = "SELECT id FROM " + this.record + " ORDER BY timestamp DESC" this.db.readTransaction(function(t) { var win = function (xxx, results) { if (results.rows.length == 0 ) { cb.call(that, []) } else { var r = []; for (var i = 0, l = results.rows.length; i < l; i++) { r.push(results.rows.item(i).id); } cb.call(that, r) } } t.executeSql(keys, [], win, fail) }) return this }, // you think thats air you're breathing now? save: function (obj, callback, error) { var that = this , objs = (this.isArray(obj) ? obj : [obj]).map(function(o){if(!o.key) { o.key = that.uuid()} return o}) , ins = "INSERT OR REPLACE INTO " + this.record + " (value, timestamp, id) VALUES (?,?,?)" , win = function () { if (callback) { that.lambda(callback).call(that, that.isArray(obj)?objs:objs[0]) }} , error= error || function() {} , insvals = [] , ts = now() try { for (var i = 0, l = objs.length; i < l; i++) { insvals[i] = [JSON.stringify(objs[i]), ts, objs[i].key]; } } catch (e) { fail(e) throw e; } that.db.transaction(function(t) { for (var i = 0, l = objs.length; i < l; i++) t.executeSql(ins, insvals[i]) }, function(e,i){fail(e,i)}, win) return this }, batch: function (objs, callback) { return this.save(objs, callback) }, get: function (keyOrArray, cb) { var that = this , sql = '' , args = this.isArray(keyOrArray) ? keyOrArray : [keyOrArray]; // batch selects support sql = 'SELECT id, value FROM ' + this.record + " WHERE id IN (" + args.map(function(){return '?'}).join(",") + ")" // FIXME // will always loop the results but cleans it up if not a batch return at the end.. // in other words, this could be faster var win = function (xxx, results) { var o , r , lookup = {} // map from results to keys for (var i = 0, l = results.rows.length; i < l; i++) { o = JSON.parse(results.rows.item(i).value) o.key = results.rows.item(i).id lookup[o.key] = o; } r = args.map(function(key) { return lookup[key]; }); if (!that.isArray(keyOrArray)) r = r.length ? r[0] : null if (cb) that.lambda(cb).call(that, r) } this.db.readTransaction(function(t){ t.executeSql(sql, args, win, fail) }) return this }, exists: function (key, cb) { var is = "SELECT * FROM " + this.record + " WHERE id = ?" , that = this , win = function(xxx, results) { if (cb) that.fn('exists', cb).call(that, (results.rows.length > 0)) } this.db.readTransaction(function(t){ t.executeSql(is, [key], win, fail) }) return this }, all: function (callback) { var that = this , all = "SELECT * FROM " + this.record , r = [] , cb = this.fn(this.name, callback) || undefined , win = function (xxx, results) { if (results.rows.length != 0) { for (var i = 0, l = results.rows.length; i < l; i++) { var obj = JSON.parse(results.rows.item(i).value) obj.key = results.rows.item(i).id r.push(obj) } } if (cb) cb.call(that, r) } this.db.readTransaction(function (t) { t.executeSql(all, [], win, fail) }) return this }, remove: function (keyOrArray, cb) { var that = this , args , sql = "DELETE FROM " + this.record + " WHERE id " , win = function () { if (cb) that.lambda(cb).call(that) } if (!this.isArray(keyOrArray)) { sql += '= ?'; args = [keyOrArray]; } else { args = keyOrArray; sql += "IN (" + args.map(function(){return '?'}).join(',') + ")"; } args = args.map(function(obj) { return obj.key ? obj.key : obj; }); this.db.transaction( function (t) { t.executeSql(sql, args, win, fail); }); return this; }, nuke: function (cb) { var nuke = "DELETE FROM " + this.record , that = this , win = cb ? function() { that.lambda(cb).call(that) } : function(){} this.db.transaction(function (t) { t.executeSql(nuke, [], win, fail) }) return this } ////// }})())
Ink.createExt('Ghink', 1, ['Ink.Dom.Browser_1'], function( Browser ) { var Ghink = function() { this.init(); }; Ghink.prototype = { init: function() { // Fadein all the "fadein" classes var fades = document.getElementsByClassName("fadein"); for (var i = fades.length - 1; i >= 0; i--) this.fade(fades[i]); // initialize map if(typeof(initMap)!=="undefined") initMap(); }, shuffle: function(o) { for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }, fade: function(e) { var op = 0; // initial opacity e.style.opacity = 0; e.style.filter = 'alpha(opacity=0)'; e.style.visibility="visible"; var timer = setInterval(function () { if (op >= 1){ clearInterval(timer); } op += 0.1; e.style.opacity = op; e.style.filter = 'alpha(opacity=' + op * 100 + ")"; }, 50); }, // Marks menu items as active if they match the data-urlexp attribute menuSelectItems: function() { var menus = document.getElementsByClassName("menu"); for (var j=0; j < menus.length; j++) { var items = menus[j].getElementsByTagName('li'); for (var i = 0; i < items.length; i++) { var re = items[i].getAttribute('data-urlexp'); if( re && window.location.pathname.search(eval(re))!==-1) { items[i].className = 'active'; return; } } } }, // Code prettifyer prettifyer: function() { var codes = document.getElementsByClassName("highlight"); for (var i = codes.length - 1; i >= 0; i--) { for (var j = codes[i].childNodes.length - 1; j >= 0; j--) { if(codes[i].childNodes[j].tagName==='PRE') { codes[i].childNodes[j].className = 'prettyprint'; } } } try { prettyPrint(); } catch(err) { } }, // Print related posts printRandomPosts: function(posts,num) { var prs=[]; var pc=0; var elm = Ink.i('relatedposts'); if(elm) { var html=''; var rposts=this.shuffle(posts); for(var i=0;i<rposts.length && pc<num;i++) { var post=rposts[i]; if(post.thumbnail && post.thumbnail.length && window.location.pathname !== post.url) { html+='<a href="'+post.url+'"><h5>'+post.title+'</h5><img src="'+post.thumbnail+'"><br/><small>'+post.excerpt+'</small></a>'; pc++; } } elm.innerHTML=html; } } }; return Ghink; });
'use strict' const ipcMain = require('electron').ipcMain const webContents = require('electron').webContents // Doesn't exist in early initialization. let webViewManager = null const supportedWebViewEvents = [ 'load-commit', 'did-attach', 'did-finish-load', 'did-fail-load', 'did-frame-finish-load', 'did-start-loading', 'did-stop-loading', 'did-get-response-details', 'did-get-redirect-request', 'dom-ready', 'console-message', 'devtools-opened', 'devtools-closed', 'devtools-focused', 'new-window', 'will-navigate', 'did-navigate', 'did-navigate-in-page', 'close', 'crashed', 'gpu-crashed', 'plugin-crashed', 'destroyed', 'page-title-updated', 'page-favicon-updated', 'enter-html-full-screen', 'leave-html-full-screen', 'media-started-playing', 'media-paused', 'found-in-page', 'did-change-theme-color', 'update-target-url' ] let nextGuestInstanceId = 0 const guestInstances = {} const embedderElementsMap = {} // Moves the last element of array to the first one. const moveLastToFirst = function (list) { return list.unshift(list.pop()) } // Generate guestInstanceId. const getNextGuestInstanceId = function () { return ++nextGuestInstanceId } // Create a new guest instance. const createGuest = function (embedder, params) { if (webViewManager == null) { webViewManager = process.atomBinding('web_view_manager') } const guestInstanceId = getNextGuestInstanceId(embedder) const guest = webContents.create({ isGuest: true, partition: params.partition, embedder: embedder }) guestInstances[guestInstanceId] = { guest: guest, embedder: embedder } watchEmbedder(embedder) // Init guest web view after attached. guest.on('did-attach', function () { let opts params = this.attachParams delete this.attachParams this.viewInstanceId = params.instanceId this.setSize({ normal: { width: params.elementWidth, height: params.elementHeight }, enableAutoSize: params.autosize, min: { width: params.minwidth, height: params.minheight }, max: { width: params.maxwidth, height: params.maxheight } }) if (params.src) { opts = {} if (params.httpreferrer) { opts.httpReferrer = params.httpreferrer } if (params.useragent) { opts.userAgent = params.useragent } this.loadURL(params.src, opts) } guest.allowPopups = params.allowpopups }) // Dispatch events to embedder. const fn = function (event) { guest.on(event, function (_, ...args) { const embedder = getEmbedder(guestInstanceId) if (!embedder) { return } embedder.send.apply(embedder, ['ELECTRON_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + guest.viewInstanceId, event].concat(args)) }) } for (const event of supportedWebViewEvents) { fn(event) } // Dispatch guest's IPC messages to embedder. guest.on('ipc-message-host', function (_, [channel, ...args]) { const embedder = getEmbedder(guestInstanceId) if (!embedder) { return } embedder.send.apply(embedder, ['ELECTRON_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + guest.viewInstanceId, channel].concat(args)) }) // Autosize. guest.on('size-changed', function (_, ...args) { const embedder = getEmbedder(guestInstanceId) if (!embedder) { return } embedder.send.apply(embedder, ['ELECTRON_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + guest.viewInstanceId].concat(args)) }) return guestInstanceId } // Attach the guest to an element of embedder. const attachGuest = function (embedder, elementInstanceId, guestInstanceId, params) { let guest, guestInstance, key, oldKey, oldGuestInstanceId, ref1, webPreferences // Destroy the old guest when attaching. key = (embedder.getId()) + '-' + elementInstanceId oldGuestInstanceId = embedderElementsMap[key] if (oldGuestInstanceId != null) { // Reattachment to the same guest is just a no-op. if (oldGuestInstanceId === guestInstanceId) { return } destroyGuest(embedder, oldGuestInstanceId) } guestInstance = guestInstances[guestInstanceId] // If this isn't a valid guest instance then do nothing. if (!guestInstance) { return } guest = guestInstance.guest // If this guest is already attached to an element then remove it if (guestInstance.elementInstanceId) { oldKey = (guestInstance.embedder.getId()) + '-' + guestInstance.elementInstanceId delete embedderElementsMap[oldKey] webViewManager.removeGuest(guestInstance.embedder, guestInstanceId) guestInstance.embedder.send('ELECTRON_GUEST_VIEW_INTERNAL_DESTROY_GUEST-' + guest.viewInstanceId) } webPreferences = { guestInstanceId: guestInstanceId, nodeIntegration: (ref1 = params.nodeintegration) != null ? ref1 : false, plugins: params.plugins, zoomFactor: params.zoomFactor, webSecurity: !params.disablewebsecurity, blinkFeatures: params.blinkfeatures, disableBlinkFeatures: params.disableblinkfeatures } if (params.preload) { webPreferences.preloadURL = params.preload } webViewManager.addGuest(guestInstanceId, elementInstanceId, embedder, guest, webPreferences) guest.attachParams = params embedderElementsMap[key] = guestInstanceId guest.setEmbedder(embedder) guestInstance.embedder = embedder guestInstance.elementInstanceId = elementInstanceId watchEmbedder(embedder) } // Destroy an existing guest instance. const destroyGuest = function (embedder, guestInstanceId) { if (!(guestInstanceId in guestInstances)) { return } let guestInstance = guestInstances[guestInstanceId] if (embedder !== guestInstance.embedder) { return } webViewManager.removeGuest(embedder, guestInstanceId) guestInstance.guest.destroy() delete guestInstances[guestInstanceId] const key = embedder.getId() + '-' + guestInstance.elementInstanceId return delete embedderElementsMap[key] } // Once an embedder has had a guest attached we watch it for destruction to // destroy any remaining guests. const watchedEmbedders = new Set() const watchEmbedder = function (embedder) { if (watchedEmbedders.has(embedder)) { return } watchedEmbedders.add(embedder) const destroyEvents = ['will-destroy', 'crashed', 'did-navigate'] const destroy = function () { for (const guestInstanceId of Object.keys(guestInstances)) { if (guestInstances[guestInstanceId].embedder === embedder) { destroyGuest(embedder, parseInt(guestInstanceId)) } } for (const event of destroyEvents) { embedder.removeListener(event, destroy) } watchedEmbedders.delete(embedder) } for (const event of destroyEvents) { embedder.once(event, destroy) // Users might also listen to the crashed event, so we must ensure the guest // is destroyed before users' listener gets called. It is done by moving our // listener to the first one in queue. const listeners = embedder._events[event] if (Array.isArray(listeners)) { moveLastToFirst(listeners) } } } ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_CREATE_GUEST', function (event, params, requestId) { event.sender.send('ELECTRON_RESPONSE_' + requestId, createGuest(event.sender, params)) }) ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_ATTACH_GUEST', function (event, elementInstanceId, guestInstanceId, params) { attachGuest(event.sender, elementInstanceId, guestInstanceId, params) }) ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_DESTROY_GUEST', function (event, guestInstanceId) { destroyGuest(event.sender, guestInstanceId) }) ipcMain.on('ELECTRON_GUEST_VIEW_MANAGER_SET_SIZE', function (event, guestInstanceId, params) { const guestInstance = guestInstances[guestInstanceId] return guestInstance != null ? guestInstance.guest.setSize(params) : void 0 }) // Returns WebContents from its guest id. exports.getGuest = function (guestInstanceId) { const guestInstance = guestInstances[guestInstanceId] return guestInstance != null ? guestInstance.guest : void 0 } // Returns the embedder of the guest. const getEmbedder = function (guestInstanceId) { const guestInstance = guestInstances[guestInstanceId] return guestInstance != null ? guestInstance.embedder : void 0 } exports.getEmbedder = getEmbedder
// Copyright (c) 2020 Uber Technologies, Inc. // // 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. /* eslint-disable max-statements */ 'use strict'; function X100(job) { this.job = job; } X100.prototype.bench = function bench() { // 1 block of 10 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 2 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 3 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 4 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 5 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 6 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 7 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 8 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 9 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); // 10 this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); this.job.bench(); }; module.exports = X100;
var flow = require('../index').flow; flow('mainFlow')( function step1() { console.log(this.stepName); this.next(); }, flow('subFlow')( function subStep1() { console.log(this.stepName); this.next(); }, function subStep2() { console.log(this.stepName); this.next(); }, function subStep3() { console.log(this.stepName); throw new Error('hoge'); } ), function step2() { console.log(this.stepName); this.next(); }, function step3() { if (this.err) { console.log(this.stepName); this.err = null; } console.log('done'); this.next(); } )();
version https://git-lfs.github.com/spec/v1 oid sha256:641d756dd06b966993480a1da7a48a74f020ebbe298f023619185c531260b56b size 53843
/** * @fileoverview Responsible for loading ignore config files and managing ignore patterns * @author Jonathan Rajavuori */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var fs = require("fs"), debug = require("debug"), minimatch = require("minimatch"), FileFinder = require("./file-finder"); debug = debug("eslint:ignored-paths"); //------------------------------------------------------------------------------ // Constants //------------------------------------------------------------------------------ var ESLINT_IGNORE_FILENAME = ".eslintignore"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Load and parse ignore patterns from the file at the given path * @param {string} filepath Path to the ignore file. * @returns {string[]} An array of ignore patterns or an empty array if no ignore file. */ function loadIgnoreFile(filepath) { var ignorePatterns = []; function nonEmpty(line) { return line.trim() !== "" && line[0] !== "#"; } if (filepath) { try { ignorePatterns = fs.readFileSync(filepath, "utf8").split(/\r?\n/).filter(nonEmpty); } catch (e) { e.message = "Cannot read ignore file: " + filepath + "\nError: " + e.message; throw e; } } return ignorePatterns; } var ignoreFileFinder; /** * Find an ignore file in the current directory. * @returns {string|boolean} path of ignore file if found, or false if no ignore is found */ function findIgnoreFile() { if (!ignoreFileFinder) { ignoreFileFinder = new FileFinder(ESLINT_IGNORE_FILENAME); } return ignoreFileFinder.findInDirectory(); } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * IgnoredPaths * @constructor * @class IgnoredPaths * @param {Array} patterns to be matched against file paths */ function IgnoredPaths(patterns) { this.patterns = patterns; } /** * IgnoredPaths initializer * @param {Object} options object containing 'ignore' and 'ignorePath' properties * @returns {IgnoredPaths} object, with patterns loaded from the ignore file */ IgnoredPaths.load = function (options) { var patterns; options = options || {}; if (options.ignore) { patterns = loadIgnoreFile(options.ignorePath || findIgnoreFile()); } else { patterns = []; } return new IgnoredPaths(patterns); }; /** * Determine whether a file path is included in the configured ignore patterns * @param {string} filepath Path to check * @returns {boolean} true if the file path matches one or more patterns, false otherwise */ IgnoredPaths.prototype.contains = function (filepath) { if (this.patterns === null) { throw new Error("No ignore patterns loaded, call 'load' first"); } filepath = filepath.replace("\\", "/"); return this.patterns.reduce(function(ignored, pattern) { var negated = pattern[0] === "!", matches; if (negated) { pattern = pattern.slice(1); } matches = minimatch(filepath, pattern) || minimatch(filepath, pattern + "/**"); return matches ? !negated : ignored; }, false); }; module.exports = IgnoredPaths;
/** @babel */ import {CompositeDisposable} from 'atom' let reporter function getReporter () { if (!reporter) { const Reporter = require('./reporter') reporter = new Reporter() } return reporter } export default { activate() { this.subscriptions = new CompositeDisposable() if (!atom.config.get('exception-reporting.userId')) { atom.config.set('exception-reporting.userId', require('node-uuid').v4()) } this.subscriptions.add(atom.onDidThrowError(({message, url, line, column, originalError}) => { try { getReporter().reportUncaughtException(originalError) } catch (secondaryException) { try { console.error("Error reporting uncaught exception", secondaryException) getReporter().reportUncaughtException(secondaryException) } catch (error) { } } }) ) if (atom.onDidFailAssertion != null) { this.subscriptions.add(atom.onDidFailAssertion(error => { try { getReporter().reportFailedAssertion(error) } catch (secondaryException) { try { console.error("Error reporting assertion failure", secondaryException) getReporter().reportUncaughtException(secondaryException) } catch (error) {} } }) ) } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _base = _interopRequireDefault(require("./base")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function last(stack) { return stack[stack.length - 1]; } class CommentsParser extends _base.default { addComment(comment) { if (this.filename) comment.loc.filename = this.filename; this.state.trailingComments.push(comment); this.state.leadingComments.push(comment); } adjustCommentsAfterTrailingComma(node, elements, takeAllComments) { if (this.state.leadingComments.length === 0) { return; } let lastElement = null; let i = elements.length; while (lastElement === null && i > 0) { lastElement = elements[--i]; } if (lastElement === null) { return; } for (let j = 0; j < this.state.leadingComments.length; j++) { if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { this.state.leadingComments.splice(j, 1); j--; } } const newTrailingComments = []; for (let i = 0; i < this.state.leadingComments.length; i++) { const leadingComment = this.state.leadingComments[i]; if (leadingComment.end < node.end) { newTrailingComments.push(leadingComment); if (!takeAllComments) { this.state.leadingComments.splice(i, 1); i--; } } else { if (node.trailingComments === undefined) { node.trailingComments = []; } node.trailingComments.push(leadingComment); } } if (takeAllComments) this.state.leadingComments = []; if (newTrailingComments.length > 0) { lastElement.trailingComments = newTrailingComments; } else if (lastElement.trailingComments !== undefined) { lastElement.trailingComments = []; } } processComment(node) { if (node.type === "Program" && node.body.length > 0) return; const stack = this.state.commentStack; let firstChild, lastChild, trailingComments, i, j; if (this.state.trailingComments.length > 0) { if (this.state.trailingComments[0].start >= node.end) { trailingComments = this.state.trailingComments; this.state.trailingComments = []; } else { this.state.trailingComments.length = 0; } } else if (stack.length > 0) { const lastInStack = last(stack); if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) { trailingComments = lastInStack.trailingComments; delete lastInStack.trailingComments; } } if (stack.length > 0 && last(stack).start >= node.start) { firstChild = stack.pop(); } while (stack.length > 0 && last(stack).start >= node.start) { lastChild = stack.pop(); } if (!lastChild && firstChild) lastChild = firstChild; if (firstChild) { switch (node.type) { case "ObjectExpression": this.adjustCommentsAfterTrailingComma(node, node.properties); break; case "ObjectPattern": this.adjustCommentsAfterTrailingComma(node, node.properties, true); break; case "CallExpression": this.adjustCommentsAfterTrailingComma(node, node.arguments); break; case "ArrayExpression": this.adjustCommentsAfterTrailingComma(node, node.elements); break; case "ArrayPattern": this.adjustCommentsAfterTrailingComma(node, node.elements, true); break; } } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) { this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode], true); } if (lastChild) { if (lastChild.leadingComments) { if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } else { for (i = lastChild.leadingComments.length - 2; i >= 0; --i) { if (lastChild.leadingComments[i].end <= node.start) { node.leadingComments = lastChild.leadingComments.splice(0, i + 1); break; } } } } } else if (this.state.leadingComments.length > 0) { if (last(this.state.leadingComments).end <= node.start) { if (this.state.commentPreviousNode) { for (j = 0; j < this.state.leadingComments.length; j++) { if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { this.state.leadingComments.splice(j, 1); j--; } } } if (this.state.leadingComments.length > 0) { node.leadingComments = this.state.leadingComments; this.state.leadingComments = []; } } else { for (i = 0; i < this.state.leadingComments.length; i++) { if (this.state.leadingComments[i].end > node.start) { break; } } const leadingComments = this.state.leadingComments.slice(0, i); if (leadingComments.length) { node.leadingComments = leadingComments; } trailingComments = this.state.leadingComments.slice(i); if (trailingComments.length === 0) { trailingComments = null; } } } this.state.commentPreviousNode = node; if (trailingComments) { if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) { node.innerComments = trailingComments; } else { node.trailingComments = trailingComments; } } stack.push(node); } } exports.default = CommentsParser;
import Ember from 'ember'; export default Ember.Route.extend({ title: function(tokens) { var base = 'My Blog'; var hasTokens = tokens && tokens.length; return hasTokens ? tokens.reverse().join(' - ') + ' - ' + base : base; } });
/** * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-env node */ 'use strict'; var crypto = require('crypto'); var defaults = require('lodash.defaults'); var externalFunctions = require('./functions.js'); var fs = require('fs'); var glob = require('glob'); var mkdirp = require('mkdirp'); var path = require('path'); var prettyBytes = require('pretty-bytes'); var template = require('lodash.template'); var util = require('util'); require('es6-promise').polyfill(); // This should only change if there are breaking changes in the cache format used by the SW. var VERSION = 'v1'; function absolutePath(relativePath) { return path.resolve(process.cwd(), relativePath); } function getFileAndSizeAndHashForFile(file) { var stat = fs.statSync(file); if (stat.isFile()) { var buffer = fs.readFileSync(file); return { file: file, size: stat.size, hash: getHash(buffer) }; } return null; } function getFilesAndSizesAndHashesForGlobPattern(globPattern, excludeFilePath) { return glob.sync(globPattern.replace(path.sep, '/')).map(function(file) { // Return null if we want to exclude this file, and it will be excluded in // the subsequent filter(). return excludeFilePath === absolutePath(file) ? null : getFileAndSizeAndHashForFile(file); }).filter(function(fileAndSizeAndHash) { return fileAndSizeAndHash !== null; }); } function getHash(data) { var md5 = crypto.createHash('md5'); md5.update(data); return md5.digest('hex'); } function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function generate(params, callback) { return new Promise(function(resolve, reject) { params = defaults(params || {}, { cacheId: '', directoryIndex: 'index.html', dynamicUrlToDependencies: {}, handleFetch: true, ignoreUrlParametersMatching: [/^utm_/], importScripts: [], logger: console.log, maximumFileSizeToCacheInBytes: 2 * 1024 * 1024, // 2MB navigateFallback: '', navigateFallbackWhitelist: [], stripPrefix: '', replacePrefix: '', staticFileGlobs: [], templateFilePath: path.join( path.dirname(fs.realpathSync(__filename)), '..', 'service-worker.tmpl'), verbose: false }); if (!Array.isArray(params.ignoreUrlParametersMatching)) { params.ignoreUrlParametersMatching = [params.ignoreUrlParametersMatching]; } var relativeUrlToHash = {}; var cumulativeSize = 0; params.staticFileGlobs.forEach(function(globPattern) { var filesAndSizesAndHashes = getFilesAndSizesAndHashesForGlobPattern( globPattern, params.outputFilePath); // The files returned from glob are sorted by default, so we don't need to sort here. filesAndSizesAndHashes.forEach(function(fileAndSizeAndHash) { if (fileAndSizeAndHash.size <= params.maximumFileSizeToCacheInBytes) { // Strip the prefix to turn this into a relative URL. var relativeUrl = fileAndSizeAndHash.file .replace( new RegExp('^' + escapeRegExp(params.stripPrefix)), params.replacePrefix) .replace(path.sep, '/'); relativeUrlToHash[relativeUrl] = fileAndSizeAndHash.hash; if (params.verbose) { params.logger(util.format('Caching static resource "%s" (%s)', fileAndSizeAndHash.file, prettyBytes(fileAndSizeAndHash.size))); } cumulativeSize += fileAndSizeAndHash.size; } else { params.logger( util.format('Skipping static resource "%s" (%s) - max size is %s', fileAndSizeAndHash.file, prettyBytes(fileAndSizeAndHash.size), prettyBytes(params.maximumFileSizeToCacheInBytes))); } }); }); Object.keys(params.dynamicUrlToDependencies).forEach(function(dynamicUrl) { if (!Array.isArray(params.dynamicUrlToDependencies[dynamicUrl])) { throw Error(util.format( 'The value for the dynamicUrlToDependencies.%s ' + 'option must be an Array.', dynamicUrl)); } var filesAndSizesAndHashes = params.dynamicUrlToDependencies[dynamicUrl] .sort() .map(function(file) { try { return getFileAndSizeAndHashForFile(file); } catch (e) { // Provide some additional information about the failure if the file is missing. if (e.code === 'ENOENT') { params.logger(util.format( '%s was listed as a dependency for dynamic URL %s, but ' + 'the file does not exist. Either remove the entry as a ' + 'dependency, or correct the path to the file.', file, dynamicUrl )); } // Re-throw the exception unconditionally, since this should be treated as fatal. throw e; } }); var concatenatedHashes = ''; filesAndSizesAndHashes.forEach(function(fileAndSizeAndHash) { // Let's assume that the response size of a server-generated page is roughly equal to the // total size of all its components. cumulativeSize += fileAndSizeAndHash.size; concatenatedHashes += fileAndSizeAndHash.hash; }); relativeUrlToHash[dynamicUrl] = getHash(concatenatedHashes); if (params.verbose) { params.logger(util.format( 'Caching dynamic URL "%s" with dependencies on %j', dynamicUrl, params.dynamicUrlToDependencies[dynamicUrl])); } }); var runtimeCaching; var swToolboxCode; if (params.runtimeCaching) { var pathToSWToolbox = require.resolve('sw-toolbox/sw-toolbox.js'); swToolboxCode = fs.readFileSync(pathToSWToolbox, 'utf8') .replace('//# sourceMappingURL=sw-toolbox.map.json', ''); runtimeCaching = params.runtimeCaching.reduce(function(prev, curr) { var line; if (curr.default) { line = util.format('\ntoolbox.router.default = toolbox.%s;', curr.default); } else { if (!(curr.urlPattern instanceof RegExp || typeof curr.urlPattern === 'string')) { throw new Error( 'runtimeCaching.urlPattern must be a string or RegExp'); } line = util.format('\ntoolbox.router.%s(%s, %s, %s);', // Default to setting up a 'get' handler. curr.method || 'get', // urlPattern might be a String or a RegExp. sw-toolbox supports both. curr.urlPattern, // If curr.handler is a string, then assume it's the name of one // of the built-in sw-toolbox strategies. // E.g. 'networkFirst' -> toolbox.networkFirst // If curr.handler is something else (like a function), then just // include its body inline. (typeof curr.handler === 'string' ? 'toolbox.' : '') + curr.handler, // Default to no options. JSON.stringify(curr.options || {})); } return prev + line; }, ''); } // It's very important that running this operation multiple times with the same input files // produces identical output, since we need the generated service-worker.js file to change iff // the input files changes. The service worker update algorithm, // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#update-algorithm, // relies on detecting even a single byte change in service-worker.js to trigger an update. // Because of this, we write out the cache options as a series of sorted, nested arrays rather // than as objects whose serialized key ordering might vary. var relativeUrls = Object.keys(relativeUrlToHash); var precacheConfig = relativeUrls.sort().map(function(relativeUrl) { return [relativeUrl, relativeUrlToHash[relativeUrl]]; }); params.logger(util.format( 'Total precache size is about %s for %d resources.', prettyBytes(cumulativeSize), relativeUrls.length)); fs.readFile(params.templateFilePath, 'utf8', function(error, data) { if (error) { if (callback) { callback(error); } return reject(error); } var populatedTemplate = template(data)({ cacheId: params.cacheId, // Ensure that anything false is translated into '', since this will be treated as a string. directoryIndex: params.directoryIndex || '', externalFunctions: externalFunctions, handleFetch: params.handleFetch, ignoreUrlParametersMatching: params.ignoreUrlParametersMatching, importScripts: params.importScripts ? params.importScripts.map(JSON.stringify).join(',') : null, // Ensure that anything false is translated into '', since this will be treated as a string. navigateFallback: params.navigateFallback || '', navigateFallbackWhitelist: JSON.stringify(params.navigateFallbackWhitelist.map(function(regex) { return regex.source; })), precacheConfig: JSON.stringify(precacheConfig), runtimeCaching: runtimeCaching, swToolboxCode: swToolboxCode, version: VERSION }); if (callback) { callback(null, populatedTemplate); } resolve(populatedTemplate); }); }); } function write(filePath, params, callback) { return new Promise(function(resolve, reject) { function finish(error, value) { if (error) { reject(error); } else { resolve(value); } if (callback) { callback(error, value); } } mkdirp.sync(path.dirname(filePath)); // Keep track of where we're outputting the file to ensure that we don't // pick up a previously written version in our new list of files. // See https://github.com/GoogleChrome/sw-precache/issues/101 params.outputFilePath = absolutePath(filePath); generate(params).then(function(serviceWorkerFileContents) { fs.writeFile(filePath, serviceWorkerFileContents, finish); }, finish); }); } module.exports = { generate: generate, write: write };
module.exports = { 'desc' : 'Mark A Pending Submission As Complete', 'examples' : [{ cmd : 'fhc appforms environments submissions complete --environment=<Environment Id> --id=<Submission Id> ', desc : 'Mark A Pending Submission As Complete'}], 'demand' : ['environment', 'id'], 'alias' : {}, 'describe' : { 'environment': "Environment Id", 'id': "Submission Id" }, 'url' : function(params){ return "/api/v2/mbaas/" + params.environment + "/appforms/submissions/" + params.id + "/complete" ; }, 'method' : 'post' };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @flow strict-local * @format */ // flowlint ambiguous-object-type:error 'use strict'; const { getModuleComponentKey, getModuleOperationKey, } = require('../store/RelayStoreUtils'); import type {NormalizationSplitOperation} from './NormalizationNode'; import type {JSResourceReference} from 'JSResourceReference'; export opaque type Local3DPayload< +DocumentName: string, +Response: {...}, > = Response; function createPayloadFor3DField<+DocumentName: string, +Response: {...}>( name: DocumentName, operation: JSResourceReference<NormalizationSplitOperation>, component: JSResourceReference<mixed>, response: Response, ): Local3DPayload<DocumentName, Response> { const data = { ...response, }; data[getModuleComponentKey(name)] = component; data[getModuleOperationKey(name)] = operation; return data; } module.exports = createPayloadFor3DField;
// micro-module to test functionality (function() { 'use strict'; var hello = function () { return "hello"; } module.exports = hello; }()); // benalman.com/news/2010/11/immediately-invoked-function-expression
it("should not evaluate __dirname or __filename when node option is false", function(done) { if (typeof __dirname !== "undefined") { done.fail(); } if (typeof __filename !== "undefined") { done.fail(); } done(); });
define ( [ 'kbwidget', 'bootstrap', 'jquery', 'kbaseAuthenticatedWidget', 'kbaseTabs', 'jquery-dataTables', 'jquery-dataTables-bootstrap' ], function( KBWidget, bootstrap, $, kbaseAuthenticatedWidget, kbaseTabs, jquery_dataTables, bootstrap ) { return KBWidget({ name: "FbaModelComparisonWidget", parent : kbaseAuthenticatedWidget, version: "1.0.0", token: null, ws_name: null, fba_model1_id: null, fba_model1: null, fba_model2_id: null, fba_model2: null, genome1_ref: null, genome2_ref: null, genome1_id: null, genome2_id: null, genome1_name: null, genome2_name: null, proteome_cmp: null, gene_translation: {}, options: { ws_name: null, fba_model1_id: null, fba_model2_id: null, proteome_cmp_id: null }, wsUrl: window.kbconfig.urls.workspace, loadingImage: window.kbconfig.loading_gif, init: function(options) { this._super(options); this.ws_name = options.ws_name; this.fba_model1_id = options.fba_model1_id; this.fba_model2_id = options.fba_model2_id; this.gene_translation = {}; if (options.proteome_cmp) { this.proteome_cmp = options.proteome_cmp; } return this; }, render: function() { var self = this; var container = this.$elem; container.empty(); if (!self.authToken()) { container.append("<div>[Error] You're not logged in</div>"); return; } container.append("<div><img src=\""+self.loadingImage+"\">&nbsp;&nbsp;Loading models and comparison data...</div>"); var pref = this.uuid(); var kbws = new Workspace(this.wsUrl, {'token': self.authToken()}); var get_object_input = [{ref: self.ws_name + "/" + self.fba_model1_id},{ref: self.ws_name + "/" + self.fba_model2_id}]; if (self.proteome_cmp) { get_object_input.push({ref: self.ws_name + "/" + self.proteome_cmp}); } kbws.get_objects(get_object_input, function(data) { self.fba_model1 = data[0].data; self.fba_model2 = data[1].data; prepare_model(self.fba_model1); prepare_model(self.fba_model2); self.genome1_ref = self.fba_model1.genome_ref; self.genome2_ref = self.fba_model2.genome_ref; if (data[2]) { var ftrs = data[2].data.proteome1names; for (var i=0; i< ftrs.length; i++) { var hits = data[2].data.data1[i]; for (var j=0; j < hits.length; j++) { //if (hits[j][2] == 100) { if (self.gene_translation[ftrs[i]] === undefined) { self.gene_translation[ftrs[i]] = []; } self.gene_translation[ftrs[i]].push(data[2].data.proteome2names[hits[j][0]]); //} } } ftrs = data[2].data.proteome2names; for (var i=0; i< ftrs.length; i++) { var hits = data[2].data.data2[i]; for (var j=0; j < hits.length; j++) { //if (hits[j][2] == 100) { if (self.gene_translation[ftrs[i]] === undefined) { self.gene_translation[ftrs[i]] = []; } self.gene_translation[ftrs[i]].push(data[2].data.proteome1names[hits[j][0]]); //} } } } kbws.get_object_subset([ {ref: self.genome1_ref, included: ["scientific_name"]}, {ref: self.genome2_ref, included: ["scientific_name"]} ], function(data) { self.genome1_id = data[0].info[1]; self.genome2_id = data[1].info[1]; self.genome1_name = data[0].data.scientific_name; self.genome2_name = data[1].data.scientific_name; dataIsReady(); }, function(data) { if (!error) container.empty(); error = true; container.append('<p>[Error] ' + data.error.message + '</p>'); }); }, function(data) { if (!error) container.empty(); error = true; container.append('<p>[Error] ' + data.error.message + '</p>'); }); var prepare_model = function(model) { model.cpdhash = {}; model.rxnhash = {}; model.cmphash = {}; for (var i=0; i< model.modelcompartments.length; i++) { var cmp = model.modelcompartments[i]; model.cmphash[cmp.id] = cmp; } for (var i=0; i< model.modelcompounds.length; i++) { var cpd = model.modelcompounds[i]; cpd.cmpkbid = cpd.modelcompartment_ref.split("/").pop(); cpd.cpdkbid = cpd.compound_ref.split("/").pop(); if (cpd.name === undefined) { cpd.name = cpd.id; } cpd.name = cpd.name.replace(/_[a-zA-z]\d+$/, ''); model.cpdhash[cpd.id] = cpd; if (cpd.cpdkbid != "cpd00000") { model.cpdhash[cpd.cpdkbid+"_"+cpd.cmpkbid] = cpd; } } for (var i=0; i< model.modelreactions.length; i++) { var rxn = model.modelreactions[i]; rxn.rxnkbid = rxn.reaction_ref.split("/").pop(); rxn.cmpkbid = rxn.modelcompartment_ref.split("/").pop(); rxn.dispid = rxn.id.replace(/_[a-zA-z]\d+$/, '')+"["+rxn.cmpkbid+"]"; rxn.name = rxn.name.replace(/_[a-zA-z]\d+$/, ''); if (rxn.name == "CustomReaction") { rxn.name = rxn.id.replace(/_[a-zA-z]\d+$/, ''); } model.rxnhash[rxn.id] = rxn; if (rxn.rxnkbid != "rxn00000") { model.rxnhash[rxn.rxnkbid+"_"+rxn.cmpkbid] = rxn; if (rxn.rxnkbid+"_"+rxn.cmpkbid != rxn.id) { rxn.dispid += "<br>("+rxn.rxnkbid+")"; } } var reactants = ""; var products = ""; var sign = "<=>"; if (rxn.direction == ">") { sign = "=>"; } else if (rxn.direction == "<") { sign = "<="; } for (var j=0; j< rxn.modelReactionReagents.length; j++) { var rgt = rxn.modelReactionReagents[j]; rgt.cpdkbid = rgt.modelcompound_ref.split("/").pop(); if (rgt.coefficient < 0) { if (reactants.length > 0) { reactants += " + "; } if (rgt.coefficient != -1) { var abscoef = Math.round(-1*100*rgt.coefficient)/100; reactants += "("+abscoef+") "; } reactants += model.cpdhash[rgt.cpdkbid].name+"["+model.cpdhash[rgt.cpdkbid].cmpkbid+"]"; } else { if (products.length > 0) { products += " + "; } if (rgt.coefficient != 1) { var abscoef = Math.round(100*rgt.coefficient)/100; products += "("+abscoef+") "; } products += model.cpdhash[rgt.cpdkbid].name+"["+model.cpdhash[rgt.cpdkbid].cmpkbid+"]"; } } rxn.ftrhash = {}; for (var j=0; j< rxn.modelReactionProteins.length; j++) { var prot = rxn.modelReactionProteins[j]; for (var k=0; k< prot.modelReactionProteinSubunits.length; k++) { var subunit = prot.modelReactionProteinSubunits[k]; for (var m=0; m< subunit.feature_refs.length; m++) { rxn.ftrhash[subunit.feature_refs[m].split("/").pop()] = 1; } } } rxn.dispfeatures = ""; for (var gene in rxn.ftrhash) { if (rxn.dispfeatures.length > 0) { rxn.dispfeatures += "<br>"; } rxn.dispfeatures += gene; } rxn.equation = reactants+" "+sign+" "+products; } } var compare_models = function() { model1 = self.fba_model1; model2 = self.fba_model2; self.overlap_rxns = []; self.exact_matches = 0; model1.unique_rxn = []; for (var i=0; i< model1.modelreactions.length; i++) { var rxn = model1.modelreactions[i]; if (rxn.rxnkbid == "rxn00000") { if (model2.rxnhash[rxn.id] === undefined) { model1.unique_rxn.push(rxn); } else { var rxn2 = model2.rxnhash[rxn.id]; var model1ftrs = ""; var exact = 1; for (var gene in rxn.ftrhash) { if (model1ftrs.length > 0) { model1ftrs += "<br>"; } if (self.gene_translation[gene]) { var transftrs = self.gene_translation[gene]; var found = 0; for (var n=0; n < transftrs.length; n++) { if (rxn2.ftrhash[transftrs[n]]) { model1ftrs += gene; found = 1; break; } } if (found == 0) { model1ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } } else if (rxn2.ftrhash[gene] === undefined) { model1ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } else { model1ftrs += gene; } } var model2ftrs = ""; for (var gene in rxn2.ftrhash) { if (model2ftrs.length > 0) { model2ftrs += "<br>"; } if (self.gene_translation[gene]) { var transftrs = self.gene_translation[gene]; var found = 0; for (var n=0; n < transftrs.length; n++) { if (rxn.ftrhash[transftrs[n]]) { model2ftrs += gene; found = 1; break; } } if (found == 0) { model2ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } } else if (rxn.ftrhash[gene] === undefined) { model2ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } else { model2ftrs += gene; } } if (exact == 1) { self.exact_matches++; } self.overlap_rxns.push({ 'model1rxn': rxn, 'model2rxn': rxn2, 'canonical':0, 'exact': exact, 'model1features': model1ftrs, 'model2features': model2ftrs }); } } else if (model2.rxnhash[rxn.rxnkbid+"_"+rxn.cmpkbid] === undefined) { model1.unique_rxn.push(rxn); } else { var rxn2 = model2.rxnhash[rxn.rxnkbid+"_"+rxn.cmpkbid]; var model1ftrs = ""; var exact = 1; for (var gene in rxn.ftrhash) { if (model1ftrs.length > 0) { model1ftrs += "<br>"; } if (self.gene_translation[gene]) { var transftrs = self.gene_translation[gene]; var found = 0; for (var n=0; n < transftrs.length; n++) { if (rxn2.ftrhash[transftrs[n]]) { model1ftrs += gene; found = 1; break; } } if (found == 0) { model1ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } } else if (rxn2.ftrhash[gene] === undefined) { model1ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } else { model1ftrs += gene; } } var model2ftrs = ""; for (var gene in rxn2.ftrhash) { if (model2ftrs.length > 0) { model2ftrs += "<br>"; } if (self.gene_translation[gene]) { var transftrs = self.gene_translation[gene]; var found = 0; for (var n=0; n < transftrs.length; n++) { if (rxn.ftrhash[transftrs[n]]) { model2ftrs += gene; found = 1; break; } } if (found == 0) { model2ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } } else if (rxn.ftrhash[gene] === undefined) { model2ftrs += '<font color="red">' + gene + '</font>'; exact = 0; } else { model2ftrs += gene; } } if (exact == 1) { self.exact_matches++; } self.overlap_rxns.push({ 'model1rxn': rxn, 'model2rxn': rxn2, 'canonical':1, 'exact': exact, 'model1features': model1ftrs, 'model2features': model2ftrs }); } } model2.unique_rxn = []; for (var i=0; i< model2.modelreactions.length; i++) { var rxn = model2.modelreactions[i]; if (rxn.rxnkbid == "rxn00000") { if (model1.rxnhash[rxn.id] === undefined) { model2.unique_rxn.push(rxn); } } else if (model1.rxnhash[rxn.rxnkbid+"_"+rxn.cmpkbid] === undefined) { model2.unique_rxn.push(rxn); } } } var dataIsReady = function() { compare_models(); ///////////////////////////////////// Instantiating Tabs //////////////////////////////////////////// container.empty(); var tabPane = $('<div id="'+self.pref+'tab-content">'); container.append(tabPane); var tabWidget = new kbaseTabs(tabPane, {canDelete : true, tabs : []}); //////////////////////////////////////////// Statistics tab ///////////////////////////////////////////// var tabStats = $("<div/>"); tabWidget.addTab({tab: 'Statistics', content: tabStats, canDelete : false, show: true}); var tableStats = $('<table class="table table-striped table-bordered" '+ 'style="margin-left: auto; margin-right: auto;" id="'+self.pref+'modelcomp-stats"/>'); tabStats.append(tableStats); tableStats.append('<tr><td><b>'+self.fba_model1_id+'</b> genome</td><td>'+self.genome1_id+'<br>('+self.genome1_name+')</td></tr>'); tableStats.append('<tr><td><b>'+self.fba_model2_id+'</b> genome</td><td>'+self.genome2_id+'<br>('+self.genome2_name+')</td></tr>'); tableStats.append('<tr><td>Reactions in <b>'+self.fba_model1_id+'</b></td><td>'+self.fba_model1.modelreactions.length+'</td></tr>'); tableStats.append('<tr><td>Reactions in <b>'+self.fba_model2_id+'</b></td><td>'+self.fba_model2.modelreactions.length+'</td></tr>'); tableStats.append('<tr><td>Common reactions</td><td>'+self.overlap_rxns.length+'</td></tr>'); tableStats.append('<tr><td>Reactions with same features</td><td>'+self.exact_matches+'</td></tr>'); tableStats.append('<tr><td>Unique reactions in <b>'+self.fba_model1_id+'</b></td><td>'+self.fba_model1.unique_rxn.length+'</td></tr>'); tableStats.append('<tr><td>Unique reactions in <b>'+self.fba_model2_id+'</b></td><td>'+self.fba_model2.unique_rxn.length+'</td></tr>'); //////////////////////////////////////////// Common tab ///////////////////////////////////////////// var tabCommon = $("<div/>"); tabWidget.addTab({tab: 'Common reactions', content: tabCommon, canDelete : false, show: false}); var tableCommon = $('<table class="table table-striped table-bordered" '+ 'style="margin-left: auto; margin-right: auto;" id="'+self.pref+'modelcomp-common"/>'); tabCommon.append(tableCommon); tableCommon.dataTable({ "sPaginationType": "full_numbers", "iDisplayLength": 10, "aaData": self.overlap_rxns, "aaSorting": [[ 2, "desc" ], [0, "asc"]], "aoColumns": [ { "sTitle": "Reaction", 'mData': 'model1rxn.dispid'}, { "sTitle": "Equation&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 'mData': 'model1rxn.equation'}, { "sTitle": "<b>"+self.fba_model1_id+"</b> features", 'mData': 'model1features'}, { "sTitle": "<b>"+self.fba_model2_id+"</b> features", 'mData': 'model2features'}, { "sTitle": "Name", 'mData': 'model1rxn.name'}, { "sTitle": "Exact", 'mData': 'exact'}, ], "oLanguage": { "sEmptyTable": "No functions found!", "sSearch": "Search: " }, 'fnDrawCallback': events }); tabCommon.append($('<table><tr><td>(*) color legend: sub-best bidirectional hits are marked<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;by <font color="blue">blue</font>, '+ 'orphan features are marked by <font color="red">red</font>.</td></tr></table>')); //////////////////////////////////////////// Model1 only tab ///////////////////////////////////////////// var tabModel1 = $("<div/>"); tabWidget.addTab({tab: self.fba_model1_id+" only", content: tabModel1, canDelete : false, show: false}); var tableModel1 = $('<table class="table table-striped table-bordered" '+ 'style="margin-left: auto; margin-right: auto;" id="'+self.pref+'modelcomp-model1"/>'); tabModel1.append(tableModel1); tableModel1.dataTable({ "sPaginationType": "full_numbers", "iDisplayLength": 10, "aaData": self.fba_model1.unique_rxn, "aaSorting": [[ 2, "desc" ], [0, "asc"]], "aoColumns": [ { "sTitle": "Reaction", 'mData': 'dispid'}, { "sTitle": "Equation&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 'mData': 'equation'}, { "sTitle": "<b>"+self.fba_model1_id+"</b> features", 'mData': 'dispfeatures'}, { "sTitle": "Name", 'mData': 'name'}, ], "oLanguage": { "sEmptyTable": "No functions found!", "sSearch": "Search: " }, 'fnDrawCallback': events }); //////////////////////////////////////////// Model2 only tab ///////////////////////////////////////////// var tabModel2 = $("<div/>"); tabWidget.addTab({tab: self.fba_model2_id+" only", content: tabModel2, canDelete : false, show: false}); var tableModel2 = $('<table class="table table-striped table-bordered" '+ 'style="margin-left: auto; margin-right: auto;" id="'+self.pref+'modelcomp-model2"/>'); tabModel2.append(tableModel2); tableModel2.dataTable({ "sPaginationType": "full_numbers", "iDisplayLength": 10, "aaData": self.fba_model2.unique_rxn, "aaSorting": [[ 2, "desc" ], [0, "asc"]], "aoColumns": [ { "sTitle": "Reaction", 'mData': 'dispid'}, { "sTitle": "Equation&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 'mData': 'equation'}, { "sTitle": "<b>"+self.fba_model2_id+"</b> features", 'mData': 'dispfeatures'}, { "sTitle": "Name", 'mData': 'name'}, ], "oLanguage": { "sEmptyTable": "No functions found!", "sSearch": "Search: " }, 'fnDrawCallback': events }); ///////////////////////////////////// Event handling for links /////////////////////////////////////////// function events() { // event for clicking on ortholog count $('.show-reaction'+self.pref).unbind('click'); $('.show-reaction'+self.pref).click(function() { var id = $(this).data('id'); if (tabWidget.hasTab(id)) { tabWidget.showTab(id); return; } tabWidget.addTab({tab: id, content: "Coming soon!", canDelete : true, show: true}); }); $('.show-gene'+self.pref).unbind('click'); $('.show-gene'+self.pref).click(function() { var id = $(this).data('id'); if (tabWidget.hasTab(id)) { tabWidget.showTab(id); return; } tabWidget.addTab({tab: id, content: "Coming soon!", canDelete : true, show: true}); }); } }; return this; }, loggedInCallback: function(event, auth) { this.token = auth.token; this.render(); return this; }, loggedOutCallback: function(event, auth) { this.token = null; this.render(); return this; }, uuid: function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } }) });
class CountUp { constructor(startVal, endVal, decimals, duration, options = {}, page = getCurrentPages()[getCurrentPages().length - 1]) { Object.assign(this, { page, startVal, endVal, decimals, duration, options, }) this.__init() } /** * 初始化 */ __init() { this.setData = this.page.setData.bind(this.page) this.lastTime = 0 // merge options this.mergeOptions(this.options) this.startVal = Number(this.startVal) this.cacheVal = this.startVal this.endVal = Number(this.endVal) this.countDown = (this.startVal > this.endVal) this.frameVal = this.startVal this.decimals = Math.max(0, this.decimals || 0) this.dec = Math.pow(10, this.decimals) this.duration = Number(this.duration) * 1000 || 2000 // format startVal on initialization this.printValue(this.formattingFn(this.startVal)) } /** * 默认参数 */ setDefaultOptions() { return { useEasing: true, // toggle easing useGrouping: true, // 1,000,000 vs 1000000 separator: ',', // character to use as a separator decimal: '.', // character to use as a decimal easingFn: null, // optional custom easing closure function, default is Robert Penner's easeOutExpo formattingFn: null, // optional custom formatting function, default is this.formatNumber below printValue(value) {}, // printValue } } /** * 合并参数 */ mergeOptions(options) { const defaultOptions = this.setDefaultOptions() // extend default options with passed options object for (let key in defaultOptions) { if (defaultOptions.hasOwnProperty(key)) { this.options[key] = typeof options[key] !== 'undefined' ? options[key] : defaultOptions[key] if (typeof this.options[key] === 'function') { this.options[key] = this.options[key].bind(this) } } } if (this.options.separator === '') { this.options.useGrouping = !1 } if (!this.options.prefix) this.options.prefix = '' if (!this.options.suffix) this.options.suffix = '' this.easingFn = this.options.easingFn ? this.options.easingFn : this.easeOutExpo this.formattingFn = this.options.formattingFn ? this.options.formattingFn : this.formatNumber this.printValue = this.options.printValue ? this.options.printValue : function() {} } /** * 创建定时器 */ requestAnimationFrame(callback) { let currTime = new Date().getTime() let timeToCall = Math.max(0, 16 - (currTime - this.lastTime)) let timeout = setTimeout(() => { callback.bind(this)(currTime + timeToCall) }, timeToCall) this.lastTime = currTime + timeToCall return timeout } /** * 清空定时器 */ cancelAnimationFrame(timeout) { clearTimeout(timeout) } /** * 格式化数字 */ formatNumber(nStr) { nStr = nStr.toFixed(this.decimals) nStr += '' let x, x1, x2, rgx x = nStr.split('.') x1 = x[0] x2 = x.length > 1 ? this.options.decimal + x[1] : '' rgx = /(\d+)(\d{3})/ if (this.options.useGrouping) { while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + this.options.separator + '$2') } } return this.options.prefix + x1 + x2 + this.options.suffix } /** * 过渡效果 */ easeOutExpo(t, b, c, d) { return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b } /** * 计数函数 */ count(timestamp) { if (!this.startTime) { this.startTime = timestamp } this.timestamp = timestamp const progress = timestamp - this.startTime this.remaining = this.duration - progress // to ease or not to ease if (this.options.useEasing) { if (this.countDown) { this.frameVal = this.startVal - this.easingFn(progress, 0, this.startVal - this.endVal, this.duration) } else { this.frameVal = this.easingFn(progress, this.startVal, this.endVal - this.startVal, this.duration) } } else { if (this.countDown) { this.frameVal = this.startVal - ((this.startVal - this.endVal) * (progress / this.duration)) } else { this.frameVal = this.startVal + (this.endVal - this.startVal) * (progress / this.duration) } } // don't go past endVal since progress can exceed duration in the last frame if (this.countDown) { this.frameVal = (this.frameVal < this.endVal) ? this.endVal : this.frameVal } else { this.frameVal = (this.frameVal > this.endVal) ? this.endVal : this.frameVal } // decimal this.frameVal = Math.round(this.frameVal * this.dec) / this.dec // format and print value this.printValue(this.formattingFn(this.frameVal)) // whether to continue if (progress < this.duration) { this.rAF = this.requestAnimationFrame(this.count) } else { if (this.callback) { this.callback() } } } /** * 启动计数器 */ start(callback) { this.callback = callback this.rAF = this.requestAnimationFrame(this.count) return !1 } /** * 停止计数器 */ pauseResume() { if (!this.paused) { this.paused = !0 this.cancelAnimationFrame(this.rAF) } else { this.paused = !1 delete this.startTime this.duration = this.remaining this.startVal = this.frameVal this.requestAnimationFrame(this.count) } } /** * 重置计数器 */ reset() { this.paused = !1 delete this.startTime this.startVal = this.cacheVal this.cancelAnimationFrame(this.rAF) this.printValue(this.formattingFn(this.startVal)) } /** * 更新计数器 */ update(newEndVal) { this.cancelAnimationFrame(this.rAF) this.paused = !1 delete this.startTime this.startVal = this.frameVal this.endVal = Number(newEndVal) this.countDown = (this.startVal > this.endVal) this.rAF = this.requestAnimationFrame(this.count) } } export default CountUp
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { selectLocale } from './selectors'; export class LanguageProvider extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
define([ 'aeris/util', 'mocks/mockfactory', 'aeris/model', 'aeris/promise', 'aeris/errors/apiresponseerror' ], function(_, MockFactory, Model, Promise, ApiResponseError) { /** * @class MockAerisApiModel * @extends aeris.Model */ var MockAerisApiModel = MockFactory({ methods: [ 'fetch' ], inherits: Model, constructor: function(opt_attrs, opt_options) { var options = opt_options || {}; this.params_ = new Model(options.params); } }); /** * @method setParams * @param {Object} params */ MockAerisApiModel.prototype.setParams = function(params) { this.params_.set(params); }; /** * @method getParams * @return {Object} */ MockAerisApiModel.prototype.getParams = function() { return this.params_; }; /** * @method fetch * @return {aeris.Promise} */ MockAerisApiModel.prototype.fetch = function() { return this.promise_ = new Promise(); }; /** * Resolves the promise return by apiModel#fetch * * @method andResolveWith * @param {Object} response */ MockAerisApiModel.prototype.andResolveWith = function(response) { if (!this.promise_) { throw new Error('fetch has not yet been called'); } this.promise_.resolve(response); }; /** * Rejects the promise return by apiModel#fetch * * @method andRejectWith * @param {Object} obj * @param {string=} obj.code * @param {string=} obj.message * @param {Object=} obj.responseObject */ MockAerisApiModel.prototype.andRejectWith = function(obj) { var error; if (!this.promise_) { throw new Error('fetch has not yet been called'); } error = new ApiResponseError(); _.extend(error, _.defaults(obj, { code: 'STUB_CODE', message: 'STUB_MESSAGE', responseObject: {} })); this.promise_.reject(error); }; return MockAerisApiModel; });
export type User = { name: string; location: Location; }; export type Location = { address: string; } //export type address = string; export default function demo (input: User): string { return input.location.address; }
angular.module('webui.services.rpc.helpers', [ 'webui.services.deps', 'webui.services.rpc', 'webui.services.alerts' ]) .factory('$rpchelpers', ['$_', '$rpc', '$alerts', function(_, rpc, alerts) { var miscellaneous = {version: '', enabledFeatures: []}; rpc.once('getVersion', [], function(data) { miscellaneous = data[0]}); return { isFeatureEnabled: function(feature) { return miscellaneous.enabledFeatures.indexOf(feature) != -1; }, getAria2Version: function() { return miscellaneous.version; }, addUris: function(uris, settings, cb) { _.each(uris, function(uri) { uri_parsed = []; // parse options passed in the URIs. E.g. http://ex1.com/f1.jpg --out=image.jpg --check-integrity _.each(uri, function(uri_element) { if (uri_element.startsWith('--')) { uri_options = uri_element.split(/--|=(.*)/); if (uri_options.length > 2) { settings[uri_options[2]] = uri_options[3] || 'true'; } } else { uri_parsed.push(uri_element); } }); // passing true to batch all the addUri calls rpc.once('addUri', [uri_parsed, settings], cb, true); }); // now dispatch all addUri syscalls rpc.forceUpdate(); }, addTorrents: function(txts, settings, cb) { _.each(txts, function(txt) { // passing true to batch all the addUri calls rpc.once('addTorrent', [txt, [], settings], cb, true); }); // now dispatch all addUri syscalls rpc.forceUpdate(); }, addMetalinks: function(txts, settings, cb) { _.each(txts, function(txt) { // passing true to batch all the addUri calls rpc.once('addMetalink', [txt, settings], cb, true); }); // now dispatch all addUri syscalls rpc.forceUpdate(); } }; }]);
/** * Copyright 2014 Telerik AD * * 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(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["tn-ZA"] = { name: "tn-ZA", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-%n","%n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "R" } }, calendars: { standard: { days: { names: ["Latshipi","Mosupologo","Labobedi","Laboraro","Labone","Labotlhano","Lamatlhatso"], namesAbbr: ["Ltp.","Mos.","Lbd.","Lbr.","Lbn.","Lbt.","Lmt."], namesShort: ["Lp","Ms","Lb","Lr","Ln","Lt","Lm"] }, months: { names: ["Ferikgong","Tlhakole","Mopitloe","Moranang","Motsheganong","Seetebosigo","Phukwi","Phatwe","Lwetse","Diphalane","Ngwanatsele","Sedimothole",""], namesAbbr: ["Fer.","Tlhak.","Mop.","Mor.","Motsh.","Seet.","Phukw.","Phatw.","Lwets.","Diph.","Ngwan.","Sed.",""] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "yyyy/MM/dd", D: "dd MMMM yyyy", F: "dd MMMM yyyy hh:mm:ss tt", g: "yyyy/MM/dd hh:mm tt", G: "yyyy/MM/dd hh:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
/* * Translated default messages for bootstrap-select. * Locale: DE (German, deutsch) * Region: DE (Germany, Deutschland) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Bitte wählen...', noneResultsText: 'Keine Ergebnisse für {0}', countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? '{0} Element ausgewählt' : '{0} Elemente ausgewählt'; }, maxOptionsText: function (numAll, numGroup) { return [ (numAll == 1) ? 'Limit erreicht ({n} Element max.)' : 'Limit erreicht ({n} Elemente max.)', (numGroup == 1) ? 'Gruppen-Limit erreicht ({n} Element max.)' : 'Gruppen-Limit erreicht ({n} Elemente max.)' ]; }, selectAllText: 'Alles auswählen', deselectAllText: 'Nichts auswählen', multipleSeparator: ', ' }; })(jQuery);
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var ts = require("typescript"); var _ts = require("../ts-internal"); var _ = require("lodash"); var declaration_1 = require("../utils/options/declaration"); var context_1 = require("./context"); var components_1 = require("./components"); var compiler_host_1 = require("./utils/compiler-host"); var component_1 = require("../utils/component"); var fs_1 = require("../utils/fs"); var Converter = Converter_1 = (function (_super) { __extends(Converter, _super); function Converter() { return _super !== null && _super.apply(this, arguments) || this; } Converter.prototype.initialize = function () { this.compilerHost = new compiler_host_1.CompilerHost(this); this.nodeConverters = {}; this.typeTypeConverters = []; this.typeNodeConverters = []; }; Converter.prototype.addComponent = function (name, componentClass) { var component = _super.prototype.addComponent.call(this, name, componentClass); if (component instanceof components_1.ConverterNodeComponent) { this.addNodeConverter(component); } else if (component instanceof components_1.ConverterTypeComponent) { this.addTypeConverter(component); } return component; }; Converter.prototype.addNodeConverter = function (converter) { for (var _i = 0, _a = converter.supports; _i < _a.length; _i++) { var supports = _a[_i]; this.nodeConverters[supports] = converter; } }; Converter.prototype.addTypeConverter = function (converter) { if ('supportsNode' in converter && 'convertNode' in converter) { this.typeNodeConverters.push(converter); this.typeNodeConverters.sort(function (a, b) { return (b.priority || 0) - (a.priority || 0); }); } if ('supportsType' in converter && 'convertType' in converter) { this.typeTypeConverters.push(converter); this.typeTypeConverters.sort(function (a, b) { return (b.priority || 0) - (a.priority || 0); }); } }; Converter.prototype.removeComponent = function (name) { var component = _super.prototype.removeComponent.call(this, name); if (component instanceof components_1.ConverterNodeComponent) { this.removeNodeConverter(component); } else if (component instanceof components_1.ConverterTypeComponent) { this.removeTypeConverter(component); } return component; }; Converter.prototype.removeNodeConverter = function (converter) { var converters = this.nodeConverters; var keys = _.keys(this.nodeConverters); for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var key = keys_1[_i]; if (converters[key] === converter) { delete converters[key]; } } }; Converter.prototype.removeTypeConverter = function (converter) { var index = this.typeNodeConverters.indexOf(converter); if (index !== -1) { this.typeTypeConverters.splice(index, 1); } index = this.typeNodeConverters.indexOf(converter); if (index !== -1) { this.typeNodeConverters.splice(index, 1); } }; Converter.prototype.removeAllComponents = function () { _super.prototype.removeAllComponents.call(this); this.nodeConverters = {}; this.typeTypeConverters = []; this.typeNodeConverters = []; }; Converter.prototype.convert = function (fileNames) { for (var i = 0, c = fileNames.length; i < c; i++) { fileNames[i] = fs_1.normalizePath(_ts.normalizeSlashes(fileNames[i])); } var program = ts.createProgram(fileNames, this.application.options.getCompilerOptions(), this.compilerHost); var checker = program.getTypeChecker(); var context = new context_1.Context(this, fileNames, checker, program); this.trigger(Converter_1.EVENT_BEGIN, context); var errors = this.compile(context); var project = this.resolve(context); this.trigger(Converter_1.EVENT_END, context); return { errors: errors, project: project }; }; Converter.prototype.convertNode = function (context, node) { if (context.visitStack.indexOf(node) !== -1) { return null; } var oldVisitStack = context.visitStack; context.visitStack = oldVisitStack.slice(); context.visitStack.push(node); var result; if (node.kind in this.nodeConverters) { result = this.nodeConverters[node.kind].convert(context, node); } context.visitStack = oldVisitStack; return result; }; Converter.prototype.convertType = function (context, node, type) { if (node) { type = type || context.getTypeAtLocation(node); for (var _i = 0, _a = this.typeNodeConverters; _i < _a.length; _i++) { var converter = _a[_i]; if (converter.supportsNode(context, node, type)) { return converter.convertNode(context, node, type); } } } if (type) { for (var _b = 0, _c = this.typeTypeConverters; _b < _c.length; _b++) { var converter = _c[_b]; if (converter.supportsType(context, type)) { return converter.convertType(context, type); } } } }; Converter.prototype.compile = function (context) { var _this = this; var program = context.program; program.getSourceFiles().forEach(function (sourceFile) { _this.convertNode(context, sourceFile); }); var diagnostics = program.getOptionsDiagnostics(); if (diagnostics.length) { return diagnostics; } diagnostics = program.getSyntacticDiagnostics(); if (diagnostics.length) { return diagnostics; } diagnostics = program.getGlobalDiagnostics(); if (diagnostics.length) { return diagnostics; } diagnostics = program.getSemanticDiagnostics(); if (diagnostics.length) { return diagnostics; } return []; }; Converter.prototype.resolve = function (context) { this.trigger(Converter_1.EVENT_RESOLVE_BEGIN, context); var project = context.project; for (var id in project.reflections) { if (!project.reflections.hasOwnProperty(id)) { continue; } this.trigger(Converter_1.EVENT_RESOLVE, context, project.reflections[id]); } this.trigger(Converter_1.EVENT_RESOLVE_END, context); return project; }; Converter.prototype.getDefaultLib = function () { return ts.getDefaultLibFileName(this.application.options.getCompilerOptions()); }; return Converter; }(component_1.ChildableComponent)); Converter.EVENT_BEGIN = 'begin'; Converter.EVENT_END = 'end'; Converter.EVENT_FILE_BEGIN = 'fileBegin'; Converter.EVENT_CREATE_DECLARATION = 'createDeclaration'; Converter.EVENT_CREATE_SIGNATURE = 'createSignature'; Converter.EVENT_CREATE_PARAMETER = 'createParameter'; Converter.EVENT_CREATE_TYPE_PARAMETER = 'createTypeParameter'; Converter.EVENT_FUNCTION_IMPLEMENTATION = 'functionImplementation'; Converter.EVENT_RESOLVE_BEGIN = 'resolveBegin'; Converter.EVENT_RESOLVE = 'resolveReflection'; Converter.EVENT_RESOLVE_END = 'resolveEnd'; __decorate([ component_1.Option({ name: 'name', help: 'Set the name of the project that will be used in the header of the template.' }) ], Converter.prototype, "name", void 0); __decorate([ component_1.Option({ name: 'externalPattern', help: 'Define a pattern for files that should be considered being external.' }) ], Converter.prototype, "externalPattern", void 0); __decorate([ component_1.Option({ name: 'includeDeclarations', help: 'Turn on parsing of .d.ts declaration files.', type: declaration_1.ParameterType.Boolean }) ], Converter.prototype, "includeDeclarations", void 0); __decorate([ component_1.Option({ name: 'excludeExternals', help: 'Prevent externally resolved TypeScript files from being documented.', type: declaration_1.ParameterType.Boolean }) ], Converter.prototype, "excludeExternals", void 0); __decorate([ component_1.Option({ name: 'excludeNotExported', help: 'Prevent symbols that are not exported from being documented.', type: declaration_1.ParameterType.Boolean }) ], Converter.prototype, "excludeNotExported", void 0); __decorate([ component_1.Option({ name: 'excludePrivate', help: 'Ignores private variables and methods', type: declaration_1.ParameterType.Boolean }) ], Converter.prototype, "excludePrivate", void 0); Converter = Converter_1 = __decorate([ component_1.Component({ name: 'converter', internal: true, childClass: components_1.ConverterComponent }) ], Converter); exports.Converter = Converter; var Converter_1; //# sourceMappingURL=converter.js.map
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.charting.themes.Tufte"]){dojo._hasResource["dojox.charting.themes.Tufte"]=true;dojo.provide("dojox.charting.themes.Tufte");dojo.require("dojox.charting.Theme");(function(){var _1=dojox.charting;_1.themes.Tufte=new _1.Theme({antiAlias:false,chart:{stroke:null,fill:"inherit"},plotarea:{stroke:null,fill:"transparent"},axis:{stroke:{width:0},line:{width:0},majorTick:{color:"#666666",width:1,length:5},minorTick:{color:"black",width:1,length:2},font:"normal normal normal 8pt Tahoma",fontColor:"#999999"},series:{outline:{width:0,color:"black"},stroke:{width:1,color:"black"},fill:new dojo.Color([59,68,75,0.85]),font:"normal normal normal 7pt Tahoma",fontColor:"#717171"},marker:{stroke:{width:1},fill:"#333",font:"normal normal normal 7pt Tahoma",fontColor:"#000"},colors:[dojo.colorFromHex("#8a8c8f"),dojo.colorFromHex("#4b4b4b"),dojo.colorFromHex("#3b444b"),dojo.colorFromHex("#2e2d30"),dojo.colorFromHex("#000000")]});})();}
/** * @class Generic map of IDs to items - can generate own IDs or accept given IDs. IDs should be strings in order to not * clash with internally generated IDs, which are numbers. * @private */ var SceneJS_Map = function(items, _baseId) { /** * @property Items in this map */ this.items = items || []; var baseId = _baseId || 0; var lastUniqueId = baseId + 1; /** * Adds an item to the map and returns the ID of the item in the map. If an ID is given, the item is * mapped to that ID. Otherwise, the map automatically generates the ID and maps to that. * * id = myMap.addItem("foo") // ID internally generated * * id = myMap.addItem("foo", "bar") // ID is "foo" * */ this.addItem = function() { var item; if (arguments.length == 2) { var id = arguments[0]; item = arguments[1]; if (this.items[id]) { // Won't happen if given ID is string throw SceneJS_error.fatalError(SceneJS.errors.ID_CLASH, "ID clash: '" + id + "'"); } this.items[id] = item; return id; } else { while (true) { item = arguments[0]; var findId = lastUniqueId++; if (!this.items[findId]) { this.items[findId] = item; return findId; } } } }; /** * Removes the item of the given ID from the map */ this.removeItem = function(id) { delete this.items[id]; }; };
// Load global config and gulp import config from '../foley.json' import gulp from 'gulp' // Specific task modules import { argv as argv } from 'yargs' import debug from 'gulp-debug' import gulpif from 'gulp-if' import browserSync from 'browser-sync' import imagemin from 'gulp-imagemin' import pngquant from 'imagemin-pngquant' // Image minification task gulp.task('img', () => { return gulp.src(config.paths.img + '{,**/}*.{png,jpg,gif,svg}') .pipe(gulpif(argv.debug === true, debug({title: 'Images Optimised:'}))) .pipe(imagemin({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] })) .pipe(gulp.dest(config.paths.buildAssets + 'img')) .pipe(browserSync.stream()) })
goog.provide('ol.dom'); goog.require('goog.asserts'); goog.require('goog.userAgent'); goog.require('goog.vec.Mat4'); goog.require('ol'); /** * Create an html canvas element and returns its 2d context. * @param {number=} opt_width Canvas width. * @param {number=} opt_height Canvas height. * @return {CanvasRenderingContext2D} The context. */ ol.dom.createCanvasContext2D = function(opt_width, opt_height) { var canvas = document.createElement('CANVAS'); if (opt_width) { canvas.width = opt_width; } if (opt_height) { canvas.height = opt_height; } return canvas.getContext('2d'); }; /** * Detect 2d transform. * Adapted from http://stackoverflow.com/q/5661671/130442 * http://caniuse.com/#feat=transforms2d * @return {boolean} */ ol.dom.canUseCssTransform = (function() { var canUseCssTransform; return function() { if (canUseCssTransform === undefined) { goog.asserts.assert(document.body, 'document.body should not be null'); goog.asserts.assert(ol.global.getComputedStyle, 'getComputedStyle is required (unsupported browser?)'); var el = document.createElement('P'), has2d, transforms = { 'webkitTransform': '-webkit-transform', 'OTransform': '-o-transform', 'msTransform': '-ms-transform', 'MozTransform': '-moz-transform', 'transform': 'transform' }; document.body.appendChild(el); for (var t in transforms) { if (t in el.style) { el.style[t] = 'translate(1px,1px)'; has2d = ol.global.getComputedStyle(el).getPropertyValue( transforms[t]); } } document.body.removeChild(el); canUseCssTransform = (has2d && has2d !== 'none'); } return canUseCssTransform; }; }()); /** * Detect 3d transform. * Adapted from http://stackoverflow.com/q/5661671/130442 * http://caniuse.com/#feat=transforms3d * @return {boolean} */ ol.dom.canUseCssTransform3D = (function() { var canUseCssTransform3D; return function() { if (canUseCssTransform3D === undefined) { goog.asserts.assert(document.body, 'document.body should not be null'); goog.asserts.assert(ol.global.getComputedStyle, 'getComputedStyle is required (unsupported browser?)'); var el = document.createElement('P'), has3d, transforms = { 'webkitTransform': '-webkit-transform', 'OTransform': '-o-transform', 'msTransform': '-ms-transform', 'MozTransform': '-moz-transform', 'transform': 'transform' }; document.body.appendChild(el); for (var t in transforms) { if (t in el.style) { el.style[t] = 'translate3d(1px,1px,1px)'; has3d = ol.global.getComputedStyle(el).getPropertyValue( transforms[t]); } } document.body.removeChild(el); canUseCssTransform3D = (has3d && has3d !== 'none'); } return canUseCssTransform3D; }; }()); /** * @param {Element} element Element. * @param {string} value Value. */ ol.dom.setTransform = function(element, value) { var style = element.style; style.WebkitTransform = value; style.MozTransform = value; style.OTransform = value; style.msTransform = value; style.transform = value; // IE 9+ seems to assume transform-origin: 100% 100%; for some unknown reason if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9.0')) { element.style.transformOrigin = '0 0'; } }; /** * @param {!Element} element Element. * @param {goog.vec.Mat4.Number} transform Matrix. * @param {number=} opt_precision Precision. */ ol.dom.transformElement2D = function(element, transform, opt_precision) { // using matrix() causes gaps in Chrome and Firefox on Mac OS X, so prefer // matrix3d() var i; if (ol.dom.canUseCssTransform3D()) { var value3D; if (opt_precision !== undefined) { /** @type {Array.<string>} */ var strings3D = new Array(16); for (i = 0; i < 16; ++i) { strings3D[i] = transform[i].toFixed(opt_precision); } value3D = strings3D.join(','); } else { value3D = transform.join(','); } ol.dom.setTransform(element, 'matrix3d(' + value3D + ')'); } else if (ol.dom.canUseCssTransform()) { /** @type {Array.<number>} */ var transform2D = [ goog.vec.Mat4.getElement(transform, 0, 0), goog.vec.Mat4.getElement(transform, 1, 0), goog.vec.Mat4.getElement(transform, 0, 1), goog.vec.Mat4.getElement(transform, 1, 1), goog.vec.Mat4.getElement(transform, 0, 3), goog.vec.Mat4.getElement(transform, 1, 3) ]; var value2D; if (opt_precision !== undefined) { /** @type {Array.<string>} */ var strings2D = new Array(6); for (i = 0; i < 6; ++i) { strings2D[i] = transform2D[i].toFixed(opt_precision); } value2D = strings2D.join(','); } else { value2D = transform2D.join(','); } ol.dom.setTransform(element, 'matrix(' + value2D + ')'); } else { element.style.left = Math.round(goog.vec.Mat4.getElement(transform, 0, 3)) + 'px'; element.style.top = Math.round(goog.vec.Mat4.getElement(transform, 1, 3)) + 'px'; // TODO: Add scaling here. This isn't quite as simple as multiplying // width/height, because that only changes the container size, not the // content size. } }; /** * Get the current computed width for the given element including margin, * padding and border. * Equivalent to jQuery's `$(el).outerWidth(true)`. * @param {!Element} element Element. * @return {number} The width. */ ol.dom.outerWidth = function(element) { var width = element.offsetWidth; var style = element.currentStyle || ol.global.getComputedStyle(element); width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10); return width; }; /** * Get the current computed height for the given element including margin, * padding and border. * Equivalent to jQuery's `$(el).outerHeight(true)`. * @param {!Element} element Element. * @return {number} The height. */ ol.dom.outerHeight = function(element) { var height = element.offsetHeight; var style = element.currentStyle || ol.global.getComputedStyle(element); height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10); return height; };
/** * Rangy, a cross-browser JavaScript range and selection library * https://github.com/timdown/rangy * * Copyright 2015, Tim Down * Licensed under the MIT license. * Version: 1.3.0-alpha.20150122 * Build date: 22 January 2015 */ (function(factory, root) { if (typeof define == "function" && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof module != "undefined" && typeof exports == "object") { // Node/CommonJS style module.exports = factory(); } else { // No AMD or CommonJS support so we place Rangy in (probably) the global variable root.rangy = factory(); } })(function() { var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined"; // Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START // are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113. var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; // Minimal set of methods required for DOM Level 2 Range compliance var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore", "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents", "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"]; var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"]; // Subset of TextRange's full set of methods that we're interested in var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "moveToElementText", "parentElement", "select", "setEndPoint", "getBoundingClientRect"]; /*----------------------------------------------------------------------------------------------------------------*/ // Trio of functions taken from Peter Michaux's article: // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(o, p) { var t = typeof o[p]; return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown"; } function isHostObject(o, p) { return !!(typeof o[p] == OBJECT && o[p]); } function isHostProperty(o, p) { return typeof o[p] != UNDEFINED; } // Creates a convenience function to save verbose repeated calls to tests functions function createMultiplePropertyTest(testFunc) { return function(o, props) { var i = props.length; while (i--) { if (!testFunc(o, props[i])) { return false; } } return true; }; } // Next trio of functions are a convenience to save verbose repeated calls to previous two functions var areHostMethods = createMultiplePropertyTest(isHostMethod); var areHostObjects = createMultiplePropertyTest(isHostObject); var areHostProperties = createMultiplePropertyTest(isHostProperty); function isTextRange(range) { return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties); } function getBody(doc) { return isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0]; } var modules = {}; var isBrowser = (typeof window != UNDEFINED && typeof document != UNDEFINED); var util = { isHostMethod: isHostMethod, isHostObject: isHostObject, isHostProperty: isHostProperty, areHostMethods: areHostMethods, areHostObjects: areHostObjects, areHostProperties: areHostProperties, isTextRange: isTextRange, getBody: getBody }; var api = { version: "1.3.0-alpha.20150122", initialized: false, isBrowser: isBrowser, supported: true, util: util, features: {}, modules: modules, config: { alertOnFail: true, alertOnWarn: false, preferTextRange: false, autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize } }; function consoleLog(msg) { if (typeof console != UNDEFINED && isHostMethod(console, "log")) { console.log(msg); } } function alertOrLog(msg, shouldAlert) { if (isBrowser && shouldAlert) { alert(msg); } else { consoleLog(msg); } } function fail(reason) { api.initialized = true; api.supported = false; alertOrLog("Rangy is not supported in this environment. Reason: " + reason, api.config.alertOnFail); } api.fail = fail; function warn(msg) { alertOrLog("Rangy warning: " + msg, api.config.alertOnWarn); } api.warn = warn; // Add utility extend() method var extend; if ({}.hasOwnProperty) { util.extend = extend = function(obj, props, deep) { var o, p; for (var i in props) { if (props.hasOwnProperty(i)) { o = obj[i]; p = props[i]; if (deep && o !== null && typeof o == "object" && p !== null && typeof p == "object") { extend(o, p, true); } obj[i] = p; } } // Special case for toString, which does not show up in for...in loops in IE <= 8 if (props.hasOwnProperty("toString")) { obj.toString = props.toString; } return obj; }; util.createOptions = function(optionsParam, defaults) { var options = {}; extend(options, defaults); if (optionsParam) { extend(options, optionsParam); } return options; }; } else { fail("hasOwnProperty not supported"); } // Test whether we're in a browser and bail out if not if (!isBrowser) { fail("Rangy can only run in a browser"); } // Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not (function() { var toArray; if (isBrowser) { var el = document.createElement("div"); el.appendChild(document.createElement("span")); var slice = [].slice; try { if (slice.call(el.childNodes, 0)[0].nodeType == 1) { toArray = function(arrayLike) { return slice.call(arrayLike, 0); }; } } catch (e) {} } if (!toArray) { toArray = function(arrayLike) { var arr = []; for (var i = 0, len = arrayLike.length; i < len; ++i) { arr[i] = arrayLike[i]; } return arr; }; } util.toArray = toArray; })(); // Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or // normalization of event properties var addListener; if (isBrowser) { if (isHostMethod(document, "addEventListener")) { addListener = function(obj, eventType, listener) { obj.addEventListener(eventType, listener, false); }; } else if (isHostMethod(document, "attachEvent")) { addListener = function(obj, eventType, listener) { obj.attachEvent("on" + eventType, listener); }; } else { fail("Document does not have required addEventListener or attachEvent method"); } util.addListener = addListener; } var initListeners = []; function getErrorDesc(ex) { return ex.message || ex.description || String(ex); } // Initialization function init() { if (!isBrowser || api.initialized) { return; } var testRange; var implementsDomRange = false, implementsTextRange = false; // First, perform basic feature tests if (isHostMethod(document, "createRange")) { testRange = document.createRange(); if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) { implementsDomRange = true; } } var body = getBody(document); if (!body || body.nodeName.toLowerCase() != "body") { fail("No body element found"); return; } if (body && isHostMethod(body, "createTextRange")) { testRange = body.createTextRange(); if (isTextRange(testRange)) { implementsTextRange = true; } } if (!implementsDomRange && !implementsTextRange) { fail("Neither Range nor TextRange are available"); return; } api.initialized = true; api.features = { implementsDomRange: implementsDomRange, implementsTextRange: implementsTextRange }; // Initialize modules var module, errorMessage; for (var moduleName in modules) { if ( (module = modules[moduleName]) instanceof Module ) { module.init(module, api); } } // Call init listeners for (var i = 0, len = initListeners.length; i < len; ++i) { try { initListeners[i](api); } catch (ex) { errorMessage = "Rangy init listener threw an exception. Continuing. Detail: " + getErrorDesc(ex); consoleLog(errorMessage); } } } // Allow external scripts to initialize this library in case it's loaded after the document has loaded api.init = init; // Execute listener immediately if already initialized api.addInitListener = function(listener) { if (api.initialized) { listener(api); } else { initListeners.push(listener); } }; var shimListeners = []; api.addShimListener = function(listener) { shimListeners.push(listener); }; function shim(win) { win = win || window; init(); // Notify listeners for (var i = 0, len = shimListeners.length; i < len; ++i) { shimListeners[i](win); } } if (isBrowser) { api.shim = api.createMissingNativeApi = shim; } function Module(name, dependencies, initializer) { this.name = name; this.dependencies = dependencies; this.initialized = false; this.supported = false; this.initializer = initializer; } Module.prototype = { init: function() { var requiredModuleNames = this.dependencies || []; for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) { moduleName = requiredModuleNames[i]; requiredModule = modules[moduleName]; if (!requiredModule || !(requiredModule instanceof Module)) { throw new Error("required module '" + moduleName + "' not found"); } requiredModule.init(); if (!requiredModule.supported) { throw new Error("required module '" + moduleName + "' not supported"); } } // Now run initializer this.initializer(this); }, fail: function(reason) { this.initialized = true; this.supported = false; throw new Error("Module '" + this.name + "' failed to load: " + reason); }, warn: function(msg) { api.warn("Module " + this.name + ": " + msg); }, deprecationNotice: function(deprecated, replacement) { api.warn("DEPRECATED: " + deprecated + " in module " + this.name + "is deprecated. Please use " + replacement + " instead"); }, createError: function(msg) { return new Error("Error in Rangy " + this.name + " module: " + msg); } }; function createModule(name, dependencies, initFunc) { var newModule = new Module(name, dependencies, function(module) { if (!module.initialized) { module.initialized = true; try { initFunc(api, module); module.supported = true; } catch (ex) { var errorMessage = "Module '" + name + "' failed to load: " + getErrorDesc(ex); consoleLog(errorMessage); if (ex.stack) { consoleLog(ex.stack); } } } }); modules[name] = newModule; return newModule; } api.createModule = function(name) { // Allow 2 or 3 arguments (second argument is an optional array of dependencies) var initFunc, dependencies; if (arguments.length == 2) { initFunc = arguments[1]; dependencies = []; } else { initFunc = arguments[2]; dependencies = arguments[1]; } var module = createModule(name, dependencies, initFunc); // Initialize the module immediately if the core is already initialized if (api.initialized && api.supported) { module.init(); } }; api.createCoreModule = function(name, dependencies, initFunc) { createModule(name, dependencies, initFunc); }; /*----------------------------------------------------------------------------------------------------------------*/ // Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately function RangePrototype() {} api.RangePrototype = RangePrototype; api.rangePrototype = new RangePrototype(); function SelectionPrototype() {} api.selectionPrototype = new SelectionPrototype(); /*----------------------------------------------------------------------------------------------------------------*/ // DOM utility methods used by Rangy api.createCoreModule("DomUtil", [], function(api, module) { var UNDEF = "undefined"; var util = api.util; // Perform feature tests if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) { module.fail("document missing a Node creation method"); } if (!util.isHostMethod(document, "getElementsByTagName")) { module.fail("document missing getElementsByTagName method"); } var el = document.createElement("div"); if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) { module.fail("Incomplete Element implementation"); } // innerHTML is required for Range's createContextualFragment method if (!util.isHostProperty(el, "innerHTML")) { module.fail("Element is missing innerHTML property"); } var textNode = document.createTextNode("test"); if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) || !util.areHostProperties(textNode, ["data"]))) { module.fail("Incomplete Text Node implementation"); } /*----------------------------------------------------------------------------------------------------------------*/ // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that // contains just the document as a single element and the value searched for is the document. var arrayContains = /*Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val) > -1; }:*/ function(arr, val) { var i = arr.length; while (i--) { if (arr[i] === val) { return true; } } return false; }; // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI function isHtmlNamespace(node) { var ns; return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml"); } function parentElement(node) { var parent = node.parentNode; return (parent.nodeType == 1) ? parent : null; } function getNodeIndex(node) { var i = 0; while( (node = node.previousSibling) ) { ++i; } return i; } function getNodeLength(node) { switch (node.nodeType) { case 7: case 10: return 0; case 3: case 8: return node.length; default: return node.childNodes.length; } } function getCommonAncestor(node1, node2) { var ancestors = [], n; for (n = node1; n; n = n.parentNode) { ancestors.push(n); } for (n = node2; n; n = n.parentNode) { if (arrayContains(ancestors, n)) { return n; } } return null; } function isAncestorOf(ancestor, descendant, selfIsAncestor) { var n = selfIsAncestor ? descendant : descendant.parentNode; while (n) { if (n === ancestor) { return true; } else { n = n.parentNode; } } return false; } function isOrIsAncestorOf(ancestor, descendant) { return isAncestorOf(ancestor, descendant, true); } function getClosestAncestorIn(node, ancestor, selfIsAncestor) { var p, n = selfIsAncestor ? node : node.parentNode; while (n) { p = n.parentNode; if (p === ancestor) { return n; } n = p; } return null; } function isCharacterDataNode(node) { var t = node.nodeType; return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment } function isTextOrCommentNode(node) { if (!node) { return false; } var t = node.nodeType; return t == 3 || t == 8 ; // Text or Comment } function insertAfter(node, precedingNode) { var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode; if (nextNode) { parent.insertBefore(node, nextNode); } else { parent.appendChild(node); } return node; } // Note that we cannot use splitText() because it is bugridden in IE 9. function splitDataNode(node, index, positionsToPreserve) { var newNode = node.cloneNode(false); newNode.deleteData(0, index); node.deleteData(index, node.length - index); insertAfter(newNode, node); // Preserve positions if (positionsToPreserve) { for (var i = 0, position; position = positionsToPreserve[i++]; ) { // Handle case where position was inside the portion of node after the split point if (position.node == node && position.offset > index) { position.node = newNode; position.offset -= index; } // Handle the case where the position is a node offset within node's parent else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) { ++position.offset; } } } return newNode; } function getDocument(node) { if (node.nodeType == 9) { return node; } else if (typeof node.ownerDocument != UNDEF) { return node.ownerDocument; } else if (typeof node.document != UNDEF) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); } else { throw module.createError("getDocument: no document found for node"); } } function getWindow(node) { var doc = getDocument(node); if (typeof doc.defaultView != UNDEF) { return doc.defaultView; } else if (typeof doc.parentWindow != UNDEF) { return doc.parentWindow; } else { throw module.createError("Cannot get a window object for node"); } } function getIframeDocument(iframeEl) { if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument; } else if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow.document; } else { throw module.createError("getIframeDocument: No Document object found for iframe element"); } } function getIframeWindow(iframeEl) { if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow; } else if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument.defaultView; } else { throw module.createError("getIframeWindow: No Window object found for iframe element"); } } // This looks bad. Is it worth it? function isWindow(obj) { return obj && util.isHostMethod(obj, "setTimeout") && util.isHostObject(obj, "document"); } function getContentDocument(obj, module, methodName) { var doc; if (!obj) { doc = document; } // Test if a DOM node has been passed and obtain a document object for it if so else if (util.isHostProperty(obj, "nodeType")) { doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == "iframe") ? getIframeDocument(obj) : getDocument(obj); } // Test if the doc parameter appears to be a Window object else if (isWindow(obj)) { doc = obj.document; } if (!doc) { throw module.createError(methodName + "(): Parameter must be a Window object or DOM node"); } return doc; } function getRootContainer(node) { var parent; while ( (parent = node.parentNode) ) { node = parent; } return node; } function comparePoints(nodeA, offsetA, nodeB, offsetB) { // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing var nodeC, root, childA, childB, n; if (nodeA == nodeB) { // Case 1: nodes are the same return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) { // Case 2: node C (container B or an ancestor) is a child node of A return offsetA <= getNodeIndex(nodeC) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) { // Case 3: node C (container A or an ancestor) is a child node of B return getNodeIndex(nodeC) < offsetB ? -1 : 1; } else { root = getCommonAncestor(nodeA, nodeB); if (!root) { throw new Error("comparePoints error: nodes have no common ancestor"); } // Case 4: containers are siblings or descendants of siblings childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true); childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true); if (childA === childB) { // This shouldn't be possible throw module.createError("comparePoints got to case 4 and childA and childB are the same!"); } else { n = root.firstChild; while (n) { if (n === childA) { return -1; } else if (n === childB) { return 1; } n = n.nextSibling; } } } } /*----------------------------------------------------------------------------------------------------------------*/ // Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried var crashyTextNodes = false; function isBrokenNode(node) { var n; try { n = node.parentNode; return false; } catch (e) { return true; } } (function() { var el = document.createElement("b"); el.innerHTML = "1"; var textNode = el.firstChild; el.innerHTML = "<br />"; crashyTextNodes = isBrokenNode(textNode); api.features.crashyTextNodes = crashyTextNodes; })(); /*----------------------------------------------------------------------------------------------------------------*/ function inspectNode(node) { if (!node) { return "[No node]"; } if (crashyTextNodes && isBrokenNode(node)) { return "[Broken node]"; } if (isCharacterDataNode(node)) { return '"' + node.data + '"'; } if (node.nodeType == 1) { var idAttr = node.id ? ' id="' + node.id + '"' : ""; return "<" + node.nodeName + idAttr + ">[index:" + getNodeIndex(node) + ",length:" + node.childNodes.length + "][" + (node.innerHTML || "[innerHTML not supported]").slice(0, 25) + "]"; } return node.nodeName; } function fragmentFromNodeChildren(node) { var fragment = getDocument(node).createDocumentFragment(), child; while ( (child = node.firstChild) ) { fragment.appendChild(child); } return fragment; } var getComputedStyleProperty; if (typeof window.getComputedStyle != UNDEF) { getComputedStyleProperty = function(el, propName) { return getWindow(el).getComputedStyle(el, null)[propName]; }; } else if (typeof document.documentElement.currentStyle != UNDEF) { getComputedStyleProperty = function(el, propName) { return el.currentStyle[propName]; }; } else { module.fail("No means of obtaining computed style properties found"); } function NodeIterator(root) { this.root = root; this._next = root; } NodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { var n = this._current = this._next; var child, next; if (this._current) { child = n.firstChild; if (child) { this._next = child; } else { next = null; while ((n !== this.root) && !(next = n.nextSibling)) { n = n.parentNode; } this._next = next; } } return this._current; }, detach: function() { this._current = this._next = this.root = null; } }; function createIterator(root) { return new NodeIterator(root); } function DomPosition(node, offset) { this.node = node; this.offset = offset; } DomPosition.prototype = { equals: function(pos) { return !!pos && this.node === pos.node && this.offset == pos.offset; }, inspect: function() { return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]"; }, toString: function() { return this.inspect(); } }; function DOMException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "DOMException: " + this.codeName; } DOMException.prototype = { INDEX_SIZE_ERR: 1, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INVALID_STATE_ERR: 11, INVALID_NODE_TYPE_ERR: 24 }; DOMException.prototype.toString = function() { return this.message; }; api.dom = { arrayContains: arrayContains, isHtmlNamespace: isHtmlNamespace, parentElement: parentElement, getNodeIndex: getNodeIndex, getNodeLength: getNodeLength, getCommonAncestor: getCommonAncestor, isAncestorOf: isAncestorOf, isOrIsAncestorOf: isOrIsAncestorOf, getClosestAncestorIn: getClosestAncestorIn, isCharacterDataNode: isCharacterDataNode, isTextOrCommentNode: isTextOrCommentNode, insertAfter: insertAfter, splitDataNode: splitDataNode, getDocument: getDocument, getWindow: getWindow, getIframeWindow: getIframeWindow, getIframeDocument: getIframeDocument, getBody: util.getBody, isWindow: isWindow, getContentDocument: getContentDocument, getRootContainer: getRootContainer, comparePoints: comparePoints, isBrokenNode: isBrokenNode, inspectNode: inspectNode, getComputedStyleProperty: getComputedStyleProperty, fragmentFromNodeChildren: fragmentFromNodeChildren, createIterator: createIterator, DomPosition: DomPosition }; api.DOMException = DOMException; }); /*----------------------------------------------------------------------------------------------------------------*/ // Pure JavaScript implementation of DOM Range api.createCoreModule("DomRange", ["DomUtil"], function(api, module) { var dom = api.dom; var util = api.util; var DomPosition = dom.DomPosition; var DOMException = api.DOMException; var isCharacterDataNode = dom.isCharacterDataNode; var getNodeIndex = dom.getNodeIndex; var isOrIsAncestorOf = dom.isOrIsAncestorOf; var getDocument = dom.getDocument; var comparePoints = dom.comparePoints; var splitDataNode = dom.splitDataNode; var getClosestAncestorIn = dom.getClosestAncestorIn; var getNodeLength = dom.getNodeLength; var arrayContains = dom.arrayContains; var getRootContainer = dom.getRootContainer; var crashyTextNodes = api.features.crashyTextNodes; /*----------------------------------------------------------------------------------------------------------------*/ // Utility functions function isNonTextPartiallySelected(node, range) { return (node.nodeType != 3) && (isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer)); } function getRangeDocument(range) { return range.document || getDocument(range.startContainer); } function getBoundaryBeforeNode(node) { return new DomPosition(node.parentNode, getNodeIndex(node)); } function getBoundaryAfterNode(node) { return new DomPosition(node.parentNode, getNodeIndex(node) + 1); } function insertNodeAtPosition(node, n, o) { var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node; if (isCharacterDataNode(n)) { if (o == n.length) { dom.insertAfter(node, n); } else { n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o)); } } else if (o >= n.childNodes.length) { n.appendChild(node); } else { n.insertBefore(node, n.childNodes[o]); } return firstNodeInserted; } function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) { assertRangeValid(rangeA); assertRangeValid(rangeB); if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset), endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; } function cloneSubtree(iterator) { var partiallySelected; for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { partiallySelected = iterator.isPartiallySelectedSubtree(); node = node.cloneNode(!partiallySelected); if (partiallySelected) { subIterator = iterator.getSubtreeIterator(); node.appendChild(cloneSubtree(subIterator)); subIterator.detach(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function iterateSubtree(rangeIterator, func, iteratorState) { var it, n; iteratorState = iteratorState || { stop: false }; for (var node, subRangeIterator; node = rangeIterator.next(); ) { if (rangeIterator.isPartiallySelectedSubtree()) { if (func(node) === false) { iteratorState.stop = true; return; } else { // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of // the node selected by the Range. subRangeIterator = rangeIterator.getSubtreeIterator(); iterateSubtree(subRangeIterator, func, iteratorState); subRangeIterator.detach(); if (iteratorState.stop) { return; } } } else { // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its // descendants it = dom.createIterator(node); while ( (n = it.next()) ) { if (func(n) === false) { iteratorState.stop = true; return; } } } } } function deleteSubtree(iterator) { var subIterator; while (iterator.next()) { if (iterator.isPartiallySelectedSubtree()) { subIterator = iterator.getSubtreeIterator(); deleteSubtree(subIterator); subIterator.detach(); } else { iterator.remove(); } } } function extractSubtree(iterator) { for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { if (iterator.isPartiallySelectedSubtree()) { node = node.cloneNode(false); subIterator = iterator.getSubtreeIterator(); node.appendChild(extractSubtree(subIterator)); subIterator.detach(); } else { iterator.remove(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function getNodesInRange(range, nodeTypes, filter) { var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex; var filterExists = !!filter; if (filterNodeTypes) { regex = new RegExp("^(" + nodeTypes.join("|") + ")$"); } var nodes = []; iterateSubtree(new RangeIterator(range, false), function(node) { if (filterNodeTypes && !regex.test(node.nodeType)) { return; } if (filterExists && !filter(node)) { return; } // Don't include a boundary container if it is a character data node and the range does not contain any // of its character data. See issue 190. var sc = range.startContainer; if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) { return; } var ec = range.endContainer; if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) { return; } nodes.push(node); }); return nodes; } function inspect(range) { var name = (typeof range.getName == "undefined") ? "Range" : range.getName(); return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " + dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]"; } /*----------------------------------------------------------------------------------------------------------------*/ // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange) function RangeIterator(range, clonePartiallySelectedTextNodes) { this.range = range; this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes; if (!range.collapsed) { this.sc = range.startContainer; this.so = range.startOffset; this.ec = range.endContainer; this.eo = range.endOffset; var root = range.commonAncestorContainer; if (this.sc === this.ec && isCharacterDataNode(this.sc)) { this.isSingleCharacterDataNode = true; this._first = this._last = this._next = this.sc; } else { this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ? this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true); this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ? this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true); } } } RangeIterator.prototype = { _current: null, _next: null, _first: null, _last: null, isSingleCharacterDataNode: false, reset: function() { this._current = null; this._next = this._first; }, hasNext: function() { return !!this._next; }, next: function() { // Move to next node var current = this._current = this._next; if (current) { this._next = (current !== this._last) ? current.nextSibling : null; // Check for partially selected text nodes if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) { if (current === this.ec) { (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo); } if (this._current === this.sc) { (current = current.cloneNode(true)).deleteData(0, this.so); } } } return current; }, remove: function() { var current = this._current, start, end; if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) { start = (current === this.sc) ? this.so : 0; end = (current === this.ec) ? this.eo : current.length; if (start != end) { current.deleteData(start, end - start); } } else { if (current.parentNode) { current.parentNode.removeChild(current); } else { } } }, // Checks if the current node is partially selected isPartiallySelectedSubtree: function() { var current = this._current; return isNonTextPartiallySelected(current, this.range); }, getSubtreeIterator: function() { var subRange; if (this.isSingleCharacterDataNode) { subRange = this.range.cloneRange(); subRange.collapse(false); } else { subRange = new Range(getRangeDocument(this.range)); var current = this._current; var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current); if (isOrIsAncestorOf(current, this.sc)) { startContainer = this.sc; startOffset = this.so; } if (isOrIsAncestorOf(current, this.ec)) { endContainer = this.ec; endOffset = this.eo; } updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset); } return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes); }, detach: function() { this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null; } }; /*----------------------------------------------------------------------------------------------------------------*/ var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10]; var rootContainerNodeTypes = [2, 9, 11]; var readonlyNodeTypes = [5, 6, 10, 12]; var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11]; var surroundNodeTypes = [1, 3, 4, 5, 7, 8]; function createAncestorFinder(nodeTypes) { return function(node, selfIsAncestor) { var t, n = selfIsAncestor ? node : node.parentNode; while (n) { t = n.nodeType; if (arrayContains(nodeTypes, t)) { return n; } n = n.parentNode; } return null; }; } var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] ); var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes); var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] ); function assertNoDocTypeNotationEntityAncestor(node, allowSelf) { if (getDocTypeNotationEntityAncestor(node, allowSelf)) { throw new DOMException("INVALID_NODE_TYPE_ERR"); } } function assertValidNodeType(node, invalidTypes) { if (!arrayContains(invalidTypes, node.nodeType)) { throw new DOMException("INVALID_NODE_TYPE_ERR"); } } function assertValidOffset(node, offset) { if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) { throw new DOMException("INDEX_SIZE_ERR"); } } function assertSameDocumentOrFragment(node1, node2) { if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } function assertNodeNotReadOnly(node) { if (getReadonlyAncestor(node, true)) { throw new DOMException("NO_MODIFICATION_ALLOWED_ERR"); } } function assertNode(node, codeName) { if (!node) { throw new DOMException(codeName); } } function isOrphan(node) { return (crashyTextNodes && dom.isBrokenNode(node)) || !arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true); } function isValidOffset(node, offset) { return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length); } function isRangeValid(range) { return (!!range.startContainer && !!range.endContainer && !isOrphan(range.startContainer) && !isOrphan(range.endContainer) && isValidOffset(range.startContainer, range.startOffset) && isValidOffset(range.endContainer, range.endOffset)); } function assertRangeValid(range) { if (!isRangeValid(range)) { throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")"); } } /*----------------------------------------------------------------------------------------------------------------*/ // Test the browser's innerHTML support to decide how to implement createContextualFragment var styleEl = document.createElement("style"); var htmlParsingConforms = false; try { styleEl.innerHTML = "<b>x</b>"; htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node } catch (e) { // IE 6 and 7 throw } api.features.htmlParsingConforms = htmlParsingConforms; var createContextualFragment = htmlParsingConforms ? // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See // discussion and base code for this implementation at issue 67. // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface // Thanks to Aleks Williams. function(fragmentStr) { // "Let node the context object's start's node." var node = this.startContainer; var doc = getDocument(node); // "If the context object's start's node is null, raise an INVALID_STATE_ERR // exception and abort these steps." if (!node) { throw new DOMException("INVALID_STATE_ERR"); } // "Let element be as follows, depending on node's interface:" // Document, Document Fragment: null var el = null; // "Element: node" if (node.nodeType == 1) { el = node; // "Text, Comment: node's parentElement" } else if (isCharacterDataNode(node)) { el = dom.parentElement(node); } // "If either element is null or element's ownerDocument is an HTML document // and element's local name is "html" and element's namespace is the HTML // namespace" if (el === null || ( el.nodeName == "HTML" && dom.isHtmlNamespace(getDocument(el).documentElement) && dom.isHtmlNamespace(el) )) { // "let element be a new Element with "body" as its local name and the HTML // namespace as its namespace."" el = doc.createElement("body"); } else { el = el.cloneNode(false); } // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm." // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm." // "In either case, the algorithm must be invoked with fragment as the input // and element as the context element." el.innerHTML = fragmentStr; // "If this raises an exception, then abort these steps. Otherwise, let new // children be the nodes returned." // "Let fragment be a new DocumentFragment." // "Append all new children to fragment." // "Return fragment." return dom.fragmentFromNodeChildren(el); } : // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that // previous versions of Rangy used (with the exception of using a body element rather than a div) function(fragmentStr) { var doc = getRangeDocument(this); var el = doc.createElement("body"); el.innerHTML = fragmentStr; return dom.fragmentFromNodeChildren(el); }; function splitRangeBoundaries(range, positionsToPreserve) { assertRangeValid(range); var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset; var startEndSame = (sc === ec); if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) { splitDataNode(ec, eo, positionsToPreserve); } if (isCharacterDataNode(sc) && so > 0 && so < sc.length) { sc = splitDataNode(sc, so, positionsToPreserve); if (startEndSame) { eo -= so; ec = sc; } else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) { eo++; } so = 0; } range.setStartAndEnd(sc, so, ec, eo); } function rangeToHtml(range) { assertRangeValid(range); var container = range.commonAncestorContainer.parentNode.cloneNode(false); container.appendChild( range.cloneContents() ); return container.innerHTML; } /*----------------------------------------------------------------------------------------------------------------*/ var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; var s2s = 0, s2e = 1, e2e = 2, e2s = 3; var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3; util.extend(api.rangePrototype, { compareBoundaryPoints: function(how, range) { assertRangeValid(this); assertSameDocumentOrFragment(this.startContainer, range.startContainer); var nodeA, offsetA, nodeB, offsetB; var prefixA = (how == e2s || how == s2s) ? "start" : "end"; var prefixB = (how == s2e || how == s2s) ? "start" : "end"; nodeA = this[prefixA + "Container"]; offsetA = this[prefixA + "Offset"]; nodeB = range[prefixB + "Container"]; offsetB = range[prefixB + "Offset"]; return comparePoints(nodeA, offsetA, nodeB, offsetB); }, insertNode: function(node) { assertRangeValid(this); assertValidNodeType(node, insertableNodeTypes); assertNodeNotReadOnly(this.startContainer); if (isOrIsAncestorOf(node, this.startContainer)) { throw new DOMException("HIERARCHY_REQUEST_ERR"); } // No check for whether the container of the start of the Range is of a type that does not allow // children of the type of node: the browser's DOM implementation should do this for us when we attempt // to add the node var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset); this.setStartBefore(firstNodeInserted); }, cloneContents: function() { assertRangeValid(this); var clone, frag; if (this.collapsed) { return getRangeDocument(this).createDocumentFragment(); } else { if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) { clone = this.startContainer.cloneNode(true); clone.data = clone.data.slice(this.startOffset, this.endOffset); frag = getRangeDocument(this).createDocumentFragment(); frag.appendChild(clone); return frag; } else { var iterator = new RangeIterator(this, true); clone = cloneSubtree(iterator); iterator.detach(); } return clone; } }, canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, surroundContents: function(node) { assertValidNodeType(node, surroundNodeTypes); if (!this.canSurroundContents()) { throw new DOMException("INVALID_STATE_ERR"); } // Extract the contents var content = this.extractContents(); // Clear the children of the node if (node.hasChildNodes()) { while (node.lastChild) { node.removeChild(node.lastChild); } } // Insert the new node and add the extracted contents insertNodeAtPosition(node, this.startContainer, this.startOffset); node.appendChild(content); this.selectNode(node); }, cloneRange: function() { assertRangeValid(this); var range = new Range(getRangeDocument(this)); var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = this[prop]; } return range; }, toString: function() { assertRangeValid(this); var sc = this.startContainer; if (sc === this.endContainer && isCharacterDataNode(sc)) { return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : ""; } else { var textParts = [], iterator = new RangeIterator(this, true); iterateSubtree(iterator, function(node) { // Accept only text or CDATA nodes, not comments if (node.nodeType == 3 || node.nodeType == 4) { textParts.push(node.data); } }); iterator.detach(); return textParts.join(""); } }, // The methods below are all non-standard. The following batch were introduced by Mozilla but have since // been removed from Mozilla. compareNode: function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }, comparePoint: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) { return -1; } else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) { return 1; } return 0; }, createContextualFragment: createContextualFragment, toHtml: function() { return rangeToHtml(this); }, // touchingIsIntersecting determines whether this method considers a node that borders a range intersects // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default) intersectsNode: function(node, touchingIsIntersecting) { assertRangeValid(this); assertNode(node, "NOT_FOUND_ERR"); if (getDocument(node) !== getRangeDocument(this)) { return false; } var parent = node.parentNode, offset = getNodeIndex(node); assertNode(parent, "NOT_FOUND_ERR"); var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset), endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, isPointInRange: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) && (comparePoints(node, offset, this.endContainer, this.endOffset) <= 0); }, // The methods below are non-standard and invented by me. // Sharing a boundary start-to-end or end-to-start does not count as intersection. intersectsRange: function(range) { return rangesIntersect(this, range, false); }, // Sharing a boundary start-to-end or end-to-start does count as intersection. intersectsOrTouchesRange: function(range) { return rangesIntersect(this, range, true); }, intersection: function(range) { if (this.intersectsRange(range)) { var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset), endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset); var intersectionRange = this.cloneRange(); if (startComparison == -1) { intersectionRange.setStart(range.startContainer, range.startOffset); } if (endComparison == 1) { intersectionRange.setEnd(range.endContainer, range.endOffset); } return intersectionRange; } return null; }, union: function(range) { if (this.intersectsOrTouchesRange(range)) { var unionRange = this.cloneRange(); if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) { unionRange.setStart(range.startContainer, range.startOffset); } if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) { unionRange.setEnd(range.endContainer, range.endOffset); } return unionRange; } else { throw new DOMException("Ranges do not intersect"); } }, containsNode: function(node, allowPartial) { if (allowPartial) { return this.intersectsNode(node, false); } else { return this.compareNode(node) == n_i; } }, containsNodeContents: function(node) { return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0; }, containsRange: function(range) { var intersection = this.intersection(range); return intersection !== null && range.equals(intersection); }, containsNodeText: function(node) { var nodeRange = this.cloneRange(); nodeRange.selectNode(node); var textNodes = nodeRange.getNodes([3]); if (textNodes.length > 0) { nodeRange.setStart(textNodes[0], 0); var lastTextNode = textNodes.pop(); nodeRange.setEnd(lastTextNode, lastTextNode.length); return this.containsRange(nodeRange); } else { return this.containsNodeContents(node); } }, getNodes: function(nodeTypes, filter) { assertRangeValid(this); return getNodesInRange(this, nodeTypes, filter); }, getDocument: function() { return getRangeDocument(this); }, collapseBefore: function(node) { this.setEndBefore(node); this.collapse(false); }, collapseAfter: function(node) { this.setStartAfter(node); this.collapse(true); }, getBookmark: function(containerNode) { var doc = getRangeDocument(this); var preSelectionRange = api.createRange(doc); containerNode = containerNode || dom.getBody(doc); preSelectionRange.selectNodeContents(containerNode); var range = this.intersection(preSelectionRange); var start = 0, end = 0; if (range) { preSelectionRange.setEnd(range.startContainer, range.startOffset); start = preSelectionRange.toString().length; end = start + range.toString().length; } return { start: start, end: end, containerNode: containerNode }; }, moveToBookmark: function(bookmark) { var containerNode = bookmark.containerNode; var charIndex = 0; this.setStart(containerNode, 0); this.collapse(true); var nodeStack = [containerNode], node, foundStart = false, stop = false; var nextCharIndex, i, childNodes; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { nextCharIndex = charIndex + node.length; if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) { this.setStart(node, bookmark.start - charIndex); foundStart = true; } if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) { this.setEnd(node, bookmark.end - charIndex); stop = true; } charIndex = nextCharIndex; } else { childNodes = node.childNodes; i = childNodes.length; while (i--) { nodeStack.push(childNodes[i]); } } } }, getName: function() { return "DomRange"; }, equals: function(range) { return Range.rangesEqual(this, range); }, isValid: function() { return isRangeValid(this); }, inspect: function() { return inspect(this); }, detach: function() { // In DOM4, detach() is now a no-op. } }); function copyComparisonConstantsToObject(obj) { obj.START_TO_START = s2s; obj.START_TO_END = s2e; obj.END_TO_END = e2e; obj.END_TO_START = e2s; obj.NODE_BEFORE = n_b; obj.NODE_AFTER = n_a; obj.NODE_BEFORE_AND_AFTER = n_b_a; obj.NODE_INSIDE = n_i; } function copyComparisonConstants(constructor) { copyComparisonConstantsToObject(constructor); copyComparisonConstantsToObject(constructor.prototype); } function createRangeContentRemover(remover, boundaryUpdater) { return function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer; var iterator = new RangeIterator(this, true); // Work out where to position the range after content removal var node, boundary; if (sc !== root) { node = getClosestAncestorIn(sc, root, true); boundary = getBoundaryAfterNode(node); sc = boundary.node; so = boundary.offset; } // Check none of the range is read-only iterateSubtree(iterator, assertNodeNotReadOnly); iterator.reset(); // Remove the content var returnValue = remover(iterator); iterator.detach(); // Move to the new position boundaryUpdater(this, sc, so, sc, so); return returnValue; }; } function createPrototypeRange(constructor, boundaryUpdater) { function createBeforeAfterNodeSetter(isBefore, isStart) { return function(node) { assertValidNodeType(node, beforeAfterNodeTypes); assertValidNodeType(getRootContainer(node), rootContainerNodeTypes); var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node); (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset); }; } function setRangeStart(range, node, offset) { var ec = range.endContainer, eo = range.endOffset; if (node !== range.startContainer || offset !== range.startOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) { ec = node; eo = offset; } boundaryUpdater(range, node, offset, ec, eo); } } function setRangeEnd(range, node, offset) { var sc = range.startContainer, so = range.startOffset; if (node !== range.endContainer || offset !== range.endOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) { sc = node; so = offset; } boundaryUpdater(range, sc, so, node, offset); } } // Set up inheritance var F = function() {}; F.prototype = api.rangePrototype; constructor.prototype = new F(); util.extend(constructor.prototype, { setStart: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStart(this, node, offset); }, setEnd: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeEnd(this, node, offset); }, /** * Convenience method to set a range's start and end boundaries. Overloaded as follows: * - Two parameters (node, offset) creates a collapsed range at that position * - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at * startOffset and ending at endOffset * - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in * startNode and ending at endOffset in endNode */ setStartAndEnd: function() { var args = arguments; var sc = args[0], so = args[1], ec = sc, eo = so; switch (args.length) { case 3: eo = args[2]; break; case 4: ec = args[2]; eo = args[3]; break; } boundaryUpdater(this, sc, so, ec, eo); }, setBoundary: function(node, offset, isStart) { this["set" + (isStart ? "Start" : "End")](node, offset); }, setStartBefore: createBeforeAfterNodeSetter(true, true), setStartAfter: createBeforeAfterNodeSetter(false, true), setEndBefore: createBeforeAfterNodeSetter(true, false), setEndAfter: createBeforeAfterNodeSetter(false, false), collapse: function(isStart) { assertRangeValid(this); if (isStart) { boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset); } else { boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset); } }, selectNodeContents: function(node) { assertNoDocTypeNotationEntityAncestor(node, true); boundaryUpdater(this, node, 0, node, getNodeLength(node)); }, selectNode: function(node) { assertNoDocTypeNotationEntityAncestor(node, false); assertValidNodeType(node, beforeAfterNodeTypes); var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node); boundaryUpdater(this, start.node, start.offset, end.node, end.offset); }, extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater), deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater), canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && isNonTextPartiallySelected(iterator._first, this) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, splitBoundaries: function() { splitRangeBoundaries(this); }, splitBoundariesPreservingPositions: function(positionsToPreserve) { splitRangeBoundaries(this, positionsToPreserve); }, normalizeBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var mergeForward = function(node) { var sibling = node.nextSibling; if (sibling && sibling.nodeType == node.nodeType) { ec = node; eo = node.length; node.appendData(sibling.data); sibling.parentNode.removeChild(sibling); } }; var mergeBackward = function(node) { var sibling = node.previousSibling; if (sibling && sibling.nodeType == node.nodeType) { sc = node; var nodeLength = node.length; so = sibling.length; node.insertData(0, sibling.data); sibling.parentNode.removeChild(sibling); if (sc == ec) { eo += so; ec = sc; } else if (ec == node.parentNode) { var nodeIndex = getNodeIndex(node); if (eo == nodeIndex) { ec = node; eo = nodeLength; } else if (eo > nodeIndex) { eo--; } } } }; var normalizeStart = true; if (isCharacterDataNode(ec)) { if (ec.length == eo) { mergeForward(ec); } } else { if (eo > 0) { var endNode = ec.childNodes[eo - 1]; if (endNode && isCharacterDataNode(endNode)) { mergeForward(endNode); } } normalizeStart = !this.collapsed; } if (normalizeStart) { if (isCharacterDataNode(sc)) { if (so == 0) { mergeBackward(sc); } } else { if (so < sc.childNodes.length) { var startNode = sc.childNodes[so]; if (startNode && isCharacterDataNode(startNode)) { mergeBackward(startNode); } } } } else { sc = ec; so = eo; } boundaryUpdater(this, sc, so, ec, eo); }, collapseToPoint: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); this.setStartAndEnd(node, offset); } }); copyComparisonConstants(constructor); } /*----------------------------------------------------------------------------------------------------------------*/ // Updates commonAncestorContainer and collapsed after boundary change function updateCollapsedAndCommonAncestor(range) { range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); range.commonAncestorContainer = range.collapsed ? range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer); } function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) { range.startContainer = startContainer; range.startOffset = startOffset; range.endContainer = endContainer; range.endOffset = endOffset; range.document = dom.getDocument(startContainer); updateCollapsedAndCommonAncestor(range); } function Range(doc) { this.startContainer = doc; this.startOffset = 0; this.endContainer = doc; this.endOffset = 0; this.document = doc; updateCollapsedAndCommonAncestor(this); } createPrototypeRange(Range, updateBoundaries); util.extend(Range, { rangeProperties: rangeProperties, RangeIterator: RangeIterator, copyComparisonConstants: copyComparisonConstants, createPrototypeRange: createPrototypeRange, inspect: inspect, toHtml: rangeToHtml, getRangeDocument: getRangeDocument, rangesEqual: function(r1, r2) { return r1.startContainer === r2.startContainer && r1.startOffset === r2.startOffset && r1.endContainer === r2.endContainer && r1.endOffset === r2.endOffset; } }); api.DomRange = Range; }); /*----------------------------------------------------------------------------------------------------------------*/ // Wrappers for the browser's native DOM Range and/or TextRange implementation api.createCoreModule("WrappedRange", ["DomRange"], function(api, module) { var WrappedRange, WrappedTextRange; var dom = api.dom; var util = api.util; var DomPosition = dom.DomPosition; var DomRange = api.DomRange; var getBody = dom.getBody; var getContentDocument = dom.getContentDocument; var isCharacterDataNode = dom.isCharacterDataNode; /*----------------------------------------------------------------------------------------------------------------*/ if (api.features.implementsDomRange) { // This is a wrapper around the browser's native DOM Range. It has two aims: // - Provide workarounds for specific browser bugs // - provide convenient extensions, which are inherited from Rangy's DomRange (function() { var rangeProto; var rangeProperties = DomRange.rangeProperties; function updateRangeProperties(range) { var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = range.nativeRange[prop]; } // Fix for broken collapsed property in IE 9. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); } function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset); var nativeRangeDifferent = !range.equals(range.nativeRange); // Always set both boundaries for the benefit of IE9 (see issue 35) if (startMoved || endMoved || nativeRangeDifferent) { range.setEnd(endContainer, endOffset); range.setStart(startContainer, startOffset); } } var createBeforeAfterNodeSetter; WrappedRange = function(range) { if (!range) { throw module.createError("WrappedRange: Range must be specified"); } this.nativeRange = range; updateRangeProperties(this); }; DomRange.createPrototypeRange(WrappedRange, updateNativeRange); rangeProto = WrappedRange.prototype; rangeProto.selectNode = function(node) { this.nativeRange.selectNode(node); updateRangeProperties(this); }; rangeProto.cloneContents = function() { return this.nativeRange.cloneContents(); }; // Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect, // insertNode() is never delegated to the native range. rangeProto.surroundContents = function(node) { this.nativeRange.surroundContents(node); updateRangeProperties(this); }; rangeProto.collapse = function(isStart) { this.nativeRange.collapse(isStart); updateRangeProperties(this); }; rangeProto.cloneRange = function() { return new WrappedRange(this.nativeRange.cloneRange()); }; rangeProto.refresh = function() { updateRangeProperties(this); }; rangeProto.toString = function() { return this.nativeRange.toString(); }; // Create test range and node for feature detection var testTextNode = document.createTextNode("test"); getBody(document).appendChild(testTextNode); var range = document.createRange(); /*--------------------------------------------------------------------------------------------------------*/ // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and // correct for it range.setStart(testTextNode, 0); range.setEnd(testTextNode, 0); try { range.setStart(testTextNode, 1); rangeProto.setStart = function(node, offset) { this.nativeRange.setStart(node, offset); updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { this.nativeRange.setEnd(node, offset); updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name) { return function(node) { this.nativeRange[name](node); updateRangeProperties(this); }; }; } catch(ex) { rangeProto.setStart = function(node, offset) { try { this.nativeRange.setStart(node, offset); } catch (ex) { this.nativeRange.setEnd(node, offset); this.nativeRange.setStart(node, offset); } updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { try { this.nativeRange.setEnd(node, offset); } catch (ex) { this.nativeRange.setStart(node, offset); this.nativeRange.setEnd(node, offset); } updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name, oppositeName) { return function(node) { try { this.nativeRange[name](node); } catch (ex) { this.nativeRange[oppositeName](node); this.nativeRange[name](node); } updateRangeProperties(this); }; }; } rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore"); rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter"); rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore"); rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter"); /*--------------------------------------------------------------------------------------------------------*/ // Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing // whether the native implementation can be trusted rangeProto.selectNodeContents = function(node) { this.setStartAndEnd(node, 0, dom.getNodeLength(node)); }; /*--------------------------------------------------------------------------------------------------------*/ // Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for // constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738 range.selectNodeContents(testTextNode); range.setEnd(testTextNode, 3); var range2 = document.createRange(); range2.selectNodeContents(testTextNode); range2.setEnd(testTextNode, 4); range2.setStart(testTextNode, 2); if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 && range.compareBoundaryPoints(range.END_TO_START, range2) == 1) { // This is the wrong way round, so correct for it rangeProto.compareBoundaryPoints = function(type, range) { range = range.nativeRange || range; if (type == range.START_TO_END) { type = range.END_TO_START; } else if (type == range.END_TO_START) { type = range.START_TO_END; } return this.nativeRange.compareBoundaryPoints(type, range); }; } else { rangeProto.compareBoundaryPoints = function(type, range) { return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for IE deleteContents() and extractContents() bug and correct it. See issue 107. var el = document.createElement("div"); el.innerHTML = "123"; var textNode = el.firstChild; var body = getBody(document); body.appendChild(el); range.setStart(textNode, 1); range.setEnd(textNode, 2); range.deleteContents(); if (textNode.data == "13") { // Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and // extractContents() rangeProto.deleteContents = function() { this.nativeRange.deleteContents(); updateRangeProperties(this); }; rangeProto.extractContents = function() { var frag = this.nativeRange.extractContents(); updateRangeProperties(this); return frag; }; } else { } body.removeChild(el); body = null; /*--------------------------------------------------------------------------------------------------------*/ // Test for existence of createContextualFragment and delegate to it if it exists if (util.isHostMethod(range, "createContextualFragment")) { rangeProto.createContextualFragment = function(fragmentStr) { return this.nativeRange.createContextualFragment(fragmentStr); }; } /*--------------------------------------------------------------------------------------------------------*/ // Clean up getBody(document).removeChild(testTextNode); rangeProto.getName = function() { return "WrappedRange"; }; api.WrappedRange = WrappedRange; api.createNativeRange = function(doc) { doc = getContentDocument(doc, module, "createNativeRange"); return doc.createRange(); }; })(); } if (api.features.implementsTextRange) { /* This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement() method. For example, in the following (where pipes denote the selection boundaries): <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul> var range = document.selection.createRange(); alert(range.parentElement().id); // Should alert "ul" but alerts "b" This method returns the common ancestor node of the following: - the parentElement() of the textRange - the parentElement() of the textRange after calling collapse(true) - the parentElement() of the textRange after calling collapse(false) */ var getTextRangeContainerElement = function(textRange) { var parentEl = textRange.parentElement(); var range = textRange.duplicate(); range.collapse(true); var startEl = range.parentElement(); range = textRange.duplicate(); range.collapse(false); var endEl = range.parentElement(); var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl); return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer); }; var textRangeIsCollapsed = function(textRange) { return textRange.compareEndPoints("StartToEnd", textRange) == 0; }; // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started // out as an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) // but has grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange // bugs, handling for inputs and images, plus optimizations. var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) { var workingRange = textRange.duplicate(); workingRange.collapse(isStart); var containerElement = workingRange.parentElement(); // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so // check for that if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) { containerElement = wholeRangeContainerElement; } // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx if (!containerElement.canHaveHTML) { var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement)); return { boundaryPosition: pos, nodeInfo: { nodeIndex: pos.offset, containerElement: pos.node } }; } var workingNode = dom.getDocument(containerElement).createElement("span"); // Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5 // Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64 if (workingNode.parentNode) { workingNode.parentNode.removeChild(workingNode); } var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd"; var previousNode, nextNode, boundaryPosition, boundaryNode; var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0; var childNodeCount = containerElement.childNodes.length; var end = childNodeCount; // Check end first. Code within the loop assumes that the endth child node of the container is definitely // after the range boundary. var nodeIndex = end; while (true) { if (nodeIndex == childNodeCount) { containerElement.appendChild(workingNode); } else { containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]); } workingRange.moveToElementText(workingNode); comparison = workingRange.compareEndPoints(workingComparisonType, textRange); if (comparison == 0 || start == end) { break; } else if (comparison == -1) { if (end == start + 1) { // We know the endth child node is after the range boundary, so we must be done. break; } else { start = nodeIndex; } } else { end = (end == start + 1) ? start : nodeIndex; } nodeIndex = Math.floor((start + end) / 2); containerElement.removeChild(workingNode); } // We've now reached or gone past the boundary of the text range we're interested in // so have identified the node we want boundaryNode = workingNode.nextSibling; if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) { // This is a character data node (text, comment, cdata). The working range is collapsed at the start of // the node containing the text range's boundary, so we move the end of the working range to the // boundary point and measure the length of its text to get the boundary's offset within the node. workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange); var offset; if (/[\r\n]/.test(boundaryNode.data)) { /* For the particular case of a boundary within a text node containing rendered line breaks (within a <pre> element, for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts: - Each line break is represented as \r in the text node's data/nodeValue properties - Each line break is represented as \r\n in the TextRange's 'text' property - The 'text' property of the TextRange does not contain trailing line breaks To get round the problem presented by the final fact above, we can use the fact that TextRange's moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily the same as the number of characters it was instructed to move. The simplest approach is to use this to store the characters moved when moving both the start and end of the range to the start of the document body and subtracting the start offset from the end offset (the "move-negative-gazillion" method). However, this is extremely slow when the document is large and the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same problem. Another approach that works is to use moveStart() to move the start boundary of the range up to the end boundary one character at a time and incrementing a counter with the value returned by the moveStart() call. However, the check for whether the start boundary has reached the end boundary is expensive, so this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of the range within the document). The approach used below is a hybrid of the two methods above. It uses the fact that a string containing the TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the text of the TextRange, so the start of the range is moved that length initially and then a character at a time to make up for any trailing line breaks not contained in the 'text' property. This has good performance in most situations compared to the previous two methods. */ var tempRange = workingRange.duplicate(); var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length; offset = tempRange.moveStart("character", rangeLength); while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) { offset++; tempRange.moveStart("character", 1); } } else { offset = workingRange.text.length; } boundaryPosition = new DomPosition(boundaryNode, offset); } else { // If the boundary immediately follows a character data node and this is the end boundary, we should favour // a position within that, and likewise for a start boundary preceding a character data node previousNode = (isCollapsed || !isStart) && workingNode.previousSibling; nextNode = (isCollapsed || isStart) && workingNode.nextSibling; if (nextNode && isCharacterDataNode(nextNode)) { boundaryPosition = new DomPosition(nextNode, 0); } else if (previousNode && isCharacterDataNode(previousNode)) { boundaryPosition = new DomPosition(previousNode, previousNode.data.length); } else { boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode)); } } // Clean up workingNode.parentNode.removeChild(workingNode); return { boundaryPosition: boundaryPosition, nodeInfo: { nodeIndex: nodeIndex, containerElement: containerElement } }; }; // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that // node. This function started out as an optimized version of code found in Tim Cameron Ryan's IERange // (http://code.google.com/p/ierange/) var createBoundaryTextRange = function(boundaryPosition, isStart) { var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset; var doc = dom.getDocument(boundaryPosition.node); var workingNode, childNodes, workingRange = getBody(doc).createTextRange(); var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node); if (nodeIsDataNode) { boundaryNode = boundaryPosition.node; boundaryParent = boundaryNode.parentNode; } else { childNodes = boundaryPosition.node.childNodes; boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null; boundaryParent = boundaryPosition.node; } // Position the range immediately before the node containing the boundary workingNode = doc.createElement("span"); // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within // the element rather than immediately before or after it workingNode.innerHTML = "&#feff;"; // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12 if (boundaryNode) { boundaryParent.insertBefore(workingNode, boundaryNode); } else { boundaryParent.appendChild(workingNode); } workingRange.moveToElementText(workingNode); workingRange.collapse(!isStart); // Clean up boundaryParent.removeChild(workingNode); // Move the working range to the text offset, if required if (nodeIsDataNode) { workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset); } return workingRange; }; /*------------------------------------------------------------------------------------------------------------*/ // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a // prototype WrappedTextRange = function(textRange) { this.textRange = textRange; this.refresh(); }; WrappedTextRange.prototype = new DomRange(document); WrappedTextRange.prototype.refresh = function() { var start, end, startBoundary; // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that. var rangeContainerElement = getTextRangeContainerElement(this.textRange); if (textRangeIsCollapsed(this.textRange)) { end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true).boundaryPosition; } else { startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false); start = startBoundary.boundaryPosition; // An optimization used here is that if the start and end boundaries have the same parent element, the // search scope for the end boundary can be limited to exclude the portion of the element that precedes // the start boundary end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false, startBoundary.nodeInfo).boundaryPosition; } this.setStart(start.node, start.offset); this.setEnd(end.node, end.offset); }; WrappedTextRange.prototype.getName = function() { return "WrappedTextRange"; }; DomRange.copyComparisonConstants(WrappedTextRange); var rangeToTextRange = function(range) { if (range.collapsed) { return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); } else { var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false); var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange(); textRange.setEndPoint("StartToStart", startRange); textRange.setEndPoint("EndToEnd", endRange); return textRange; } }; WrappedTextRange.rangeToTextRange = rangeToTextRange; WrappedTextRange.prototype.toTextRange = function() { return rangeToTextRange(this); }; api.WrappedTextRange = WrappedTextRange; // IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which // implementation to use by default. if (!api.features.implementsDomRange || api.config.preferTextRange) { // Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work var globalObj = (function(f) { return f("return this;")(); })(Function); if (typeof globalObj.Range == "undefined") { globalObj.Range = WrappedTextRange; } api.createNativeRange = function(doc) { doc = getContentDocument(doc, module, "createNativeRange"); return getBody(doc).createTextRange(); }; api.WrappedRange = WrappedTextRange; } } api.createRange = function(doc) { doc = getContentDocument(doc, module, "createRange"); return new api.WrappedRange(api.createNativeRange(doc)); }; api.createRangyRange = function(doc) { doc = getContentDocument(doc, module, "createRangyRange"); return new DomRange(doc); }; api.createIframeRange = function(iframeEl) { module.deprecationNotice("createIframeRange()", "createRange(iframeEl)"); return api.createRange(iframeEl); }; api.createIframeRangyRange = function(iframeEl) { module.deprecationNotice("createIframeRangyRange()", "createRangyRange(iframeEl)"); return api.createRangyRange(iframeEl); }; api.addShimListener(function(win) { var doc = win.document; if (typeof doc.createRange == "undefined") { doc.createRange = function() { return api.createRange(doc); }; } doc = win = null; }); }); /*----------------------------------------------------------------------------------------------------------------*/ // This module creates a selection object wrapper that conforms as closely as possible to the Selection specification // in the HTML Editing spec (http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections) api.createCoreModule("WrappedSelection", ["DomRange", "WrappedRange"], function(api, module) { api.config.checkSelectionRanges = true; var BOOLEAN = "boolean"; var NUMBER = "number"; var dom = api.dom; var util = api.util; var isHostMethod = util.isHostMethod; var DomRange = api.DomRange; var WrappedRange = api.WrappedRange; var DOMException = api.DOMException; var DomPosition = dom.DomPosition; var getNativeSelection; var selectionIsCollapsed; var features = api.features; var CONTROL = "Control"; var getDocument = dom.getDocument; var getBody = dom.getBody; var rangesEqual = DomRange.rangesEqual; // Utility function to support direction parameters in the API that may be a string ("backward" or "forward") or a // Boolean (true for backwards). function isDirectionBackward(dir) { return (typeof dir == "string") ? /^backward(s)?$/i.test(dir) : !!dir; } function getWindow(win, methodName) { if (!win) { return window; } else if (dom.isWindow(win)) { return win; } else if (win instanceof WrappedSelection) { return win.win; } else { var doc = dom.getContentDocument(win, module, methodName); return dom.getWindow(doc); } } function getWinSelection(winParam) { return getWindow(winParam, "getWinSelection").getSelection(); } function getDocSelection(winParam) { return getWindow(winParam, "getDocSelection").document.selection; } function winSelectionIsBackward(sel) { var backward = false; if (sel.anchorNode) { backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1); } return backward; } // Test for the Range/TextRange and Selection features required // Test for ability to retrieve selection var implementsWinGetSelection = isHostMethod(window, "getSelection"), implementsDocSelection = util.isHostObject(document, "selection"); features.implementsWinGetSelection = implementsWinGetSelection; features.implementsDocSelection = implementsDocSelection; var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange); if (useDocumentSelection) { getNativeSelection = getDocSelection; api.isSelectionValid = function(winParam) { var doc = getWindow(winParam, "isSelectionValid").document, nativeSel = doc.selection; // Check whether the selection TextRange is actually contained within the correct document return (nativeSel.type != "None" || getDocument(nativeSel.createRange().parentElement()) == doc); }; } else if (implementsWinGetSelection) { getNativeSelection = getWinSelection; api.isSelectionValid = function() { return true; }; } else { module.fail("Neither document.selection or window.getSelection() detected."); } api.getNativeSelection = getNativeSelection; var testSelection = getNativeSelection(); var testRange = api.createNativeRange(document); var body = getBody(document); // Obtaining a range from a selection var selectionHasAnchorAndFocus = util.areHostProperties(testSelection, ["anchorNode", "focusNode", "anchorOffset", "focusOffset"]); features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus; // Test for existence of native selection extend() method var selectionHasExtend = isHostMethod(testSelection, "extend"); features.selectionHasExtend = selectionHasExtend; // Test if rangeCount exists var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER); features.selectionHasRangeCount = selectionHasRangeCount; var selectionSupportsMultipleRanges = false; var collapsedNonEditableSelectionsSupported = true; var addRangeBackwardToNative = selectionHasExtend ? function(nativeSelection, range) { var doc = DomRange.getRangeDocument(range); var endRange = api.createRange(doc); endRange.collapseToPoint(range.endContainer, range.endOffset); nativeSelection.addRange(getNativeRange(endRange)); nativeSelection.extend(range.startContainer, range.startOffset); } : null; if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) && typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) { (function() { // Previously an iframe was used but this caused problems in some circumstances in IE, so tests are // performed on the current document's selection. See issue 109. // Note also that if a selection previously existed, it is wiped by these tests. This should usually be fine // because initialization usually happens when the document loads, but could be a problem for a script that // loads and initializes Rangy later. If anyone complains, code could be added to save and restore the // selection. var sel = window.getSelection(); if (sel) { // Store the current selection var originalSelectionRangeCount = sel.rangeCount; var selectionHasMultipleRanges = (originalSelectionRangeCount > 1); var originalSelectionRanges = []; var originalSelectionBackward = winSelectionIsBackward(sel); for (var i = 0; i < originalSelectionRangeCount; ++i) { originalSelectionRanges[i] = sel.getRangeAt(i); } // Create some test elements var body = getBody(document); var testEl = body.appendChild( document.createElement("div") ); testEl.contentEditable = "false"; var textNode = testEl.appendChild( document.createTextNode("\u00a0\u00a0\u00a0") ); // Test whether the native selection will allow a collapsed selection within a non-editable element var r1 = document.createRange(); r1.setStart(textNode, 1); r1.collapse(true); sel.addRange(r1); collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1); sel.removeAllRanges(); // Test whether the native selection is capable of supporting multiple ranges. if (!selectionHasMultipleRanges) { // Doing the original feature test here in Chrome 36 (and presumably later versions) prints a // console error of "Discontiguous selection is not supported." that cannot be suppressed. There's // nothing we can do about this while retaining the feature test so we have to resort to a browser // sniff. I'm not happy about it. See // https://code.google.com/p/chromium/issues/detail?id=399791 var chromeMatch = window.navigator.appVersion.match(/Chrome\/(.*?) /); if (chromeMatch && parseInt(chromeMatch[1]) >= 36) { selectionSupportsMultipleRanges = false; } else { var r2 = r1.cloneRange(); r1.setStart(textNode, 0); r2.setEnd(textNode, 3); r2.setStart(textNode, 2); sel.addRange(r1); sel.addRange(r2); selectionSupportsMultipleRanges = (sel.rangeCount == 2); } } // Clean up body.removeChild(testEl); sel.removeAllRanges(); for (i = 0; i < originalSelectionRangeCount; ++i) { if (i == 0 && originalSelectionBackward) { if (addRangeBackwardToNative) { addRangeBackwardToNative(sel, originalSelectionRanges[i]); } else { api.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend"); sel.addRange(originalSelectionRanges[i]); } } else { sel.addRange(originalSelectionRanges[i]); } } } })(); } features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges; features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported; // ControlRanges var implementsControlRange = false, testControlRange; if (body && isHostMethod(body, "createControlRange")) { testControlRange = body.createControlRange(); if (util.areHostProperties(testControlRange, ["item", "add"])) { implementsControlRange = true; } } features.implementsControlRange = implementsControlRange; // Selection collapsedness if (selectionHasAnchorAndFocus) { selectionIsCollapsed = function(sel) { return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset; }; } else { selectionIsCollapsed = function(sel) { return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false; }; } function updateAnchorAndFocusFromRange(sel, range, backward) { var anchorPrefix = backward ? "end" : "start", focusPrefix = backward ? "start" : "end"; sel.anchorNode = range[anchorPrefix + "Container"]; sel.anchorOffset = range[anchorPrefix + "Offset"]; sel.focusNode = range[focusPrefix + "Container"]; sel.focusOffset = range[focusPrefix + "Offset"]; } function updateAnchorAndFocusFromNativeSelection(sel) { var nativeSel = sel.nativeSelection; sel.anchorNode = nativeSel.anchorNode; sel.anchorOffset = nativeSel.anchorOffset; sel.focusNode = nativeSel.focusNode; sel.focusOffset = nativeSel.focusOffset; } function updateEmptySelection(sel) { sel.anchorNode = sel.focusNode = null; sel.anchorOffset = sel.focusOffset = 0; sel.rangeCount = 0; sel.isCollapsed = true; sel._ranges.length = 0; } function getNativeRange(range) { var nativeRange; if (range instanceof DomRange) { nativeRange = api.createNativeRange(range.getDocument()); nativeRange.setEnd(range.endContainer, range.endOffset); nativeRange.setStart(range.startContainer, range.startOffset); } else if (range instanceof WrappedRange) { nativeRange = range.nativeRange; } else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) { nativeRange = range; } return nativeRange; } function rangeContainsSingleElement(rangeNodes) { if (!rangeNodes.length || rangeNodes[0].nodeType != 1) { return false; } for (var i = 1, len = rangeNodes.length; i < len; ++i) { if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) { return false; } } return true; } function getSingleElementFromRange(range) { var nodes = range.getNodes(); if (!rangeContainsSingleElement(nodes)) { throw module.createError("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element"); } return nodes[0]; } // Simple, quick test which only needs to distinguish between a TextRange and a ControlRange function isTextRange(range) { return !!range && typeof range.text != "undefined"; } function updateFromTextRange(sel, range) { // Create a Range from the selected TextRange var wrappedRange = new WrappedRange(range); sel._ranges = [wrappedRange]; updateAnchorAndFocusFromRange(sel, wrappedRange, false); sel.rangeCount = 1; sel.isCollapsed = wrappedRange.collapsed; } function updateControlSelection(sel) { // Update the wrapped selection based on what's now in the native selection sel._ranges.length = 0; if (sel.docSelection.type == "None") { updateEmptySelection(sel); } else { var controlRange = sel.docSelection.createRange(); if (isTextRange(controlRange)) { // This case (where the selection type is "Control" and calling createRange() on the selection returns // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected // ControlRange have been removed from the ControlRange and removed from the document. updateFromTextRange(sel, controlRange); } else { sel.rangeCount = controlRange.length; var range, doc = getDocument(controlRange.item(0)); for (var i = 0; i < sel.rangeCount; ++i) { range = api.createRange(doc); range.selectNode(controlRange.item(i)); sel._ranges.push(range); } sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed; updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false); } } } function addRangeToControlSelection(sel, range) { var controlRange = sel.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange plus the element // contained by the supplied range var doc = getDocument(controlRange.item(0)); var newControlRange = getBody(doc).createControlRange(); for (var i = 0, len = controlRange.length; i < len; ++i) { newControlRange.add(controlRange.item(i)); } try { newControlRange.add(rangeElement); } catch (ex) { throw module.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)"); } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } var getSelectionRangeAt; if (isHostMethod(testSelection, "getRangeAt")) { // try/catch is present because getRangeAt() must have thrown an error in some browser and some situation. // Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a // lesson to us all, especially me. getSelectionRangeAt = function(sel, index) { try { return sel.getRangeAt(index); } catch (ex) { return null; } }; } else if (selectionHasAnchorAndFocus) { getSelectionRangeAt = function(sel) { var doc = getDocument(sel.anchorNode); var range = api.createRange(doc); range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); // Handle the case when the selection was selected backwards (from the end to the start in the // document) if (range.collapsed !== this.isCollapsed) { range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset); } return range; }; } function WrappedSelection(selection, docSelection, win) { this.nativeSelection = selection; this.docSelection = docSelection; this._ranges = []; this.win = win; this.refresh(); } WrappedSelection.prototype = api.selectionPrototype; function deleteProperties(sel) { sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null; sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0; sel.detached = true; } var cachedRangySelections = []; function actOnCachedSelection(win, action) { var i = cachedRangySelections.length, cached, sel; while (i--) { cached = cachedRangySelections[i]; sel = cached.selection; if (action == "deleteAll") { deleteProperties(sel); } else if (cached.win == win) { if (action == "delete") { cachedRangySelections.splice(i, 1); return true; } else { return sel; } } } if (action == "deleteAll") { cachedRangySelections.length = 0; } return null; } var getSelection = function(win) { // Check if the parameter is a Rangy Selection object if (win && win instanceof WrappedSelection) { win.refresh(); return win; } win = getWindow(win, "getNativeSelection"); var sel = actOnCachedSelection(win); var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null; if (sel) { sel.nativeSelection = nativeSel; sel.docSelection = docSel; sel.refresh(); } else { sel = new WrappedSelection(nativeSel, docSel, win); cachedRangySelections.push( { win: win, selection: sel } ); } return sel; }; api.getSelection = getSelection; api.getIframeSelection = function(iframeEl) { module.deprecationNotice("getIframeSelection()", "getSelection(iframeEl)"); return api.getSelection(dom.getIframeWindow(iframeEl)); }; var selProto = WrappedSelection.prototype; function createControlSelection(sel, ranges) { // Ensure that the selection becomes of type "Control" var doc = getDocument(ranges[0].startContainer); var controlRange = getBody(doc).createControlRange(); for (var i = 0, el, len = ranges.length; i < len; ++i) { el = getSingleElementFromRange(ranges[i]); try { controlRange.add(el); } catch (ex) { throw module.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)"); } } controlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } // Selecting a range if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) { selProto.removeAllRanges = function() { this.nativeSelection.removeAllRanges(); updateEmptySelection(this); }; var addRangeBackward = function(sel, range) { addRangeBackwardToNative(sel.nativeSelection, range); sel.refresh(); }; if (selectionHasRangeCount) { selProto.addRange = function(range, direction) { if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { if (isDirectionBackward(direction) && selectionHasExtend) { addRangeBackward(this, range); } else { var previousRangeCount; if (selectionSupportsMultipleRanges) { previousRangeCount = this.rangeCount; } else { this.removeAllRanges(); previousRangeCount = 0; } // Clone the native range so that changing the selected range does not affect the selection. // This is contrary to the spec but is the only way to achieve consistency between browsers. See // issue 80. var clonedNativeRange = getNativeRange(range).cloneRange(); try { this.nativeSelection.addRange(clonedNativeRange); } catch (ex) { } // Check whether adding the range was successful this.rangeCount = this.nativeSelection.rangeCount; if (this.rangeCount == previousRangeCount + 1) { // The range was added successfully // Check whether the range that we added to the selection is reflected in the last range extracted from // the selection if (api.config.checkSelectionRanges) { var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1); if (nativeRange && !rangesEqual(nativeRange, range)) { // Happens in WebKit with, for example, a selection placed at the start of a text node range = new WrappedRange(nativeRange); } } this._ranges[this.rangeCount - 1] = range; updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection)); this.isCollapsed = selectionIsCollapsed(this); } else { // The range was not added successfully. The simplest thing is to refresh this.refresh(); } } } }; } else { selProto.addRange = function(range, direction) { if (isDirectionBackward(direction) && selectionHasExtend) { addRangeBackward(this, range); } else { this.nativeSelection.addRange(getNativeRange(range)); this.refresh(); } }; } selProto.setRanges = function(ranges) { if (implementsControlRange && implementsDocSelection && ranges.length > 1) { createControlSelection(this, ranges); } else { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { this.addRange(ranges[i]); } } }; } else if (isHostMethod(testSelection, "empty") && isHostMethod(testRange, "select") && implementsControlRange && useDocumentSelection) { selProto.removeAllRanges = function() { // Added try/catch as fix for issue #21 try { this.docSelection.empty(); // Check for empty() not working (issue #24) if (this.docSelection.type != "None") { // Work around failure to empty a control selection by instead selecting a TextRange and then // calling empty() var doc; if (this.anchorNode) { doc = getDocument(this.anchorNode); } else if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); if (controlRange.length) { doc = getDocument( controlRange.item(0) ); } } if (doc) { var textRange = getBody(doc).createTextRange(); textRange.select(); this.docSelection.empty(); } } } catch(ex) {} updateEmptySelection(this); }; selProto.addRange = function(range) { if (this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { api.WrappedTextRange.rangeToTextRange(range).select(); this._ranges[0] = range; this.rangeCount = 1; this.isCollapsed = this._ranges[0].collapsed; updateAnchorAndFocusFromRange(this, range, false); } }; selProto.setRanges = function(ranges) { this.removeAllRanges(); var rangeCount = ranges.length; if (rangeCount > 1) { createControlSelection(this, ranges); } else if (rangeCount) { this.addRange(ranges[0]); } }; } else { module.fail("No means of selecting a Range or TextRange was found"); return false; } selProto.getRangeAt = function(index) { if (index < 0 || index >= this.rangeCount) { throw new DOMException("INDEX_SIZE_ERR"); } else { // Clone the range to preserve selection-range independence. See issue 80. return this._ranges[index].cloneRange(); } }; var refreshSelection; if (useDocumentSelection) { refreshSelection = function(sel) { var range; if (api.isSelectionValid(sel.win)) { range = sel.docSelection.createRange(); } else { range = getBody(sel.win.document).createTextRange(); range.collapse(true); } if (sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else if (isTextRange(range)) { updateFromTextRange(sel, range); } else { updateEmptySelection(sel); } }; } else if (isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == NUMBER) { refreshSelection = function(sel) { if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else { sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount; if (sel.rangeCount) { for (var i = 0, len = sel.rangeCount; i < len; ++i) { sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i)); } updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection)); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } } }; } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) { refreshSelection = function(sel) { var range, nativeSel = sel.nativeSelection; if (nativeSel.anchorNode) { range = getSelectionRangeAt(nativeSel, 0); sel._ranges = [range]; sel.rangeCount = 1; updateAnchorAndFocusFromNativeSelection(sel); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } }; } else { module.fail("No means of obtaining a Range or TextRange from the user's selection was found"); return false; } selProto.refresh = function(checkForChanges) { var oldRanges = checkForChanges ? this._ranges.slice(0) : null; var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset; refreshSelection(this); if (checkForChanges) { // Check the range count first var i = oldRanges.length; if (i != this._ranges.length) { return true; } // Now check the direction. Checking the anchor position is the same is enough since we're checking all the // ranges after this if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) { return true; } // Finally, compare each range in turn while (i--) { if (!rangesEqual(oldRanges[i], this._ranges[i])) { return true; } } return false; } }; // Removal of a single range var removeRangeManually = function(sel, range) { var ranges = sel.getAllRanges(); sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (!rangesEqual(range, ranges[i])) { sel.addRange(ranges[i]); } } if (!sel.rangeCount) { updateEmptySelection(sel); } }; if (implementsControlRange && implementsDocSelection) { selProto.removeRange = function(range) { if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange minus the // element contained by the supplied range var doc = getDocument(controlRange.item(0)); var newControlRange = getBody(doc).createControlRange(); var el, removed = false; for (var i = 0, len = controlRange.length; i < len; ++i) { el = controlRange.item(i); if (el !== rangeElement || removed) { newControlRange.add(controlRange.item(i)); } else { removed = true; } } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(this); } else { removeRangeManually(this, range); } }; } else { selProto.removeRange = function(range) { removeRangeManually(this, range); }; } // Detecting if a selection is backward var selectionIsBackward; if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) { selectionIsBackward = winSelectionIsBackward; selProto.isBackward = function() { return selectionIsBackward(this); }; } else { selectionIsBackward = selProto.isBackward = function() { return false; }; } // Create an alias for backwards compatibility. From 1.3, everything is "backward" rather than "backwards" selProto.isBackwards = selProto.isBackward; // Selection stringifier // This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation. // The current spec does not yet define this method. selProto.toString = function() { var rangeTexts = []; for (var i = 0, len = this.rangeCount; i < len; ++i) { rangeTexts[i] = "" + this._ranges[i]; } return rangeTexts.join(""); }; function assertNodeInSameDocument(sel, node) { if (sel.win.document != getDocument(node)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } // No current browser conforms fully to the spec for this method, so Rangy's own method is always used selProto.collapse = function(node, offset) { assertNodeInSameDocument(this, node); var range = api.createRange(node); range.collapseToPoint(node, offset); this.setSingleRange(range); this.isCollapsed = true; }; selProto.collapseToStart = function() { if (this.rangeCount) { var range = this._ranges[0]; this.collapse(range.startContainer, range.startOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; selProto.collapseToEnd = function() { if (this.rangeCount) { var range = this._ranges[this.rangeCount - 1]; this.collapse(range.endContainer, range.endOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; // The spec is very specific on how selectAllChildren should be implemented so the native implementation is // never used by Rangy. selProto.selectAllChildren = function(node) { assertNodeInSameDocument(this, node); var range = api.createRange(node); range.selectNodeContents(node); this.setSingleRange(range); }; selProto.deleteFromDocument = function() { // Sepcial behaviour required for IE's control selections if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var element; while (controlRange.length) { element = controlRange.item(0); controlRange.remove(element); element.parentNode.removeChild(element); } this.refresh(); } else if (this.rangeCount) { var ranges = this.getAllRanges(); if (ranges.length) { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { ranges[i].deleteContents(); } // The spec says nothing about what the selection should contain after calling deleteContents on each // range. Firefox moves the selection to where the final selected range was, so we emulate that this.addRange(ranges[len - 1]); } } }; // The following are non-standard extensions selProto.eachRange = function(func, returnValue) { for (var i = 0, len = this._ranges.length; i < len; ++i) { if ( func( this.getRangeAt(i) ) ) { return returnValue; } } }; selProto.getAllRanges = function() { var ranges = []; this.eachRange(function(range) { ranges.push(range); }); return ranges; }; selProto.setSingleRange = function(range, direction) { this.removeAllRanges(); this.addRange(range, direction); }; selProto.callMethodOnEachRange = function(methodName, params) { var results = []; this.eachRange( function(range) { results.push( range[methodName].apply(range, params) ); } ); return results; }; function createStartOrEndSetter(isStart) { return function(node, offset) { var range; if (this.rangeCount) { range = this.getRangeAt(0); range["set" + (isStart ? "Start" : "End")](node, offset); } else { range = api.createRange(this.win.document); range.setStartAndEnd(node, offset); } this.setSingleRange(range, this.isBackward()); }; } selProto.setStart = createStartOrEndSetter(true); selProto.setEnd = createStartOrEndSetter(false); // Add select() method to Range prototype. Any existing selection will be removed. api.rangePrototype.select = function(direction) { getSelection( this.getDocument() ).setSingleRange(this, direction); }; selProto.changeEachRange = function(func) { var ranges = []; var backward = this.isBackward(); this.eachRange(function(range) { func(range); ranges.push(range); }); this.removeAllRanges(); if (backward && ranges.length == 1) { this.addRange(ranges[0], "backward"); } else { this.setRanges(ranges); } }; selProto.containsNode = function(node, allowPartial) { return this.eachRange( function(range) { return range.containsNode(node, allowPartial); }, true ) || false; }; selProto.getBookmark = function(containerNode) { return { backward: this.isBackward(), rangeBookmarks: this.callMethodOnEachRange("getBookmark", [containerNode]) }; }; selProto.moveToBookmark = function(bookmark) { var selRanges = []; for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) { range = api.createRange(this.win); range.moveToBookmark(rangeBookmark); selRanges.push(range); } if (bookmark.backward) { this.setSingleRange(selRanges[0], "backward"); } else { this.setRanges(selRanges); } }; selProto.toHtml = function() { var rangeHtmls = []; this.eachRange(function(range) { rangeHtmls.push( DomRange.toHtml(range) ); }); return rangeHtmls.join(""); }; if (features.implementsTextRange) { selProto.getNativeTextRange = function() { var sel, textRange; if ( (sel = this.docSelection) ) { var range = sel.createRange(); if (isTextRange(range)) { return range; } else { throw module.createError("getNativeTextRange: selection is a control selection"); } } else if (this.rangeCount > 0) { return api.WrappedTextRange.rangeToTextRange( this.getRangeAt(0) ); } else { throw module.createError("getNativeTextRange: selection contains no range"); } }; } function inspect(sel) { var rangeInspects = []; var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset); var focus = new DomPosition(sel.focusNode, sel.focusOffset); var name = (typeof sel.getName == "function") ? sel.getName() : "Selection"; if (typeof sel.rangeCount != "undefined") { for (var i = 0, len = sel.rangeCount; i < len; ++i) { rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i)); } } return "[" + name + "(Ranges: " + rangeInspects.join(", ") + ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]"; } selProto.getName = function() { return "WrappedSelection"; }; selProto.inspect = function() { return inspect(this); }; selProto.detach = function() { actOnCachedSelection(this.win, "delete"); deleteProperties(this); }; WrappedSelection.detachAll = function() { actOnCachedSelection(null, "deleteAll"); }; WrappedSelection.inspect = inspect; WrappedSelection.isDirectionBackward = isDirectionBackward; api.Selection = WrappedSelection; api.selectionPrototype = selProto; api.addShimListener(function(win) { if (typeof win.getSelection == "undefined") { win.getSelection = function() { return getSelection(win); }; } win = null; }); }); /*----------------------------------------------------------------------------------------------------------------*/ // Wait for document to load before initializing var docReady = false; var loadHandler = function(e) { if (!docReady) { docReady = true; if (!api.initialized && api.config.autoInitialize) { init(); } } }; if (isBrowser) { // Test whether the document has already been loaded and initialize immediately if so if (document.readyState == "complete") { loadHandler(); } else { if (isHostMethod(document, "addEventListener")) { document.addEventListener("DOMContentLoaded", loadHandler, false); } // Add a fallback in case the DOMContentLoaded event isn't supported addListener(window, "load", loadHandler); } } return api; }, this);
'use strict' const npa = require('npm-package-arg') const semver = require('semver') module.exports = pickManifest function pickManifest (packument, wanted, opts) { opts = opts || {} const spec = npa.resolve(packument.name, wanted) const type = spec.type if (type === 'version' || type === 'range') { wanted = semver.clean(wanted) || wanted } const distTags = packument['dist-tags'] || {} const versions = Object.keys(packument.versions || {}).filter(v => semver.valid(v)) let err if (!versions.length) { err = new Error(`No valid versions available for ${packument.name}`) err.code = 'ENOVERSIONS' err.name = packument.name err.type = type err.wanted = wanted throw err } let target if (type === 'tag') { target = distTags[wanted] } else if (type === 'version') { target = wanted } else if (type !== 'range') { throw new Error('Only tag, version, and range are supported') } const tagVersion = distTags[opts.defaultTag || 'latest'] if ( !target && tagVersion && packument.versions[tagVersion] && semver.satisfies(tagVersion, wanted, true) ) { target = tagVersion } if (!target) { target = semver.maxSatisfying(versions, wanted, true) } if (!target && wanted === '*') { // This specific corner is meant for the case where // someone is using `*` as a selector, but all versions // are pre-releases, which don't match ranges at all. target = tagVersion } const manifest = target && packument.versions[target] if (!manifest) { err = new Error( `No matching version found for ${packument.name}@${wanted}` ) err.code = 'ETARGET' err.name = packument.name err.type = type err.wanted = wanted err.versions = versions err.distTags = distTags err.defaultTag = opts.defaultTag throw err } else { return manifest } }
var fs = require('fs'); module.exports = function(grunt) { // Bower filenames: bowerRcFilename = '.bowerrc'; bowerRcFilenameDefault = 'component.json'; // Define root paths to 3party assets and this app's custom assets: var gruntBowerDir = './grunt-bower-lib'; var customAssetsDir = './assets'; // Order critical list of 3rd party & custom dependencies, // list in correct order (i.e. jQuery first for 3rd party) // and paths relative to the Bower ("./components/")" directory. var bowerJs = []; var bowerCss = []; var bowerRc = {}; if (grunt.file.exists(bowerRcFilename)) { bowerRc = grunt.file.readJSON(bowerRcFilename); } if (!bowerRc.json) { bowerRc.json = bowerRcFilenameDefault; } var bowerComps = grunt.file.readJSON(bowerRc.json); String.prototype.endsWith = function(suffix) { return this.toLowerCase().indexOf(suffix, this.length - suffix.length) !== -1; }; var isJavascript = function(filename) { return filename.endsWith('.js'); }; var isCss = function(filename) { return filename.endsWith('.css'); }; var getFilename = function(path) { return path.split('\\').pop().split('/').pop(); }; var getPrefixMapFn = function(comp) { return function (path) { return gruntBowerDir + '/' + comp + '/' + path; }; }; Object.keys(bowerComps.dependencies).forEach(function(comp) { if (bowerComps.exportsOverride && bowerComps.exportsOverride[comp]) { // This Bower component was overridden to specify exact files to // include from the library. Additionally we will infer the order // that those files should be included in steps such as concat // which ultimately affects the order the code is presented to // the browser. So if it's critical to have one file come after another // (say you want bootstrap.css to come before bootstrap-responsive.css) // include them in that order in the exportsOverride field of // component.json. Object.keys(bowerComps.exportsOverride[comp]).forEach(function(targetDir) { var srcFiles = bowerComps.exportsOverride[comp][targetDir]; var jsFiles = srcFiles.filter(isJavascript); var cssFiles = srcFiles.filter(isCss); var prefixMapFn = getPrefixMapFn(comp); if (jsFiles && jsFiles.length > 0) { bowerJs = bowerJs.concat(jsFiles.map(getFilename).map(prefixMapFn)); } if (cssFiles && cssFiles.length > 0) { bowerCss = bowerCss.concat(cssFiles.map(getFilename).map(prefixMapFn)); } }); } else { bowerJs.push(gruntBowerDir + '/' + comp + '/*.js'); bowerCss.push(gruntBowerDir + '/' + comp + '/*.css'); } }); // Initialize Grunt configuration: grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: { prod: { src: ['./public/dist/'] }, dev: { src: ['./public/dist-dev/'] } }, bower: { install: { options: { targetDir: gruntBowerDir } } }, jshint: { // define the files to lint files: ['Gruntfile.js'], // configure JSHint (documented at http://www.jshint.com/docs/) options: { globals: { jQuery: true, console: true, module: true } } }, concat: { options: { stripBanners: false, banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */\n\n' }, '3party-js': { src: bowerJs, dest: gruntBowerDir + '/3party/3party.js' }, '3party-css': { src: bowerCss, dest: gruntBowerDir + '/3party/3party.css' }, 'custom-js': { src: [ customAssetsDir + '/js/*.js' ], dest: gruntBowerDir + '/<%= pkg.name %>/<%= pkg.name %>.js' }, 'custom-css': { src: [ customAssetsDir + '/css/*.css' ], dest: gruntBowerDir + '/<%= pkg.name %>/<%= pkg.name %>.css' } }, min: { dist: { files: { './public/dist/js/3party.min.js': gruntBowerDir + '/3party/3party.js', './public/dist/js/<%= pkg.name %>.min.js': gruntBowerDir + '/<%= pkg.name %>/<%= pkg.name %>.js' } } }, cssmin: { dist: { files: { './public/dist/css/3party.min.css': gruntBowerDir + '/3party/3party.css', './public/dist/css/<%= pkg.name %>.min.css': gruntBowerDir + '/<%= pkg.name %>/<%= pkg.name %>.css' } } }, copy: { prod: { files: [ {expand: true, cwd: customAssetsDir + '/img/', src: ['**'], dest: './public/dist/img/', filter: 'isFile'}, {expand: true, cwd: customAssetsDir + '/ico/', src: ['**'], dest: './public/dist/ico/', filter: 'isFile'}, {expand: true, cwd: customAssetsDir + '/fonts/', src: ['**'], dest: './public/dist/fonts/', filter: 'isFile'} ] }, dev: { files: [ {expand: true, cwd: gruntBowerDir + '/3party/', src: ['3party.js'], dest: './public/dist-dev/js/', filter: 'isFile'}, {expand: true, cwd: gruntBowerDir + '/3party/', src: ['3party.css'], dest: './public/dist-dev/css/', filter: 'isFile'}, {expand: true, cwd: gruntBowerDir + '/<%= pkg.name %>/', src: ['<%= pkg.name %>.js'], dest: './public/dist-dev/js/', filter: 'isFile'}, {expand: true, cwd: gruntBowerDir + '/<%= pkg.name %>/', src: ['<%= pkg.name %>.css'], dest: './public/dist-dev/css/', filter: 'isFile'}, {expand: true, cwd: customAssetsDir + '/img/', src: ['**'], dest: './public/dist-dev/img/', filter: 'isFile'}, {expand: true, cwd: customAssetsDir + '/ico/', src: ['**'], dest: './public/dist-dev/ico/', filter: 'isFile'}, {expand: true, cwd: customAssetsDir + '/fonts/', src: ['**'], dest: './public/dist-dev/fonts/', filter: 'isFile'} ] } }, watch: { files: [ '<%= jshint.files %>', // Gruntfile.js - TODO: apply to custom assets & node scripts 'package.json', // NPM modules bowerRc.json, // Bower modules 'assets/**' ], tasks: ['dev'] } }); // Load libs grunt.loadNpmTasks('grunt-bower-task'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-yui-compressor'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); // Register the default tasks grunt.registerTask('default', [ 'clean', 'bower:install', 'jshint', 'concat', 'min', 'cssmin', 'copy:prod' ] ); // Developer tasks (not for production): grunt.registerTask('dev', [ 'clean:dev', 'bower:install', 'jshint', 'concat', 'copy:dev' ]); };
'use strict'; var React = require('react'); var PureRenderMixin = require('react-addons-pure-render-mixin'); var SvgIcon = require('../../svg-icon'); var EditorInsertComment = React.createClass({ displayName: 'EditorInsertComment', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z' }) ); } }); module.exports = EditorInsertComment;
/*! * jQuery JavaScript Library v2.0.3 -event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:10Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3 -event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-dimensions", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // 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 ) { // 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: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // 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 default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // 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 ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. 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; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 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; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // 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, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } 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 ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { 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 default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, 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 ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = 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 !== core_strundefined && (!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 types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // 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: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } 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; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // 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; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.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 ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // 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 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // 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 ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && 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) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { 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 ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent 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( 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // 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 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, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, 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(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; 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.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; }; // 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 = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // 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; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari 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 = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // 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.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, 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( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { 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 ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; 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 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.firstElementChild ) { elem = elem.firstElementChild; } 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(); } }); var curCSS, iframe, // 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 = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": 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": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } 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, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } 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; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } 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 = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "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 = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via 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( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ },{}],2:[function(require,module,exports){ /* eslint-env node */ 'use strict'; // SDP helpers. var SDPUtils = {}; // Generate an alphanumeric identifier for cname or mids. // TODO: use UUIDs instead? https://gist.github.com/jed/982883 SDPUtils.generateIdentifier = function() { return Math.random().toString(36).substr(2, 10); }; // The RTCP CNAME used by all peerconnections from the same JS. SDPUtils.localCName = SDPUtils.generateIdentifier(); // Splits SDP into lines, dealing with both CRLF and LF. SDPUtils.splitLines = function(blob) { return blob.trim().split('\n').map(function(line) { return line.trim(); }); }; // Splits SDP into sessionpart and mediasections. Ensures CRLF. SDPUtils.splitSections = function(blob) { var parts = blob.split('\nm='); return parts.map(function(part, index) { return (index > 0 ? 'm=' + part : part).trim() + '\r\n'; }); }; // returns the session description. SDPUtils.getDescription = function(blob) { var sections = SDPUtils.splitSections(blob); return sections && sections[0]; }; // returns the individual media sections. SDPUtils.getMediaSections = function(blob) { var sections = SDPUtils.splitSections(blob); sections.shift(); return sections; }; // Returns lines that start with a certain prefix. SDPUtils.matchPrefix = function(blob, prefix) { return SDPUtils.splitLines(blob).filter(function(line) { return line.indexOf(prefix) === 0; }); }; // Parses an ICE candidate line. Sample input: // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8 // rport 55996" SDPUtils.parseCandidate = function(line) { var parts; // Parse both variants. if (line.indexOf('a=candidate:') === 0) { parts = line.substring(12).split(' '); } else { parts = line.substring(10).split(' '); } var candidate = { foundation: parts[0], component: parseInt(parts[1], 10), protocol: parts[2].toLowerCase(), priority: parseInt(parts[3], 10), ip: parts[4], address: parts[4], // address is an alias for ip. port: parseInt(parts[5], 10), // skip parts[6] == 'typ' type: parts[7] }; for (var i = 8; i < parts.length; i += 2) { switch (parts[i]) { case 'raddr': candidate.relatedAddress = parts[i + 1]; break; case 'rport': candidate.relatedPort = parseInt(parts[i + 1], 10); break; case 'tcptype': candidate.tcpType = parts[i + 1]; break; case 'ufrag': candidate.ufrag = parts[i + 1]; // for backward compability. candidate.usernameFragment = parts[i + 1]; break; default: // extension handling, in particular ufrag candidate[parts[i]] = parts[i + 1]; break; } } return candidate; }; // Translates a candidate object into SDP candidate attribute. SDPUtils.writeCandidate = function(candidate) { var sdp = []; sdp.push(candidate.foundation); sdp.push(candidate.component); sdp.push(candidate.protocol.toUpperCase()); sdp.push(candidate.priority); sdp.push(candidate.address || candidate.ip); sdp.push(candidate.port); var type = candidate.type; sdp.push('typ'); sdp.push(type); if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) { sdp.push('raddr'); sdp.push(candidate.relatedAddress); sdp.push('rport'); sdp.push(candidate.relatedPort); } if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') { sdp.push('tcptype'); sdp.push(candidate.tcpType); } if (candidate.usernameFragment || candidate.ufrag) { sdp.push('ufrag'); sdp.push(candidate.usernameFragment || candidate.ufrag); } return 'candidate:' + sdp.join(' '); }; // Parses an ice-options line, returns an array of option tags. // a=ice-options:foo bar SDPUtils.parseIceOptions = function(line) { return line.substr(14).split(' '); }; // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input: // a=rtpmap:111 opus/48000/2 SDPUtils.parseRtpMap = function(line) { var parts = line.substr(9).split(' '); var parsed = { payloadType: parseInt(parts.shift(), 10) // was: id }; parts = parts[0].split('/'); parsed.name = parts[0]; parsed.clockRate = parseInt(parts[1], 10); // was: clockrate parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1; // legacy alias, got renamed back to channels in ORTC. parsed.numChannels = parsed.channels; return parsed; }; // Generate an a=rtpmap line from RTCRtpCodecCapability or // RTCRtpCodecParameters. SDPUtils.writeRtpMap = function(codec) { var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } var channels = codec.channels || codec.numChannels || 1; return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (channels !== 1 ? '/' + channels : '') + '\r\n'; }; // Parses an a=extmap line (headerextension from RFC 5285). Sample input: // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset SDPUtils.parseExtmap = function(line) { var parts = line.substr(9).split(' '); return { id: parseInt(parts[0], 10), direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv', uri: parts[1] }; }; // Generates a=extmap line from RTCRtpHeaderExtensionParameters or // RTCRtpHeaderExtension. SDPUtils.writeExtmap = function(headerExtension) { return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + (headerExtension.direction && headerExtension.direction !== 'sendrecv' ? '/' + headerExtension.direction : '') + ' ' + headerExtension.uri + '\r\n'; }; // Parses an ftmp line, returns dictionary. Sample input: // a=fmtp:96 vbr=on;cng=on // Also deals with vbr=on; cng=on SDPUtils.parseFmtp = function(line) { var parsed = {}; var kv; var parts = line.substr(line.indexOf(' ') + 1).split(';'); for (var j = 0; j < parts.length; j++) { kv = parts[j].trim().split('='); parsed[kv[0].trim()] = kv[1]; } return parsed; }; // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeFmtp = function(codec) { var line = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.parameters && Object.keys(codec.parameters).length) { var params = []; Object.keys(codec.parameters).forEach(function(param) { if (codec.parameters[param]) { params.push(param + '=' + codec.parameters[param]); } else { params.push(param); } }); line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n'; } return line; }; // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input: // a=rtcp-fb:98 nack rpsi SDPUtils.parseRtcpFb = function(line) { var parts = line.substr(line.indexOf(' ') + 1).split(' '); return { type: parts.shift(), parameter: parts.join(' ') }; }; // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeRtcpFb = function(codec) { var lines = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.rtcpFeedback && codec.rtcpFeedback.length) { // FIXME: special handling for trr-int? codec.rtcpFeedback.forEach(function(fb) { lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n'; }); } return lines; }; // Parses an RFC 5576 ssrc media attribute. Sample input: // a=ssrc:3735928559 cname:something SDPUtils.parseSsrcMedia = function(line) { var sp = line.indexOf(' '); var parts = { ssrc: parseInt(line.substr(7, sp - 7), 10) }; var colon = line.indexOf(':', sp); if (colon > -1) { parts.attribute = line.substr(sp + 1, colon - sp - 1); parts.value = line.substr(colon + 1); } else { parts.attribute = line.substr(sp + 1); } return parts; }; SDPUtils.parseSsrcGroup = function(line) { var parts = line.substr(13).split(' '); return { semantics: parts.shift(), ssrcs: parts.map(function(ssrc) { return parseInt(ssrc, 10); }) }; }; // Extracts the MID (RFC 5888) from a media section. // returns the MID or undefined if no mid line was found. SDPUtils.getMid = function(mediaSection) { var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0]; if (mid) { return mid.substr(6); } }; SDPUtils.parseFingerprint = function(line) { var parts = line.substr(14).split(' '); return { algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge. value: parts[1] }; }; // Extracts DTLS parameters from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the fingerprint line as input. See also getIceParameters. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=fingerprint:'); // Note: a=setup line is ignored since we use the 'auto' role. // Note2: 'algorithm' is not case sensitive except in Edge. return { role: 'auto', fingerprints: lines.map(SDPUtils.parseFingerprint) }; }; // Serializes DTLS parameters to SDP. SDPUtils.writeDtlsParameters = function(params, setupType) { var sdp = 'a=setup:' + setupType + '\r\n'; params.fingerprints.forEach(function(fp) { sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n'; }); return sdp; }; // Parses ICE information from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the ice-ufrag and ice-pwd lines as input. SDPUtils.getIceParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var iceParameters = { usernameFragment: lines.filter(function(line) { return line.indexOf('a=ice-ufrag:') === 0; })[0].substr(12), password: lines.filter(function(line) { return line.indexOf('a=ice-pwd:') === 0; })[0].substr(10) }; return iceParameters; }; // Serializes ICE parameters to SDP. SDPUtils.writeIceParameters = function(params) { return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n'; }; // Parses the SDP media section and returns RTCRtpParameters. SDPUtils.parseRtpParameters = function(mediaSection) { var description = { codecs: [], headerExtensions: [], fecMechanisms: [], rtcp: [] }; var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].split(' '); for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..] var pt = mline[i]; var rtpmapline = SDPUtils.matchPrefix( mediaSection, 'a=rtpmap:' + pt + ' ')[0]; if (rtpmapline) { var codec = SDPUtils.parseRtpMap(rtpmapline); var fmtps = SDPUtils.matchPrefix( mediaSection, 'a=fmtp:' + pt + ' '); // Only the first a=fmtp:<pt> is considered. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {}; codec.rtcpFeedback = SDPUtils.matchPrefix( mediaSection, 'a=rtcp-fb:' + pt + ' ') .map(SDPUtils.parseRtcpFb); description.codecs.push(codec); // parse FEC mechanisms from rtpmap lines. switch (codec.name.toUpperCase()) { case 'RED': case 'ULPFEC': description.fecMechanisms.push(codec.name.toUpperCase()); break; default: // only RED and ULPFEC are recognized as FEC mechanisms. break; } } } SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) { description.headerExtensions.push(SDPUtils.parseExtmap(line)); }); // FIXME: parse rtcp. return description; }; // Generates parts of the SDP media section describing the capabilities / // parameters. SDPUtils.writeRtpDescription = function(kind, caps) { var sdp = ''; // Build the mline. sdp += 'm=' + kind + ' '; sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs. sdp += ' UDP/TLS/RTP/SAVPF '; sdp += caps.codecs.map(function(codec) { if (codec.preferredPayloadType !== undefined) { return codec.preferredPayloadType; } return codec.payloadType; }).join(' ') + '\r\n'; sdp += 'c=IN IP4 0.0.0.0\r\n'; sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. caps.codecs.forEach(function(codec) { sdp += SDPUtils.writeRtpMap(codec); sdp += SDPUtils.writeFmtp(codec); sdp += SDPUtils.writeRtcpFb(codec); }); var maxptime = 0; caps.codecs.forEach(function(codec) { if (codec.maxptime > maxptime) { maxptime = codec.maxptime; } }); if (maxptime > 0) { sdp += 'a=maxptime:' + maxptime + '\r\n'; } sdp += 'a=rtcp-mux\r\n'; if (caps.headerExtensions) { caps.headerExtensions.forEach(function(extension) { sdp += SDPUtils.writeExtmap(extension); }); } // FIXME: write fecMechanisms. return sdp; }; // Parses the SDP media section and returns an array of // RTCRtpEncodingParameters. SDPUtils.parseRtpEncodingParameters = function(mediaSection) { var encodingParameters = []; var description = SDPUtils.parseRtpParameters(mediaSection); var hasRed = description.fecMechanisms.indexOf('RED') !== -1; var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1; // filter a=ssrc:... cname:, ignore PlanB-msid var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(parts) { return parts.attribute === 'cname'; }); var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc; var secondarySsrc; var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID') .map(function(line) { var parts = line.substr(17).split(' '); return parts.map(function(part) { return parseInt(part, 10); }); }); if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) { secondarySsrc = flows[0][1]; } description.codecs.forEach(function(codec) { if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) { var encParam = { ssrc: primarySsrc, codecPayloadType: parseInt(codec.parameters.apt, 10) }; if (primarySsrc && secondarySsrc) { encParam.rtx = {ssrc: secondarySsrc}; } encodingParameters.push(encParam); if (hasRed) { encParam = JSON.parse(JSON.stringify(encParam)); encParam.fec = { ssrc: primarySsrc, mechanism: hasUlpfec ? 'red+ulpfec' : 'red' }; encodingParameters.push(encParam); } } }); if (encodingParameters.length === 0 && primarySsrc) { encodingParameters.push({ ssrc: primarySsrc }); } // we support both b=AS and b=TIAS but interpret AS as TIAS. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b='); if (bandwidth.length) { if (bandwidth[0].indexOf('b=TIAS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(7), 10); } else if (bandwidth[0].indexOf('b=AS:') === 0) { // use formula from JSEP to convert b=AS to TIAS value. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95 - (50 * 40 * 8); } else { bandwidth = undefined; } encodingParameters.forEach(function(params) { params.maxBitrate = bandwidth; }); } return encodingParameters; }; // parses http://draft.ortc.org/#rtcrtcpparameters* SDPUtils.parseRtcpParameters = function(mediaSection) { var rtcpParameters = {}; // Gets the first SSRC. Note tha with RTX there might be multiple // SSRCs. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(obj) { return obj.attribute === 'cname'; })[0]; if (remoteSsrc) { rtcpParameters.cname = remoteSsrc.value; rtcpParameters.ssrc = remoteSsrc.ssrc; } // Edge uses the compound attribute instead of reducedSize // compound is !reducedSize var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize'); rtcpParameters.reducedSize = rsize.length > 0; rtcpParameters.compound = rsize.length === 0; // parses the rtcp-mux attrіbute. // Note that Edge does not support unmuxed RTCP. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux'); rtcpParameters.mux = mux.length > 0; return rtcpParameters; }; // parses either a=msid: or a=ssrc:... msid lines and returns // the id of the MediaStream and MediaStreamTrack. SDPUtils.parseMsid = function(mediaSection) { var parts; var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:'); if (spec.length === 1) { parts = spec[0].substr(7).split(' '); return {stream: parts[0], track: parts[1]}; } var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(msidParts) { return msidParts.attribute === 'msid'; }); if (planB.length > 0) { parts = planB[0].value.split(' '); return {stream: parts[0], track: parts[1]}; } }; // Generate a session ID for SDP. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1 // recommends using a cryptographically random +ve 64-bit value // but right now this should be acceptable and within the right range SDPUtils.generateSessionId = function() { return Math.random().toString().substr(2, 21); }; // Write boilder plate for start of SDP // sessId argument is optional - if not supplied it will // be generated randomly // sessVersion is optional and defaults to 2 // sessUser is optional and defaults to 'thisisadapterortc' SDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) { var sessionId; var version = sessVer !== undefined ? sessVer : 2; if (sessId) { sessionId = sessId; } else { sessionId = SDPUtils.generateSessionId(); } var user = sessUser || 'thisisadapterortc'; // FIXME: sess-id should be an NTP timestamp. return 'v=0\r\n' + 'o=' + user + ' ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n'; }; SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) { var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps); // Map ICE parameters (ufrag, pwd) to SDP. sdp += SDPUtils.writeIceParameters( transceiver.iceGatherer.getLocalParameters()); // Map DTLS parameters to SDP. sdp += SDPUtils.writeDtlsParameters( transceiver.dtlsTransport.getLocalParameters(), type === 'offer' ? 'actpass' : 'active'); sdp += 'a=mid:' + transceiver.mid + '\r\n'; if (transceiver.direction) { sdp += 'a=' + transceiver.direction + '\r\n'; } else if (transceiver.rtpSender && transceiver.rtpReceiver) { sdp += 'a=sendrecv\r\n'; } else if (transceiver.rtpSender) { sdp += 'a=sendonly\r\n'; } else if (transceiver.rtpReceiver) { sdp += 'a=recvonly\r\n'; } else { sdp += 'a=inactive\r\n'; } if (transceiver.rtpSender) { // spec. var msid = 'msid:' + stream.id + ' ' + transceiver.rtpSender.track.id + '\r\n'; sdp += 'a=' + msid; // for Chrome. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' ' + msid; if (transceiver.sendEncodingParameters[0].rtx) { sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc + ' ' + msid; sdp += 'a=ssrc-group:FID ' + transceiver.sendEncodingParameters[0].ssrc + ' ' + transceiver.sendEncodingParameters[0].rtx.ssrc + '\r\n'; } } // FIXME: this should be written by writeRtpDescription. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' cname:' + SDPUtils.localCName + '\r\n'; if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) { sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc + ' cname:' + SDPUtils.localCName + '\r\n'; } return sdp; }; // Gets the direction from the mediaSection or the sessionpart. SDPUtils.getDirection = function(mediaSection, sessionpart) { // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv. var lines = SDPUtils.splitLines(mediaSection); for (var i = 0; i < lines.length; i++) { switch (lines[i]) { case 'a=sendrecv': case 'a=sendonly': case 'a=recvonly': case 'a=inactive': return lines[i].substr(2); default: // FIXME: What should happen here? } } if (sessionpart) { return SDPUtils.getDirection(sessionpart); } return 'sendrecv'; }; SDPUtils.getKind = function(mediaSection) { var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].split(' '); return mline[0].substr(2); }; SDPUtils.isRejected = function(mediaSection) { return mediaSection.split(' ', 2)[1] === '0'; }; SDPUtils.parseMLine = function(mediaSection) { var lines = SDPUtils.splitLines(mediaSection); var parts = lines[0].substr(2).split(' '); return { kind: parts[0], port: parseInt(parts[1], 10), protocol: parts[2], fmt: parts.slice(3).join(' ') }; }; SDPUtils.parseOLine = function(mediaSection) { var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0]; var parts = line.substr(2).split(' '); return { username: parts[0], sessionId: parts[1], sessionVersion: parseInt(parts[2], 10), netType: parts[3], addressType: parts[4], address: parts[5] }; }; // a very naive interpretation of a valid SDP. SDPUtils.isValidSDP = function(blob) { if (typeof blob !== 'string' || blob.length === 0) { return false; } var lines = SDPUtils.splitLines(blob); for (var i = 0; i < lines.length; i++) { if (lines[i].length < 2 || lines[i].charAt(1) !== '=') { return false; } // TODO: check the modifier a bit more. } return true; }; // Expose public methods. if (typeof module === 'object') { module.exports = SDPUtils; } },{}],3:[function(require,module,exports){ (function (global){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var adapterFactory = require('./adapter_factory.js'); module.exports = adapterFactory({window: global.window}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./adapter_factory.js":4}],4:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var utils = require('./utils'); // Shimming starts here. module.exports = function(dependencies, opts) { var window = dependencies && dependencies.window; var options = { shimChrome: true, shimFirefox: true, shimEdge: true, shimSafari: true, }; for (var key in opts) { if (hasOwnProperty.call(opts, key)) { options[key] = opts[key]; } } // Utils. var logging = utils.log; var browserDetails = utils.detectBrowser(window); // Uncomment the line below if you want logging to occur, including logging // for the switch statement below. Can also be turned on in the browser via // adapter.disableLog(false), but then logging from the switch statement below // will not appear. // require('./utils').disableLog(false); // Browser shims. var chromeShim = require('./chrome/chrome_shim') || null; var edgeShim = require('./edge/edge_shim') || null; var firefoxShim = require('./firefox/firefox_shim') || null; var safariShim = require('./safari/safari_shim') || null; var commonShim = require('./common_shim') || null; // Export to the adapter global object visible in the browser. var adapter = { browserDetails: browserDetails, commonShim: commonShim, extractVersion: utils.extractVersion, disableLog: utils.disableLog, disableWarnings: utils.disableWarnings }; // Shim browser if found. switch (browserDetails.browser) { case 'chrome': if (!chromeShim || !chromeShim.shimPeerConnection || !options.shimChrome) { logging('Chrome shim is not included in this adapter release.'); return adapter; } logging('adapter.js shimming chrome.'); // Export to the adapter global object visible in the browser. adapter.browserShim = chromeShim; commonShim.shimCreateObjectURL(window); chromeShim.shimGetUserMedia(window); chromeShim.shimMediaStream(window); chromeShim.shimSourceObject(window); chromeShim.shimPeerConnection(window); chromeShim.shimOnTrack(window); chromeShim.shimAddTrackRemoveTrack(window); chromeShim.shimGetSendersWithDtmf(window); chromeShim.shimSenderReceiverGetStats(window); chromeShim.fixNegotiationNeeded(window); commonShim.shimRTCIceCandidate(window); commonShim.shimMaxMessageSize(window); commonShim.shimSendThrowTypeError(window); break; case 'firefox': if (!firefoxShim || !firefoxShim.shimPeerConnection || !options.shimFirefox) { logging('Firefox shim is not included in this adapter release.'); return adapter; } logging('adapter.js shimming firefox.'); // Export to the adapter global object visible in the browser. adapter.browserShim = firefoxShim; commonShim.shimCreateObjectURL(window); firefoxShim.shimGetUserMedia(window); firefoxShim.shimSourceObject(window); firefoxShim.shimPeerConnection(window); firefoxShim.shimOnTrack(window); firefoxShim.shimRemoveStream(window); firefoxShim.shimSenderGetStats(window); firefoxShim.shimReceiverGetStats(window); firefoxShim.shimRTCDataChannel(window); commonShim.shimRTCIceCandidate(window); commonShim.shimMaxMessageSize(window); commonShim.shimSendThrowTypeError(window); break; case 'edge': if (!edgeShim || !edgeShim.shimPeerConnection || !options.shimEdge) { logging('MS edge shim is not included in this adapter release.'); return adapter; } logging('adapter.js shimming edge.'); // Export to the adapter global object visible in the browser. adapter.browserShim = edgeShim; commonShim.shimCreateObjectURL(window); edgeShim.shimGetUserMedia(window); edgeShim.shimPeerConnection(window); edgeShim.shimReplaceTrack(window); // the edge shim implements the full RTCIceCandidate object. commonShim.shimMaxMessageSize(window); commonShim.shimSendThrowTypeError(window); break; case 'safari': if (!safariShim || !options.shimSafari) { logging('Safari shim is not included in this adapter release.'); return adapter; } logging('adapter.js shimming safari.'); // Export to the adapter global object visible in the browser. adapter.browserShim = safariShim; commonShim.shimCreateObjectURL(window); safariShim.shimRTCIceServerUrls(window); safariShim.shimCreateOfferLegacy(window); safariShim.shimCallbacksAPI(window); safariShim.shimLocalStreamsAPI(window); safariShim.shimRemoteStreamsAPI(window); safariShim.shimTrackEventTransceiver(window); safariShim.shimGetUserMedia(window); commonShim.shimRTCIceCandidate(window); commonShim.shimMaxMessageSize(window); commonShim.shimSendThrowTypeError(window); break; default: logging('Unsupported browser!'); break; } return adapter; }; },{"./chrome/chrome_shim":5,"./common_shim":7,"./edge/edge_shim":1,"./firefox/firefox_shim":8,"./safari/safari_shim":10,"./utils":11}],5:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var utils = require('../utils.js'); var logging = utils.log; /* iterates the stats graph recursively. */ function walkStats(stats, base, resultSet) { if (!base || resultSet.has(base.id)) { return; } resultSet.set(base.id, base); Object.keys(base).forEach(function(name) { if (name.endsWith('Id')) { walkStats(stats, stats.get(base[name]), resultSet); } else if (name.endsWith('Ids')) { base[name].forEach(function(id) { walkStats(stats, stats.get(id), resultSet); }); } }); } /* filter getStats for a sender/receiver track. */ function filterStats(result, track, outbound) { var streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp'; var filteredResult = new Map(); if (track === null) { return filteredResult; } var trackStats = []; result.forEach(function(value) { if (value.type === 'track' && value.trackIdentifier === track.id) { trackStats.push(value); } }); trackStats.forEach(function(trackStat) { result.forEach(function(stats) { if (stats.type === streamStatsType && stats.trackId === trackStat.id) { walkStats(result, stats, filteredResult); } }); }); return filteredResult; } module.exports = { shimGetUserMedia: require('./getusermedia'), shimMediaStream: function(window) { window.MediaStream = window.MediaStream || window.webkitMediaStream; }, shimOnTrack: function(window) { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { if (this._ontrack) { this.removeEventListener('track', this._ontrack); } this.addEventListener('track', this._ontrack = f); }, enumerable: true, configurable: true }); var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription; window.RTCPeerConnection.prototype.setRemoteDescription = function() { var pc = this; if (!pc._ontrackpoly) { pc._ontrackpoly = function(e) { // onaddstream does not fire when a track is added to an existing // stream. But stream.onaddtrack is implemented so we use that. e.stream.addEventListener('addtrack', function(te) { var receiver; if (window.RTCPeerConnection.prototype.getReceivers) { receiver = pc.getReceivers().find(function(r) { return r.track && r.track.id === te.track.id; }); } else { receiver = {track: te.track}; } var event = new Event('track'); event.track = te.track; event.receiver = receiver; event.transceiver = {receiver: receiver}; event.streams = [e.stream]; pc.dispatchEvent(event); }); e.stream.getTracks().forEach(function(track) { var receiver; if (window.RTCPeerConnection.prototype.getReceivers) { receiver = pc.getReceivers().find(function(r) { return r.track && r.track.id === track.id; }); } else { receiver = {track: track}; } var event = new Event('track'); event.track = track; event.receiver = receiver; event.transceiver = {receiver: receiver}; event.streams = [e.stream]; pc.dispatchEvent(event); }); }; pc.addEventListener('addstream', pc._ontrackpoly); } return origSetRemoteDescription.apply(pc, arguments); }; } else { // even if RTCRtpTransceiver is in window, it is only used and // emitted in unified-plan. Unfortunately this means we need // to unconditionally wrap the event. utils.wrapPeerConnectionEvent(window, 'track', function(e) { if (!e.transceiver) { Object.defineProperty(e, 'transceiver', {value: {receiver: e.receiver}}); } return e; }); } }, shimGetSendersWithDtmf: function(window) { // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack. if (typeof window === 'object' && window.RTCPeerConnection && !('getSenders' in window.RTCPeerConnection.prototype) && 'createDTMFSender' in window.RTCPeerConnection.prototype) { var shimSenderWithDtmf = function(pc, track) { return { track: track, get dtmf() { if (this._dtmf === undefined) { if (track.kind === 'audio') { this._dtmf = pc.createDTMFSender(track); } else { this._dtmf = null; } } return this._dtmf; }, _pc: pc }; }; // augment addTrack when getSenders is not available. if (!window.RTCPeerConnection.prototype.getSenders) { window.RTCPeerConnection.prototype.getSenders = function() { this._senders = this._senders || []; return this._senders.slice(); // return a copy of the internal state. }; var origAddTrack = window.RTCPeerConnection.prototype.addTrack; window.RTCPeerConnection.prototype.addTrack = function(track, stream) { var pc = this; var sender = origAddTrack.apply(pc, arguments); if (!sender) { sender = shimSenderWithDtmf(pc, track); pc._senders.push(sender); } return sender; }; var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack; window.RTCPeerConnection.prototype.removeTrack = function(sender) { var pc = this; origRemoveTrack.apply(pc, arguments); var idx = pc._senders.indexOf(sender); if (idx !== -1) { pc._senders.splice(idx, 1); } }; } var origAddStream = window.RTCPeerConnection.prototype.addStream; window.RTCPeerConnection.prototype.addStream = function(stream) { var pc = this; pc._senders = pc._senders || []; origAddStream.apply(pc, [stream]); stream.getTracks().forEach(function(track) { pc._senders.push(shimSenderWithDtmf(pc, track)); }); }; var origRemoveStream = window.RTCPeerConnection.prototype.removeStream; window.RTCPeerConnection.prototype.removeStream = function(stream) { var pc = this; pc._senders = pc._senders || []; origRemoveStream.apply(pc, [stream]); stream.getTracks().forEach(function(track) { var sender = pc._senders.find(function(s) { return s.track === track; }); if (sender) { pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender } }); }; } else if (typeof window === 'object' && window.RTCPeerConnection && 'getSenders' in window.RTCPeerConnection.prototype && 'createDTMFSender' in window.RTCPeerConnection.prototype && window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) { var origGetSenders = window.RTCPeerConnection.prototype.getSenders; window.RTCPeerConnection.prototype.getSenders = function() { var pc = this; var senders = origGetSenders.apply(pc, []); senders.forEach(function(sender) { sender._pc = pc; }); return senders; }; Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', { get: function() { if (this._dtmf === undefined) { if (this.track.kind === 'audio') { this._dtmf = this._pc.createDTMFSender(this.track); } else { this._dtmf = null; } } return this._dtmf; } }); } }, shimSenderReceiverGetStats: function(window) { if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender && window.RTCRtpReceiver)) { return; } // shim sender stats. if (!('getStats' in window.RTCRtpSender.prototype)) { var origGetSenders = window.RTCPeerConnection.prototype.getSenders; if (origGetSenders) { window.RTCPeerConnection.prototype.getSenders = function() { var pc = this; var senders = origGetSenders.apply(pc, []); senders.forEach(function(sender) { sender._pc = pc; }); return senders; }; } var origAddTrack = window.RTCPeerConnection.prototype.addTrack; if (origAddTrack) { window.RTCPeerConnection.prototype.addTrack = function() { var sender = origAddTrack.apply(this, arguments); sender._pc = this; return sender; }; } window.RTCRtpSender.prototype.getStats = function() { var sender = this; return this._pc.getStats().then(function(result) { /* Note: this will include stats of all senders that * send a track with the same id as sender.track as * it is not possible to identify the RTCRtpSender. */ return filterStats(result, sender.track, true); }); }; } // shim receiver stats. if (!('getStats' in window.RTCRtpReceiver.prototype)) { var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers; if (origGetReceivers) { window.RTCPeerConnection.prototype.getReceivers = function() { var pc = this; var receivers = origGetReceivers.apply(pc, []); receivers.forEach(function(receiver) { receiver._pc = pc; }); return receivers; }; } utils.wrapPeerConnectionEvent(window, 'track', function(e) { e.receiver._pc = e.srcElement; return e; }); window.RTCRtpReceiver.prototype.getStats = function() { var receiver = this; return this._pc.getStats().then(function(result) { return filterStats(result, receiver.track, false); }); }; } if (!('getStats' in window.RTCRtpSender.prototype && 'getStats' in window.RTCRtpReceiver.prototype)) { return; } // shim RTCPeerConnection.getStats(track). var origGetStats = window.RTCPeerConnection.prototype.getStats; window.RTCPeerConnection.prototype.getStats = function() { var pc = this; if (arguments.length > 0 && arguments[0] instanceof window.MediaStreamTrack) { var track = arguments[0]; var sender; var receiver; var err; pc.getSenders().forEach(function(s) { if (s.track === track) { if (sender) { err = true; } else { sender = s; } } }); pc.getReceivers().forEach(function(r) { if (r.track === track) { if (receiver) { err = true; } else { receiver = r; } } return r.track === track; }); if (err || (sender && receiver)) { return Promise.reject(new DOMException( 'There are more than one sender or receiver for the track.', 'InvalidAccessError')); } else if (sender) { return sender.getStats(); } else if (receiver) { return receiver.getStats(); } return Promise.reject(new DOMException( 'There is no sender or receiver for the track.', 'InvalidAccessError')); } return origGetStats.apply(pc, arguments); }; }, shimSourceObject: function(window) { var URL = window && window.URL; if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this._srcObject; }, set: function(stream) { var self = this; // Use _srcObject as a private property for this shim this._srcObject = stream; if (this.src) { URL.revokeObjectURL(this.src); } if (!stream) { this.src = ''; return undefined; } this.src = URL.createObjectURL(stream); // We need to recreate the blob url when a track is added or // removed. Doing it manually since we want to avoid a recursion. stream.addEventListener('addtrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); stream.addEventListener('removetrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); } }); } } }, shimAddTrackRemoveTrackWithNative: function(window) { // shim addTrack/removeTrack with native variants in order to make // the interactions with legacy getLocalStreams behave as in other browsers. // Keeps a mapping stream.id => [stream, rtpsenders...] window.RTCPeerConnection.prototype.getLocalStreams = function() { var pc = this; this._shimmedLocalStreams = this._shimmedLocalStreams || {}; return Object.keys(this._shimmedLocalStreams).map(function(streamId) { return pc._shimmedLocalStreams[streamId][0]; }); }; var origAddTrack = window.RTCPeerConnection.prototype.addTrack; window.RTCPeerConnection.prototype.addTrack = function(track, stream) { if (!stream) { return origAddTrack.apply(this, arguments); } this._shimmedLocalStreams = this._shimmedLocalStreams || {}; var sender = origAddTrack.apply(this, arguments); if (!this._shimmedLocalStreams[stream.id]) { this._shimmedLocalStreams[stream.id] = [stream, sender]; } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) { this._shimmedLocalStreams[stream.id].push(sender); } return sender; }; var origAddStream = window.RTCPeerConnection.prototype.addStream; window.RTCPeerConnection.prototype.addStream = function(stream) { var pc = this; this._shimmedLocalStreams = this._shimmedLocalStreams || {}; stream.getTracks().forEach(function(track) { var alreadyExists = pc.getSenders().find(function(s) { return s.track === track; }); if (alreadyExists) { throw new DOMException('Track already exists.', 'InvalidAccessError'); } }); var existingSenders = pc.getSenders(); origAddStream.apply(this, arguments); var newSenders = pc.getSenders().filter(function(newSender) { return existingSenders.indexOf(newSender) === -1; }); this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders); }; var origRemoveStream = window.RTCPeerConnection.prototype.removeStream; window.RTCPeerConnection.prototype.removeStream = function(stream) { this._shimmedLocalStreams = this._shimmedLocalStreams || {}; delete this._shimmedLocalStreams[stream.id]; return origRemoveStream.apply(this, arguments); }; var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack; window.RTCPeerConnection.prototype.removeTrack = function(sender) { var pc = this; this._shimmedLocalStreams = this._shimmedLocalStreams || {}; if (sender) { Object.keys(this._shimmedLocalStreams).forEach(function(streamId) { var idx = pc._shimmedLocalStreams[streamId].indexOf(sender); if (idx !== -1) { pc._shimmedLocalStreams[streamId].splice(idx, 1); } if (pc._shimmedLocalStreams[streamId].length === 1) { delete pc._shimmedLocalStreams[streamId]; } }); } return origRemoveTrack.apply(this, arguments); }; }, shimAddTrackRemoveTrack: function(window) { var browserDetails = utils.detectBrowser(window); // shim addTrack and removeTrack. if (window.RTCPeerConnection.prototype.addTrack && browserDetails.version >= 65) { return this.shimAddTrackRemoveTrackWithNative(window); } // also shim pc.getLocalStreams when addTrack is shimmed // to return the original streams. var origGetLocalStreams = window.RTCPeerConnection.prototype .getLocalStreams; window.RTCPeerConnection.prototype.getLocalStreams = function() { var pc = this; var nativeStreams = origGetLocalStreams.apply(this); pc._reverseStreams = pc._reverseStreams || {}; return nativeStreams.map(function(stream) { return pc._reverseStreams[stream.id]; }); }; var origAddStream = window.RTCPeerConnection.prototype.addStream; window.RTCPeerConnection.prototype.addStream = function(stream) { var pc = this; pc._streams = pc._streams || {}; pc._reverseStreams = pc._reverseStreams || {}; stream.getTracks().forEach(function(track) { var alreadyExists = pc.getSenders().find(function(s) { return s.track === track; }); if (alreadyExists) { throw new DOMException('Track already exists.', 'InvalidAccessError'); } }); // Add identity mapping for consistency with addTrack. // Unless this is being used with a stream from addTrack. if (!pc._reverseStreams[stream.id]) { var newStream = new window.MediaStream(stream.getTracks()); pc._streams[stream.id] = newStream; pc._reverseStreams[newStream.id] = stream; stream = newStream; } origAddStream.apply(pc, [stream]); }; var origRemoveStream = window.RTCPeerConnection.prototype.removeStream; window.RTCPeerConnection.prototype.removeStream = function(stream) { var pc = this; pc._streams = pc._streams || {}; pc._reverseStreams = pc._reverseStreams || {}; origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]); delete pc._reverseStreams[(pc._streams[stream.id] ? pc._streams[stream.id].id : stream.id)]; delete pc._streams[stream.id]; }; window.RTCPeerConnection.prototype.addTrack = function(track, stream) { var pc = this; if (pc.signalingState === 'closed') { throw new DOMException( 'The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError'); } var streams = [].slice.call(arguments, 1); if (streams.length !== 1 || !streams[0].getTracks().find(function(t) { return t === track; })) { // this is not fully correct but all we can manage without // [[associated MediaStreams]] internal slot. throw new DOMException( 'The adapter.js addTrack polyfill only supports a single ' + ' stream which is associated with the specified track.', 'NotSupportedError'); } var alreadyExists = pc.getSenders().find(function(s) { return s.track === track; }); if (alreadyExists) { throw new DOMException('Track already exists.', 'InvalidAccessError'); } pc._streams = pc._streams || {}; pc._reverseStreams = pc._reverseStreams || {}; var oldStream = pc._streams[stream.id]; if (oldStream) { // this is using odd Chrome behaviour, use with caution: // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815 // Note: we rely on the high-level addTrack/dtmf shim to // create the sender with a dtmf sender. oldStream.addTrack(track); // Trigger ONN async. Promise.resolve().then(function() { pc.dispatchEvent(new Event('negotiationneeded')); }); } else { var newStream = new window.MediaStream([track]); pc._streams[stream.id] = newStream; pc._reverseStreams[newStream.id] = stream; pc.addStream(newStream); } return pc.getSenders().find(function(s) { return s.track === track; }); }; // replace the internal stream id with the external one and // vice versa. function replaceInternalStreamId(pc, description) { var sdp = description.sdp; Object.keys(pc._reverseStreams || []).forEach(function(internalId) { var externalStream = pc._reverseStreams[internalId]; var internalStream = pc._streams[externalStream.id]; sdp = sdp.replace(new RegExp(internalStream.id, 'g'), externalStream.id); }); return new RTCSessionDescription({ type: description.type, sdp: sdp }); } function replaceExternalStreamId(pc, description) { var sdp = description.sdp; Object.keys(pc._reverseStreams || []).forEach(function(internalId) { var externalStream = pc._reverseStreams[internalId]; var internalStream = pc._streams[externalStream.id]; sdp = sdp.replace(new RegExp(externalStream.id, 'g'), internalStream.id); }); return new RTCSessionDescription({ type: description.type, sdp: sdp }); } ['createOffer', 'createAnswer'].forEach(function(method) { var nativeMethod = window.RTCPeerConnection.prototype[method]; window.RTCPeerConnection.prototype[method] = function() { var pc = this; var args = arguments; var isLegacyCall = arguments.length && typeof arguments[0] === 'function'; if (isLegacyCall) { return nativeMethod.apply(pc, [ function(description) { var desc = replaceInternalStreamId(pc, description); args[0].apply(null, [desc]); }, function(err) { if (args[1]) { args[1].apply(null, err); } }, arguments[2] ]); } return nativeMethod.apply(pc, arguments) .then(function(description) { return replaceInternalStreamId(pc, description); }); }; }); var origSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription; window.RTCPeerConnection.prototype.setLocalDescription = function() { var pc = this; if (!arguments.length || !arguments[0].type) { return origSetLocalDescription.apply(pc, arguments); } arguments[0] = replaceExternalStreamId(pc, arguments[0]); return origSetLocalDescription.apply(pc, arguments); }; // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier var origLocalDescription = Object.getOwnPropertyDescriptor( window.RTCPeerConnection.prototype, 'localDescription'); Object.defineProperty(window.RTCPeerConnection.prototype, 'localDescription', { get: function() { var pc = this; var description = origLocalDescription.get.apply(this); if (description.type === '') { return description; } return replaceInternalStreamId(pc, description); } }); window.RTCPeerConnection.prototype.removeTrack = function(sender) { var pc = this; if (pc.signalingState === 'closed') { throw new DOMException( 'The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError'); } // We can not yet check for sender instanceof RTCRtpSender // since we shim RTPSender. So we check if sender._pc is set. if (!sender._pc) { throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' + 'does not implement interface RTCRtpSender.', 'TypeError'); } var isLocal = sender._pc === pc; if (!isLocal) { throw new DOMException('Sender was not created by this connection.', 'InvalidAccessError'); } // Search for the native stream the senders track belongs to. pc._streams = pc._streams || {}; var stream; Object.keys(pc._streams).forEach(function(streamid) { var hasTrack = pc._streams[streamid].getTracks().find(function(track) { return sender.track === track; }); if (hasTrack) { stream = pc._streams[streamid]; } }); if (stream) { if (stream.getTracks().length === 1) { // if this is the last track of the stream, remove the stream. This // takes care of any shimmed _senders. pc.removeStream(pc._reverseStreams[stream.id]); } else { // relying on the same odd chrome behaviour as above. stream.removeTrack(sender.track); } pc.dispatchEvent(new Event('negotiationneeded')); } }; }, shimPeerConnection: function(window) { var browserDetails = utils.detectBrowser(window); // The RTCPeerConnection object. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) { window.RTCPeerConnection = function(pcConfig, pcConstraints) { // Translate iceTransportPolicy to iceTransports, // see https://code.google.com/p/webrtc/issues/detail?id=4869 // this was fixed in M56 along with unprefixing RTCPeerConnection. logging('PeerConnection'); if (pcConfig && pcConfig.iceTransportPolicy) { pcConfig.iceTransports = pcConfig.iceTransportPolicy; } return new window.webkitRTCPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = window.webkitRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (window.webkitRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return window.webkitRTCPeerConnection.generateCertificate; } }); } } var origGetStats = window.RTCPeerConnection.prototype.getStats; window.RTCPeerConnection.prototype.getStats = function(selector, successCallback, errorCallback) { var pc = this; var args = arguments; // If selector is a function then we are in the old style stats so just // pass back the original getStats format to avoid breaking old users. if (arguments.length > 0 && typeof selector === 'function') { return origGetStats.apply(this, arguments); } // When spec-style getStats is supported, return those when called with // either no arguments or the selector argument is null. if (origGetStats.length === 0 && (arguments.length === 0 || typeof arguments[0] !== 'function')) { return origGetStats.apply(this, []); } var fixChromeStats_ = function(response) { var standardReport = {}; var reports = response.result(); reports.forEach(function(report) { var standardStats = { id: report.id, timestamp: report.timestamp, type: { localcandidate: 'local-candidate', remotecandidate: 'remote-candidate' }[report.type] || report.type }; report.names().forEach(function(name) { standardStats[name] = report.stat(name); }); standardReport[standardStats.id] = standardStats; }); return standardReport; }; // shim getStats with maplike support var makeMapStats = function(stats) { return new Map(Object.keys(stats).map(function(key) { return [key, stats[key]]; })); }; if (arguments.length >= 2) { var successCallbackWrapper_ = function(response) { args[1](makeMapStats(fixChromeStats_(response))); }; return origGetStats.apply(this, [successCallbackWrapper_, arguments[0]]); } // promise-support return new Promise(function(resolve, reject) { origGetStats.apply(pc, [ function(response) { resolve(makeMapStats(fixChromeStats_(response))); }, reject]); }).then(successCallback, errorCallback); }; // add promise support -- natively available in Chrome 51 if (browserDetails.version < 51) { ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = window.RTCPeerConnection.prototype[method]; window.RTCPeerConnection.prototype[method] = function() { var args = arguments; var pc = this; var promise = new Promise(function(resolve, reject) { nativeMethod.apply(pc, [args[0], resolve, reject]); }); if (args.length < 2) { return promise; } return promise.then(function() { args[1].apply(null, []); }, function(err) { if (args.length >= 3) { args[2].apply(null, [err]); } }); }; }); } // promise support for createOffer and createAnswer. Available (without // bugs) since M52: crbug/619289 if (browserDetails.version < 52) { ['createOffer', 'createAnswer'].forEach(function(method) { var nativeMethod = window.RTCPeerConnection.prototype[method]; window.RTCPeerConnection.prototype[method] = function() { var pc = this; if (arguments.length < 1 || (arguments.length === 1 && typeof arguments[0] === 'object')) { var opts = arguments.length === 1 ? arguments[0] : undefined; return new Promise(function(resolve, reject) { nativeMethod.apply(pc, [resolve, reject, opts]); }); } return nativeMethod.apply(this, arguments); }; }); } // shim implicit creation of RTCSessionDescription/RTCIceCandidate ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = window.RTCPeerConnection.prototype[method]; window.RTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate; window.RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; }, fixNegotiationNeeded: function(window) { utils.wrapPeerConnectionEvent(window, 'negotiationneeded', function(e) { var pc = e.target; if (pc.signalingState !== 'stable') { return; } return e; }); }, shimGetDisplayMedia: function(window, getSourceId) { if ('getDisplayMedia' in window.navigator) { return; } // getSourceId is a function that returns a promise resolving with // the sourceId of the screen/window/tab to be shared. if (typeof getSourceId !== 'function') { console.error('shimGetDisplayMedia: getSourceId argument is not ' + 'a function'); return; } navigator.getDisplayMedia = function(constraints) { return getSourceId(constraints) .then(function(sourceId) { var widthSpecified = constraints.video && constraints.video.width; var heightSpecified = constraints.video && constraints.video.height; var frameRateSpecified = constraints.video && constraints.video.frameRate; constraints.video = { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceId, maxFrameRate: frameRateSpecified || 3 } }; if (widthSpecified) { constraints.video.mandatory.maxWidth = widthSpecified; } if (heightSpecified) { constraints.video.mandatory.maxHeight = heightSpecified; } return navigator.mediaDevices.getUserMedia(constraints); }); }; } }; },{"../utils.js":11,"./getusermedia":6}],6:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var utils = require('../utils.js'); var logging = utils.log; // Expose public methods. module.exports = function(window) { var browserDetails = utils.detectBrowser(window); var navigator = window && window.navigator; var constraintsToChrome_ = function(c) { if (typeof c !== 'object' || c.mandatory || c.optional) { return c; } var cc = {}; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.exact !== undefined && typeof r.exact === 'number') { r.min = r.max = r.exact; } var oldname_ = function(prefix, name) { if (prefix) { return prefix + name.charAt(0).toUpperCase() + name.slice(1); } return (name === 'deviceId') ? 'sourceId' : name; }; if (r.ideal !== undefined) { cc.optional = cc.optional || []; var oc = {}; if (typeof r.ideal === 'number') { oc[oldname_('min', key)] = r.ideal; cc.optional.push(oc); oc = {}; oc[oldname_('max', key)] = r.ideal; cc.optional.push(oc); } else { oc[oldname_('', key)] = r.ideal; cc.optional.push(oc); } } if (r.exact !== undefined && typeof r.exact !== 'number') { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_('', key)] = r.exact; } else { ['min', 'max'].forEach(function(mix) { if (r[mix] !== undefined) { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_(mix, key)] = r[mix]; } }); } }); if (c.advanced) { cc.optional = (cc.optional || []).concat(c.advanced); } return cc; }; var shimConstraints_ = function(constraints, func) { if (browserDetails.version >= 61) { return func(constraints); } constraints = JSON.parse(JSON.stringify(constraints)); if (constraints && typeof constraints.audio === 'object') { var remap = function(obj, a, b) { if (a in obj && !(b in obj)) { obj[b] = obj[a]; delete obj[a]; } }; constraints = JSON.parse(JSON.stringify(constraints)); remap(constraints.audio, 'autoGainControl', 'googAutoGainControl'); remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression'); constraints.audio = constraintsToChrome_(constraints.audio); } if (constraints && typeof constraints.video === 'object') { // Shim facingMode for mobile & surface pro. var face = constraints.video.facingMode; face = face && ((typeof face === 'object') ? face : {ideal: face}); var getSupportedFacingModeLies = browserDetails.version < 66; if ((face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment')) && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode && !getSupportedFacingModeLies)) { delete constraints.video.facingMode; var matches; if (face.exact === 'environment' || face.ideal === 'environment') { matches = ['back', 'rear']; } else if (face.exact === 'user' || face.ideal === 'user') { matches = ['front']; } if (matches) { // Look for matches in label, or use last cam for back (typical). return navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices = devices.filter(function(d) { return d.kind === 'videoinput'; }); var dev = devices.find(function(d) { return matches.some(function(match) { return d.label.toLowerCase().indexOf(match) !== -1; }); }); if (!dev && devices.length && matches.indexOf('back') !== -1) { dev = devices[devices.length - 1]; // more likely the back cam } if (dev) { constraints.video.deviceId = face.exact ? {exact: dev.deviceId} : {ideal: dev.deviceId}; } constraints.video = constraintsToChrome_(constraints.video); logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }); } } constraints.video = constraintsToChrome_(constraints.video); } logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }; var shimError_ = function(e) { if (browserDetails.version >= 64) { return e; } return { name: { PermissionDeniedError: 'NotAllowedError', PermissionDismissedError: 'NotAllowedError', InvalidStateError: 'NotAllowedError', DevicesNotFoundError: 'NotFoundError', ConstraintNotSatisfiedError: 'OverconstrainedError', TrackStartError: 'NotReadableError', MediaDeviceFailedDueToShutdown: 'NotAllowedError', MediaDeviceKillSwitchOn: 'NotAllowedError', TabCaptureError: 'AbortError', ScreenCaptureError: 'AbortError', DeviceCaptureError: 'AbortError' }[e.name] || e.name, message: e.message, constraint: e.constraint || e.constraintName, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; var getUserMedia_ = function(constraints, onSuccess, onError) { shimConstraints_(constraints, function(c) { navigator.webkitGetUserMedia(c, onSuccess, function(e) { if (onError) { onError(shimError_(e)); } }); }); }; navigator.getUserMedia = getUserMedia_; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { navigator.getUserMedia(constraints, resolve, reject); }); }; if (!navigator.mediaDevices) { navigator.mediaDevices = { getUserMedia: getUserMediaPromise_, enumerateDevices: function() { return new Promise(function(resolve) { var kinds = {audio: 'audioinput', video: 'videoinput'}; return window.MediaStreamTrack.getSources(function(devices) { resolve(devices.map(function(device) { return {label: device.label, kind: kinds[device.kind], deviceId: device.id, groupId: ''}; })); }); }); }, getSupportedConstraints: function() { return { deviceId: true, echoCancellation: true, facingMode: true, frameRate: true, height: true, width: true }; } }; } // A shim for getUserMedia method on the mediaDevices object. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (!navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia = function(constraints) { return getUserMediaPromise_(constraints); }; } else { // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia // function which returns a Promise, it does not accept spec-style // constraints. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(cs) { return shimConstraints_(cs, function(c) { return origGetUserMedia(c).then(function(stream) { if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }); }; } // Dummy devicechange event methods. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (typeof navigator.mediaDevices.addEventListener === 'undefined') { navigator.mediaDevices.addEventListener = function() { logging('Dummy mediaDevices.addEventListener called.'); }; } if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { navigator.mediaDevices.removeEventListener = function() { logging('Dummy mediaDevices.removeEventListener called.'); }; } }; },{"../utils.js":11}],7:[function(require,module,exports){ /* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var SDPUtils = require('sdp'); var utils = require('./utils'); module.exports = { shimRTCIceCandidate: function(window) { // foundation is arbitrarily chosen as an indicator for full support for // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in window.RTCIceCandidate.prototype)) { return; } var NativeRTCIceCandidate = window.RTCIceCandidate; window.RTCIceCandidate = function(args) { // Remove the a= which shouldn't be part of the candidate string. if (typeof args === 'object' && args.candidate && args.candidate.indexOf('a=') === 0) { args = JSON.parse(JSON.stringify(args)); args.candidate = args.candidate.substr(2); } if (args.candidate && args.candidate.length) { // Augment the native candidate with the parsed fields. var nativeCandidate = new NativeRTCIceCandidate(args); var parsedCandidate = SDPUtils.parseCandidate(args.candidate); var augmentedCandidate = Object.assign(nativeCandidate, parsedCandidate); // Add a serializer that does not serialize the extra attributes. augmentedCandidate.toJSON = function() { return { candidate: augmentedCandidate.candidate, sdpMid: augmentedCandidate.sdpMid, sdpMLineIndex: augmentedCandidate.sdpMLineIndex, usernameFragment: augmentedCandidate.usernameFragment, }; }; return augmentedCandidate; } return new NativeRTCIceCandidate(args); }; window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype; // Hook up the augmented candidate in onicecandidate and // addEventListener('icecandidate', ...) utils.wrapPeerConnectionEvent(window, 'icecandidate', function(e) { if (e.candidate) { Object.defineProperty(e, 'candidate', { value: new window.RTCIceCandidate(e.candidate), writable: 'false' }); } return e; }); }, // shimCreateObjectURL must be called before shimSourceObject to avoid loop. shimCreateObjectURL: function(window) { var URL = window && window.URL; if (!(typeof window === 'object' && window.HTMLMediaElement && 'srcObject' in window.HTMLMediaElement.prototype && URL.createObjectURL && URL.revokeObjectURL)) { // Only shim CreateObjectURL using srcObject if srcObject exists. return undefined; } var nativeCreateObjectURL = URL.createObjectURL.bind(URL); var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL); var streams = new Map(), newId = 0; URL.createObjectURL = function(stream) { if ('getTracks' in stream) { var url = 'polyblob:' + (++newId); streams.set(url, stream); utils.deprecated('URL.createObjectURL(stream)', 'elem.srcObject = stream'); return url; } return nativeCreateObjectURL(stream); }; URL.revokeObjectURL = function(url) { nativeRevokeObjectURL(url); streams.delete(url); }; var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype, 'src'); Object.defineProperty(window.HTMLMediaElement.prototype, 'src', { get: function() { return dsc.get.apply(this); }, set: function(url) { this.srcObject = streams.get(url) || null; return dsc.set.apply(this, [url]); } }); var nativeSetAttribute = window.HTMLMediaElement.prototype.setAttribute; window.HTMLMediaElement.prototype.setAttribute = function() { if (arguments.length === 2 && ('' + arguments[0]).toLowerCase() === 'src') { this.srcObject = streams.get(arguments[1]) || null; } return nativeSetAttribute.apply(this, arguments); }; }, shimMaxMessageSize: function(window) { if (window.RTCSctpTransport || !window.RTCPeerConnection) { return; } var browserDetails = utils.detectBrowser(window); if (!('sctp' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', { get: function() { return typeof this._sctp === 'undefined' ? null : this._sctp; } }); } var sctpInDescription = function(description) { var sections = SDPUtils.splitSections(description.sdp); sections.shift(); return sections.some(function(mediaSection) { var mLine = SDPUtils.parseMLine(mediaSection); return mLine && mLine.kind === 'application' && mLine.protocol.indexOf('SCTP') !== -1; }); }; var getRemoteFirefoxVersion = function(description) { // TODO: Is there a better solution for detecting Firefox? var match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/); if (match === null || match.length < 2) { return -1; } var version = parseInt(match[1], 10); // Test for NaN (yes, this is ugly) return version !== version ? -1 : version; }; var getCanSendMaxMessageSize = function(remoteIsFirefox) { // Every implementation we know can send at least 64 KiB. // Note: Although Chrome is technically able to send up to 256 KiB, the // data does not reach the other peer reliably. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419 var canSendMaxMessageSize = 65536; if (browserDetails.browser === 'firefox') { if (browserDetails.version < 57) { if (remoteIsFirefox === -1) { // FF < 57 will send in 16 KiB chunks using the deprecated PPID // fragmentation. canSendMaxMessageSize = 16384; } else { // However, other FF (and RAWRTC) can reassemble PPID-fragmented // messages. Thus, supporting ~2 GiB when sending. canSendMaxMessageSize = 2147483637; } } else if (browserDetails.version < 60) { // Currently, all FF >= 57 will reset the remote maximum message size // to the default value when a data channel is created at a later // stage. :( // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831 canSendMaxMessageSize = browserDetails.version === 57 ? 65535 : 65536; } else { // FF >= 60 supports sending ~2 GiB canSendMaxMessageSize = 2147483637; } } return canSendMaxMessageSize; }; var getMaxMessageSize = function(description, remoteIsFirefox) { // Note: 65536 bytes is the default value from the SDP spec. Also, // every implementation we know supports receiving 65536 bytes. var maxMessageSize = 65536; // FF 57 has a slightly incorrect default remote max message size, so // we need to adjust it here to avoid a failure when sending. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697 if (browserDetails.browser === 'firefox' && browserDetails.version === 57) { maxMessageSize = 65535; } var match = SDPUtils.matchPrefix(description.sdp, 'a=max-message-size:'); if (match.length > 0) { maxMessageSize = parseInt(match[0].substr(19), 10); } else if (browserDetails.browser === 'firefox' && remoteIsFirefox !== -1) { // If the maximum message size is not present in the remote SDP and // both local and remote are Firefox, the remote peer can receive // ~2 GiB. maxMessageSize = 2147483637; } return maxMessageSize; }; var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription; window.RTCPeerConnection.prototype.setRemoteDescription = function() { var pc = this; pc._sctp = null; if (sctpInDescription(arguments[0])) { // Check if the remote is FF. var isFirefox = getRemoteFirefoxVersion(arguments[0]); // Get the maximum message size the local peer is capable of sending var canSendMMS = getCanSendMaxMessageSize(isFirefox); // Get the maximum message size of the remote peer. var remoteMMS = getMaxMessageSize(arguments[0], isFirefox); // Determine final maximum message size var maxMessageSize; if (canSendMMS === 0 && remoteMMS === 0) { maxMessageSize = Number.POSITIVE_INFINITY; } else if (canSendMMS === 0 || remoteMMS === 0) { maxMessageSize = Math.max(canSendMMS, remoteMMS); } else { maxMessageSize = Math.min(canSendMMS, remoteMMS); } // Create a dummy RTCSctpTransport object and the 'maxMessageSize' // attribute. var sctp = {}; Object.defineProperty(sctp, 'maxMessageSize', { get: function() { return maxMessageSize; } }); pc._sctp = sctp; } return origSetRemoteDescription.apply(pc, arguments); }; }, shimSendThrowTypeError: function(window) { if (!(window.RTCPeerConnection && 'createDataChannel' in window.RTCPeerConnection.prototype)) { return; } // Note: Although Firefox >= 57 has a native implementation, the maximum // message size can be reset for all data channels at a later stage. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831 function wrapDcSend(dc, pc) { var origDataChannelSend = dc.send; dc.send = function() { var data = arguments[0]; var length = data.length || data.size || data.byteLength; if (dc.readyState === 'open' && pc.sctp && length > pc.sctp.maxMessageSize) { throw new TypeError('Message too large (can send a maximum of ' + pc.sctp.maxMessageSize + ' bytes)'); } return origDataChannelSend.apply(dc, arguments); }; } var origCreateDataChannel = window.RTCPeerConnection.prototype.createDataChannel; window.RTCPeerConnection.prototype.createDataChannel = function() { var pc = this; var dataChannel = origCreateDataChannel.apply(pc, arguments); wrapDcSend(dataChannel, pc); return dataChannel; }; utils.wrapPeerConnectionEvent(window, 'datachannel', function(e) { wrapDcSend(e.channel, e.target); return e; }); } }; },{"./utils":11,"sdp":2}],8:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var utils = require('../utils'); module.exports = { shimGetUserMedia: require('./getusermedia'), shimOnTrack: function(window) { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.transceiver = {receiver: event.receiver}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); }, enumerable: true, configurable: true }); } if (typeof window === 'object' && window.RTCTrackEvent && ('receiver' in window.RTCTrackEvent.prototype) && !('transceiver' in window.RTCTrackEvent.prototype)) { Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', { get: function() { return {receiver: this.receiver}; } }); } }, shimSourceObject: function(window) { // Firefox has supported mozSrcObject since FF22, unprefixed in 42. if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this.mozSrcObject; }, set: function(stream) { this.mozSrcObject = stream; } }); } } }, shimPeerConnection: function(window) { var browserDetails = utils.detectBrowser(window); if (typeof window !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) { return; // probably media.peerconnection.enabled=false in about:config } // The RTCPeerConnection object. if (!window.RTCPeerConnection) { window.RTCPeerConnection = function(pcConfig, pcConstraints) { if (browserDetails.version < 38) { // .urls is not supported in FF < 38. // create RTCIceServers with a single url. if (pcConfig && pcConfig.iceServers) { var newIceServers = []; for (var i = 0; i < pcConfig.iceServers.length; i++) { var server = pcConfig.iceServers[i]; if (server.hasOwnProperty('urls')) { for (var j = 0; j < server.urls.length; j++) { var newServer = { url: server.urls[j] }; if (server.urls[j].indexOf('turn') === 0) { newServer.username = server.username; newServer.credential = server.credential; } newIceServers.push(newServer); } } else { newIceServers.push(pcConfig.iceServers[i]); } } pcConfig.iceServers = newIceServers; } } return new window.mozRTCPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = window.mozRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (window.mozRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return window.mozRTCPeerConnection.generateCertificate; } }); } window.RTCSessionDescription = window.mozRTCSessionDescription; window.RTCIceCandidate = window.mozRTCIceCandidate; } // shim away need for obsolete RTCIceCandidate/RTCSessionDescription. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = window.RTCPeerConnection.prototype[method]; window.RTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate; window.RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; // shim getStats with maplike support var makeMapStats = function(stats) { var map = new Map(); Object.keys(stats).forEach(function(key) { map.set(key, stats[key]); map[key] = stats[key]; }); return map; }; var modernStatsTypes = { inboundrtp: 'inbound-rtp', outboundrtp: 'outbound-rtp', candidatepair: 'candidate-pair', localcandidate: 'local-candidate', remotecandidate: 'remote-candidate' }; var nativeGetStats = window.RTCPeerConnection.prototype.getStats; window.RTCPeerConnection.prototype.getStats = function( selector, onSucc, onErr ) { return nativeGetStats.apply(this, [selector || null]) .then(function(stats) { if (browserDetails.version < 48) { stats = makeMapStats(stats); } if (browserDetails.version < 53 && !onSucc) { // Shim only promise getStats with spec-hyphens in type names // Leave callback version alone; misc old uses of forEach before Map try { stats.forEach(function(stat) { stat.type = modernStatsTypes[stat.type] || stat.type; }); } catch (e) { if (e.name !== 'TypeError') { throw e; } // Avoid TypeError: "type" is read-only, in old versions. 34-43ish stats.forEach(function(stat, i) { stats.set(i, Object.assign({}, stat, { type: modernStatsTypes[stat.type] || stat.type })); }); } } return stats; }) .then(onSucc, onErr); }; }, shimSenderGetStats: function(window) { if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) { return; } if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) { return; } var origGetSenders = window.RTCPeerConnection.prototype.getSenders; if (origGetSenders) { window.RTCPeerConnection.prototype.getSenders = function() { var pc = this; var senders = origGetSenders.apply(pc, []); senders.forEach(function(sender) { sender._pc = pc; }); return senders; }; } var origAddTrack = window.RTCPeerConnection.prototype.addTrack; if (origAddTrack) { window.RTCPeerConnection.prototype.addTrack = function() { var sender = origAddTrack.apply(this, arguments); sender._pc = this; return sender; }; } window.RTCRtpSender.prototype.getStats = function() { return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map()); }; }, shimReceiverGetStats: function(window) { if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) { return; } if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) { return; } var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers; if (origGetReceivers) { window.RTCPeerConnection.prototype.getReceivers = function() { var pc = this; var receivers = origGetReceivers.apply(pc, []); receivers.forEach(function(receiver) { receiver._pc = pc; }); return receivers; }; } utils.wrapPeerConnectionEvent(window, 'track', function(e) { e.receiver._pc = e.srcElement; return e; }); window.RTCRtpReceiver.prototype.getStats = function() { return this._pc.getStats(this.track); }; }, shimRemoveStream: function(window) { if (!window.RTCPeerConnection || 'removeStream' in window.RTCPeerConnection.prototype) { return; } window.RTCPeerConnection.prototype.removeStream = function(stream) { var pc = this; utils.deprecated('removeStream', 'removeTrack'); this.getSenders().forEach(function(sender) { if (sender.track && stream.getTracks().indexOf(sender.track) !== -1) { pc.removeTrack(sender); } }); }; }, shimRTCDataChannel: function(window) { // rename DataChannel to RTCDataChannel (native fix in FF60): // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851 if (window.DataChannel && !window.RTCDataChannel) { window.RTCDataChannel = window.DataChannel; } }, shimGetDisplayMedia: function(window, preferredMediaSource) { if ('getDisplayMedia' in window.navigator) { return; } navigator.getDisplayMedia = function(constraints) { if (!(constraints && constraints.video)) { var err = new DOMException('getDisplayMedia without video ' + 'constraints is undefined'); err.name = 'NotFoundError'; // from https://heycam.github.io/webidl/#idl-DOMException-error-names err.code = 8; return Promise.reject(err); } if (constraints.video === true) { constraints.video = {mediaSource: preferredMediaSource}; } else { constraints.video.mediaSource = preferredMediaSource; } return navigator.mediaDevices.getUserMedia(constraints); }; } }; },{"../utils":11,"./getusermedia":9}],9:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var utils = require('../utils'); var logging = utils.log; // Expose public methods. module.exports = function(window) { var browserDetails = utils.detectBrowser(window); var navigator = window && window.navigator; var MediaStreamTrack = window && window.MediaStreamTrack; var shimError_ = function(e) { return { name: { InternalError: 'NotReadableError', NotSupportedError: 'TypeError', PermissionDeniedError: 'NotAllowedError', SecurityError: 'NotAllowedError' }[e.name] || e.name, message: { 'The operation is insecure.': 'The request is not allowed by the ' + 'user agent or the platform in the current context.' }[e.message] || e.message, constraint: e.constraint, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; // getUserMedia constraints shim. var getUserMedia_ = function(constraints, onSuccess, onError) { var constraintsToFF37_ = function(c) { if (typeof c !== 'object' || c.require) { return c; } var require = []; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = c[key] = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.min !== undefined || r.max !== undefined || r.exact !== undefined) { require.push(key); } if (r.exact !== undefined) { if (typeof r.exact === 'number') { r. min = r.max = r.exact; } else { c[key] = r.exact; } delete r.exact; } if (r.ideal !== undefined) { c.advanced = c.advanced || []; var oc = {}; if (typeof r.ideal === 'number') { oc[key] = {min: r.ideal, max: r.ideal}; } else { oc[key] = r.ideal; } c.advanced.push(oc); delete r.ideal; if (!Object.keys(r).length) { delete c[key]; } } }); if (require.length) { c.require = require; } return c; }; constraints = JSON.parse(JSON.stringify(constraints)); if (browserDetails.version < 38) { logging('spec: ' + JSON.stringify(constraints)); if (constraints.audio) { constraints.audio = constraintsToFF37_(constraints.audio); } if (constraints.video) { constraints.video = constraintsToFF37_(constraints.video); } logging('ff37: ' + JSON.stringify(constraints)); } return navigator.mozGetUserMedia(constraints, onSuccess, function(e) { onError(shimError_(e)); }); }; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { getUserMedia_(constraints, resolve, reject); }); }; // Shim for mediaDevices on older versions. if (!navigator.mediaDevices) { navigator.mediaDevices = {getUserMedia: getUserMediaPromise_, addEventListener: function() { }, removeEventListener: function() { } }; } navigator.mediaDevices.enumerateDevices = navigator.mediaDevices.enumerateDevices || function() { return new Promise(function(resolve) { var infos = [ {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} ]; resolve(infos); }); }; if (browserDetails.version < 41) { // Work around http://bugzil.la/1169665 var orgEnumerateDevices = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); navigator.mediaDevices.enumerateDevices = function() { return orgEnumerateDevices().then(undefined, function(e) { if (e.name === 'NotFoundError') { return []; } throw e; }); }; } if (browserDetails.version < 49) { var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).then(function(stream) { // Work around https://bugzil.la/802326 if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('The object can not be found here.', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }; } if (!(browserDetails.version > 55 && 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) { var remap = function(obj, a, b) { if (a in obj && !(b in obj)) { obj[b] = obj[a]; delete obj[a]; } }; var nativeGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { if (typeof c === 'object' && typeof c.audio === 'object') { c = JSON.parse(JSON.stringify(c)); remap(c.audio, 'autoGainControl', 'mozAutoGainControl'); remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression'); } return nativeGetUserMedia(c); }; if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) { var nativeGetSettings = MediaStreamTrack.prototype.getSettings; MediaStreamTrack.prototype.getSettings = function() { var obj = nativeGetSettings.apply(this, arguments); remap(obj, 'mozAutoGainControl', 'autoGainControl'); remap(obj, 'mozNoiseSuppression', 'noiseSuppression'); return obj; }; } if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) { var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints; MediaStreamTrack.prototype.applyConstraints = function(c) { if (this.kind === 'audio' && typeof c === 'object') { c = JSON.parse(JSON.stringify(c)); remap(c, 'autoGainControl', 'mozAutoGainControl'); remap(c, 'noiseSuppression', 'mozNoiseSuppression'); } return nativeApplyConstraints.apply(this, [c]); }; } } navigator.getUserMedia = function(constraints, onSuccess, onError) { if (browserDetails.version < 44) { return getUserMedia_(constraints, onSuccess, onError); } // Replace Firefox 44+'s deprecation warning with unprefixed version. utils.deprecated('navigator.getUserMedia', 'navigator.mediaDevices.getUserMedia'); navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError); }; }; },{"../utils":11}],10:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; var utils = require('../utils'); module.exports = { shimLocalStreamsAPI: function(window) { if (typeof window !== 'object' || !window.RTCPeerConnection) { return; } if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) { window.RTCPeerConnection.prototype.getLocalStreams = function() { if (!this._localStreams) { this._localStreams = []; } return this._localStreams; }; } if (!('getStreamById' in window.RTCPeerConnection.prototype)) { window.RTCPeerConnection.prototype.getStreamById = function(id) { var result = null; if (this._localStreams) { this._localStreams.forEach(function(stream) { if (stream.id === id) { result = stream; } }); } if (this._remoteStreams) { this._remoteStreams.forEach(function(stream) { if (stream.id === id) { result = stream; } }); } return result; }; } if (!('addStream' in window.RTCPeerConnection.prototype)) { var _addTrack = window.RTCPeerConnection.prototype.addTrack; window.RTCPeerConnection.prototype.addStream = function(stream) { if (!this._localStreams) { this._localStreams = []; } if (this._localStreams.indexOf(stream) === -1) { this._localStreams.push(stream); } var pc = this; stream.getTracks().forEach(function(track) { _addTrack.call(pc, track, stream); }); }; window.RTCPeerConnection.prototype.addTrack = function(track, stream) { if (stream) { if (!this._localStreams) { this._localStreams = [stream]; } else if (this._localStreams.indexOf(stream) === -1) { this._localStreams.push(stream); } } return _addTrack.call(this, track, stream); }; } if (!('removeStream' in window.RTCPeerConnection.prototype)) { window.RTCPeerConnection.prototype.removeStream = function(stream) { if (!this._localStreams) { this._localStreams = []; } var index = this._localStreams.indexOf(stream); if (index === -1) { return; } this._localStreams.splice(index, 1); var pc = this; var tracks = stream.getTracks(); this.getSenders().forEach(function(sender) { if (tracks.indexOf(sender.track) !== -1) { pc.removeTrack(sender); } }); }; } }, shimRemoteStreamsAPI: function(window) { if (typeof window !== 'object' || !window.RTCPeerConnection) { return; } if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) { window.RTCPeerConnection.prototype.getRemoteStreams = function() { return this._remoteStreams ? this._remoteStreams : []; }; } if (!('onaddstream' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', { get: function() { return this._onaddstream; }, set: function(f) { if (this._onaddstream) { this.removeEventListener('addstream', this._onaddstream); } this.addEventListener('addstream', this._onaddstream = f); } }); var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription; window.RTCPeerConnection.prototype.setRemoteDescription = function() { var pc = this; if (!this._onaddstreampoly) { this.addEventListener('track', this._onaddstreampoly = function(e) { e.streams.forEach(function(stream) { if (!pc._remoteStreams) { pc._remoteStreams = []; } if (pc._remoteStreams.indexOf(stream) >= 0) { return; } pc._remoteStreams.push(stream); var event = new Event('addstream'); event.stream = stream; pc.dispatchEvent(event); }); }); } return origSetRemoteDescription.apply(pc, arguments); }; } }, shimCallbacksAPI: function(window) { if (typeof window !== 'object' || !window.RTCPeerConnection) { return; } var prototype = window.RTCPeerConnection.prototype; var createOffer = prototype.createOffer; var createAnswer = prototype.createAnswer; var setLocalDescription = prototype.setLocalDescription; var setRemoteDescription = prototype.setRemoteDescription; var addIceCandidate = prototype.addIceCandidate; prototype.createOffer = function(successCallback, failureCallback) { var options = (arguments.length >= 2) ? arguments[2] : arguments[0]; var promise = createOffer.apply(this, [options]); if (!failureCallback) { return promise; } promise.then(successCallback, failureCallback); return Promise.resolve(); }; prototype.createAnswer = function(successCallback, failureCallback) { var options = (arguments.length >= 2) ? arguments[2] : arguments[0]; var promise = createAnswer.apply(this, [options]); if (!failureCallback) { return promise; } promise.then(successCallback, failureCallback); return Promise.resolve(); }; var withCallback = function(description, successCallback, failureCallback) { var promise = setLocalDescription.apply(this, [description]); if (!failureCallback) { return promise; } promise.then(successCallback, failureCallback); return Promise.resolve(); }; prototype.setLocalDescription = withCallback; withCallback = function(description, successCallback, failureCallback) { var promise = setRemoteDescription.apply(this, [description]); if (!failureCallback) { return promise; } promise.then(successCallback, failureCallback); return Promise.resolve(); }; prototype.setRemoteDescription = withCallback; withCallback = function(candidate, successCallback, failureCallback) { var promise = addIceCandidate.apply(this, [candidate]); if (!failureCallback) { return promise; } promise.then(successCallback, failureCallback); return Promise.resolve(); }; prototype.addIceCandidate = withCallback; }, shimGetUserMedia: function(window) { var navigator = window && window.navigator; if (!navigator.getUserMedia) { if (navigator.webkitGetUserMedia) { navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator); } else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.getUserMedia = function(constraints, cb, errcb) { navigator.mediaDevices.getUserMedia(constraints) .then(cb, errcb); }.bind(navigator); } } }, shimRTCIceServerUrls: function(window) { // migrate from non-spec RTCIceServer.url to RTCIceServer.urls var OrigPeerConnection = window.RTCPeerConnection; window.RTCPeerConnection = function(pcConfig, pcConstraints) { if (pcConfig && pcConfig.iceServers) { var newIceServers = []; for (var i = 0; i < pcConfig.iceServers.length; i++) { var server = pcConfig.iceServers[i]; if (!server.hasOwnProperty('urls') && server.hasOwnProperty('url')) { utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls'); server = JSON.parse(JSON.stringify(server)); server.urls = server.url; delete server.url; newIceServers.push(server); } else { newIceServers.push(pcConfig.iceServers[i]); } } pcConfig.iceServers = newIceServers; } return new OrigPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = OrigPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if ('generateCertificate' in window.RTCPeerConnection) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return OrigPeerConnection.generateCertificate; } }); } }, shimTrackEventTransceiver: function(window) { // Add event.transceiver member over deprecated event.receiver if (typeof window === 'object' && window.RTCPeerConnection && ('receiver' in window.RTCTrackEvent.prototype) && // can't check 'transceiver' in window.RTCTrackEvent.prototype, as it is // defined for some reason even when window.RTCTransceiver is not. !window.RTCTransceiver) { Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', { get: function() { return {receiver: this.receiver}; } }); } }, shimCreateOfferLegacy: function(window) { var origCreateOffer = window.RTCPeerConnection.prototype.createOffer; window.RTCPeerConnection.prototype.createOffer = function(offerOptions) { var pc = this; if (offerOptions) { if (typeof offerOptions.offerToReceiveAudio !== 'undefined') { // support bit values offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio; } var audioTransceiver = pc.getTransceivers().find(function(transceiver) { return transceiver.sender.track && transceiver.sender.track.kind === 'audio'; }); if (offerOptions.offerToReceiveAudio === false && audioTransceiver) { if (audioTransceiver.direction === 'sendrecv') { if (audioTransceiver.setDirection) { audioTransceiver.setDirection('sendonly'); } else { audioTransceiver.direction = 'sendonly'; } } else if (audioTransceiver.direction === 'recvonly') { if (audioTransceiver.setDirection) { audioTransceiver.setDirection('inactive'); } else { audioTransceiver.direction = 'inactive'; } } } else if (offerOptions.offerToReceiveAudio === true && !audioTransceiver) { pc.addTransceiver('audio'); } if (typeof offerOptions.offerToReceiveVideo !== 'undefined') { // support bit values offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo; } var videoTransceiver = pc.getTransceivers().find(function(transceiver) { return transceiver.sender.track && transceiver.sender.track.kind === 'video'; }); if (offerOptions.offerToReceiveVideo === false && videoTransceiver) { if (videoTransceiver.direction === 'sendrecv') { videoTransceiver.setDirection('sendonly'); } else if (videoTransceiver.direction === 'recvonly') { videoTransceiver.setDirection('inactive'); } } else if (offerOptions.offerToReceiveVideo === true && !videoTransceiver) { pc.addTransceiver('video'); } } return origCreateOffer.apply(pc, arguments); }; } }; },{"../utils":11}],11:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logDisabled_ = true; var deprecationWarnings_ = true; /** * Extract browser version out of the provided user agent string. * * @param {!string} uastring userAgent string. * @param {!string} expr Regular expression used as match criteria. * @param {!number} pos position in the version string to be returned. * @return {!number} browser version. */ function extractVersion(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); } // Wraps the peerconnection event eventNameToWrap in a function // which returns the modified event object (or false to prevent // the event). function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) { if (!window.RTCPeerConnection) { return; } var proto = window.RTCPeerConnection.prototype; var nativeAddEventListener = proto.addEventListener; proto.addEventListener = function(nativeEventName, cb) { if (nativeEventName !== eventNameToWrap) { return nativeAddEventListener.apply(this, arguments); } var wrappedCallback = function(e) { var modifiedEvent = wrapper(e); if (modifiedEvent) { cb(modifiedEvent); } }; this._eventMap = this._eventMap || {}; this._eventMap[cb] = wrappedCallback; return nativeAddEventListener.apply(this, [nativeEventName, wrappedCallback]); }; var nativeRemoveEventListener = proto.removeEventListener; proto.removeEventListener = function(nativeEventName, cb) { if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[cb]) { return nativeRemoveEventListener.apply(this, arguments); } var unwrappedCb = this._eventMap[cb]; delete this._eventMap[cb]; return nativeRemoveEventListener.apply(this, [nativeEventName, unwrappedCb]); }; Object.defineProperty(proto, 'on' + eventNameToWrap, { get: function() { return this['_on' + eventNameToWrap]; }, set: function(cb) { if (this['_on' + eventNameToWrap]) { this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]); delete this['_on' + eventNameToWrap]; } if (cb) { this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb); } }, enumerable: true, configurable: true }); } // Utility methods. module.exports = { extractVersion: extractVersion, wrapPeerConnectionEvent: wrapPeerConnectionEvent, disableLog: function(bool) { if (typeof bool !== 'boolean') { return new Error('Argument type: ' + typeof bool + '. Please use a boolean.'); } logDisabled_ = bool; return (bool) ? 'adapter.js logging disabled' : 'adapter.js logging enabled'; }, /** * Disable or enable deprecation warnings * @param {!boolean} bool set to true to disable warnings. */ disableWarnings: function(bool) { if (typeof bool !== 'boolean') { return new Error('Argument type: ' + typeof bool + '. Please use a boolean.'); } deprecationWarnings_ = !bool; return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled'); }, log: function() { if (typeof window === 'object') { if (logDisabled_) { return; } if (typeof console !== 'undefined' && typeof console.log === 'function') { console.log.apply(console, arguments); } } }, /** * Shows a deprecation warning suggesting the modern and spec-compatible API. */ deprecated: function(oldMethod, newMethod) { if (!deprecationWarnings_) { return; } console.warn(oldMethod + ' is deprecated, please use ' + newMethod + ' instead.'); }, /** * Browser detector. * * @return {object} result containing browser and version * properties. */ detectBrowser: function(window) { var navigator = window && window.navigator; // Returned result object. var result = {}; result.browser = null; result.version = null; // Fail early if it's not a browser if (typeof window === 'undefined' || !window.navigator) { result.browser = 'Not a browser.'; return result; } if (navigator.mozGetUserMedia) { // Firefox. result.browser = 'firefox'; result.version = extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1); } else if (navigator.webkitGetUserMedia) { // Chrome, Chromium, Webview, Opera. // Version matches Chrome/WebRTC version. result.browser = 'chrome'; result.version = extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2); } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge. result.browser = 'edge'; result.version = extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2); } else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { // Safari. result.browser = 'safari'; result.version = extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1); } else { // Default fallthrough: not supported. result.browser = 'Not a supported browser.'; return result; } return result; } }; },{}]},{},[3]);
var Blob = require('blob'); if (global.ArrayBuffer) { require('./arraybuffer.js'); } if (Blob) { require('./blob.js'); } require('./base64_object.js'); // General browser only tests var parser = require('../../'); var encode = parser.encodePacket; var decode = parser.decodePacket; var encPayload = parser.encodePayload; var decPayload = parser.decodePayload; describe('basic functionality', function () { it('should encode string payloads as strings even if binary supported', function (done) { encPayload([{ type: 'ping' }, { type: 'post' }], true, function(data) { expect(data).to.be.a('string'); done(); }); }); });
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import CodeExample from '../_common/CodeExample'; import PayloadStates from '../../constants/PayloadStates'; import Hook from './Hook'; import hookCode from '!raw-loader!./Hook'; import { Card } from 'material-ui'; export default lore.connect(function(getState, props) { const { tweetId } = props.params; return { tweet: getState('tweet.byId', { id: tweetId }) } })( createReactClass({ displayName: 'Layout', propTypes: { tweet: PropTypes.object.isRequired }, render: function() { const { tweet } = this.props; if (tweet.state === PayloadStates.FETCHING) { return null; } return ( <CodeExample code={hookCode} title="Code" > <Card> <Hook model={tweet} /> </Card> </CodeExample> ); } }) );
/** * Legend-related functionality. */ import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { Component } from "../core/Component"; import { DataItem } from "../core/DataItem"; import { ListTemplate, ListDisposer } from "../core/utils/List"; import { RoundedRectangle } from "../core/elements/RoundedRectangle"; import { Container } from "../core/Container"; import { Label } from "../core/elements/Label"; import { keyboard } from "../core/utils/Keyboard"; import { registry } from "../core/Registry"; import { getInteraction } from "../core/interaction/Interaction"; import { percent } from "../core/utils/Percent"; import { InterfaceColorSet } from "../core/utils/InterfaceColorSet"; import * as $utils from "../core/utils/Utils"; import * as $type from "../core/utils/Type"; import * as $math from "../core/utils/Math"; import { Sprite } from "../core/Sprite"; import { Disposer } from "../core/utils/Disposer"; import { MouseCursorStyle } from "../core/interaction/Mouse"; import { defaultRules, ResponsiveBreakpoints } from "../core/utils/Responsive"; import { Scrollbar } from "../core/elements/Scrollbar"; /** * ============================================================================ * DATA ITEM * ============================================================================ * @hidden */ /** * Defines a [[DataItem]] for [[Legend]]. * * @see {@link DataItem} */ var LegendDataItem = /** @class */ (function (_super) { __extends(LegendDataItem, _super); /** * Constructor */ function LegendDataItem() { var _this = _super.call(this) || this; /** * @ignore */ _this.childrenCreated = false; _this.className = "LegendDataItem"; _this.applyTheme(); return _this; } Object.defineProperty(LegendDataItem.prototype, "label", { /** * A legend item's [[Label]] element. * * @return Label */ get: function () { var _this = this; if (!this._label) { var label_1 = this.component.labels.create(); this._label = label_1; this.addSprite(label_1); this._disposers.push(label_1); label_1.parent = this.itemContainer; this._disposers.push(new Disposer(function () { if ($type.hasValue(_this.component)) { _this.component.labels.removeValue(label_1); } })); } return this._label; }, enumerable: true, configurable: true }); Object.defineProperty(LegendDataItem.prototype, "color", { /** * @return Main color */ get: function () { return this.properties.color; }, /** * Main color of legend data item. * * This is set by the target element this legend item represents, like * a Series or a Slice. * * It can be used to derive a color in legend's sub-items, like label: * * ```TypeScript * chart.legend.labels.template.text = "[{color}]{name}[/]"; * ``` * ```JavaScript * chart.legend.labels.template.text = "[{color}]{name}[/]"; * ``` * ```JSON * { * // ... * "legend": { * // ... * "labels": { * "text": "[{color}]{name}[/]" * } * } * } * ``` * * @see {@link https://www.amcharts.com/docs/v4/concepts/legend/#Legend_labels} For more information about configuring legend labels. * @param value Main color */ set: function (value) { this.setProperty("color", value); }, enumerable: true, configurable: true }); Object.defineProperty(LegendDataItem.prototype, "valueLabel", { /** * A legend item's [[Label]] element for "value label". * * @return Label */ get: function () { var _this = this; if (!this._valueLabel) { var valueLabel_1 = this.component.valueLabels.create(); this._valueLabel = valueLabel_1; this.addSprite(valueLabel_1); this._disposers.push(valueLabel_1); valueLabel_1.parent = this.itemContainer; this._disposers.push(new Disposer(function () { if ($type.hasValue(_this.component)) { _this.component.valueLabels.removeValue(valueLabel_1); } })); } return this._valueLabel; }, enumerable: true, configurable: true }); Object.defineProperty(LegendDataItem.prototype, "itemContainer", { /** * A reference to the main [[Container]] that holds legend item's elements: * marker and labels. * * @return Item container */ get: function () { var _this = this; if (!this._itemContainer) { var component_1 = this.component; var itemContainer_1 = component_1.itemContainers.create(); itemContainer_1.parent = component_1; this._itemContainer = itemContainer_1; this.addSprite(itemContainer_1); this._disposers.push(itemContainer_1); // Add click/tap event to toggle item if (itemContainer_1.togglable) { itemContainer_1.events.on("toggled", function (ev) { component_1.toggleDataItem(ev.target.dataItem); }, undefined, false); } // Add focus event so that we can track which object is currently in focus // for keyboard toggling if (itemContainer_1.focusable) { itemContainer_1.events.on("hit", function (ev) { // We need this here in order to reset focused item when it is clicked // normally so that it is not toggled by ENTER afterwards component_1.focusedItem = undefined; }, undefined, false); itemContainer_1.events.on("focus", function (ev) { component_1.focusedItem = ev.target.dataItem; }, undefined, false); itemContainer_1.events.on("blur", function (ev) { component_1.focusedItem = undefined; }, undefined, false); } this._disposers.push(new Disposer(function () { if ($type.hasValue(_this.component)) { _this.component.itemContainers.removeValue(itemContainer_1); } })); if (this.dataContext.uidAttr) { itemContainer_1.readerControls = this.dataContext.uidAttr(); itemContainer_1.readerLabelledBy = this.dataContext.uidAttr(); } var sprite = this.dataContext; if ((sprite instanceof DataItem || sprite instanceof Sprite) && !sprite.isDisposed()) { var visibilitychanged = function (ev) { itemContainer_1.readerChecked = ev.visible; itemContainer_1.events.disableType("toggled"); itemContainer_1.isActive = !ev.visible; itemContainer_1.events.enableType("toggled"); }; sprite.addDisposer(new Disposer(function () { if (_this.component) { _this.component.dataItems.remove(_this); } })); if (sprite instanceof Sprite) { itemContainer_1.addDisposer(sprite.events.on("visibilitychanged", visibilitychanged, undefined, false)); itemContainer_1.addDisposer(sprite.events.on("hidden", function (ev) { itemContainer_1.readerChecked = false; itemContainer_1.events.disableType("toggled"); itemContainer_1.isActive = true; itemContainer_1.events.enableType("toggled"); }, undefined, false)); itemContainer_1.addDisposer(sprite.events.on("shown", function (ev) { itemContainer_1.readerChecked = true; itemContainer_1.events.disableType("toggled"); itemContainer_1.isActive = false; itemContainer_1.events.enableType("toggled"); }, undefined, false)); } else { itemContainer_1.addDisposer(sprite.events.on("visibilitychanged", visibilitychanged, undefined, false)); } } } return this._itemContainer; }, enumerable: true, configurable: true }); Object.defineProperty(LegendDataItem.prototype, "marker", { /** * A [[Container]] that holds legend item's marker element. * * @return Marker */ get: function () { var _this = this; if (!this._marker) { var marker_1 = this.component.markers.create(); this._marker = marker_1; marker_1.parent = this.itemContainer; this.addSprite(marker_1); this._disposers.push(marker_1); this._disposers.push(new Disposer(function () { if ($type.hasValue(_this.component)) { _this.component.markers.removeValue(marker_1); } })); } return this._marker; }, enumerable: true, configurable: true }); return LegendDataItem; }(DataItem)); export { LegendDataItem }; /** * ============================================================================ * REQUISITES * ============================================================================ * @hidden */ /** * Defines a class that carries legend settings. * * A legend might change its settings dynamically. Legend can also be shared * by several elements, requiring different settings. * * Having legend's settings in a separate object is a good way to "hot swap" * a set of settings for the legend. */ var LegendSettings = /** @class */ (function () { function LegendSettings() { /** * Should marker be created for each legend item. */ this.createMarker = true; } return LegendSettings; }()); export { LegendSettings }; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * [[Legend]] class is used to create legend for the chart. * * @see {@link https://www.amcharts.com/docs/v4/concepts/legend/} for Legend documentation * @see {@link ILegendEvents} for a list of available events * @see {@link ILegendAdapters} for a list of available Adapters */ var Legend = /** @class */ (function (_super) { __extends(Legend, _super); /** * Constructor */ function Legend() { var _this = _super.call(this) || this; _this.className = "Legend"; // Set defaults _this.layout = "grid"; _this.setPropertyValue("useDefaultMarker", false); _this.setPropertyValue("scrollable", false); _this.setPropertyValue("contentAlign", "center"); // Create a template container and list for legend items var itemContainer = new Container(); itemContainer.applyOnClones = true; itemContainer.padding(8, 0, 8, 0); itemContainer.margin(0, 10, 0, 10); itemContainer.layout = "horizontal"; itemContainer.clickable = true; itemContainer.focusable = true; itemContainer.role = "switch"; itemContainer.togglable = true; itemContainer.cursorOverStyle = MouseCursorStyle.pointer; itemContainer.background.fillOpacity = 0; // creates hit area // Create container list using item template we just created _this.itemContainers = new ListTemplate(itemContainer); _this._disposers.push(new ListDisposer(_this.itemContainers)); _this._disposers.push(_this.itemContainers.template); // Set up global keyboard events for toggling elements _this._disposers.push(getInteraction().body.events.on("keyup", function (ev) { if (keyboard.isKey(ev.event, "enter") && _this.focusedItem) { var focusedItem = _this.focusedItem; var target = focusedItem.itemContainer; if (target.togglable) { _this.toggleDataItem(focusedItem); } else if (target.clickable && target.events.isEnabled("hit")) { target.dispatchImmediately("hit", { event: ev }); // We need this here because "hit" event resets `this.focusedItem` // And we need it here _this.focusedItem = focusedItem; } } }, _this)); var interfaceColors = new InterfaceColorSet(); // Create a template container and list for the a marker var marker = new Container(); marker.width = 23; marker.height = 23; marker.interactionsEnabled = false; marker.applyOnClones = true; marker.setStateOnChildren = true; marker.background.fillOpacity = 0; marker.background.strokeOpacity = 0; marker.propertyFields.fill = "fill"; marker.valign = "middle"; var disabledColor = interfaceColors.getFor("disabledBackground"); marker.events.on("childadded", function (event) { var child = event.newValue; var activeState = child.states.create("active"); activeState.properties.stroke = disabledColor; activeState.properties.fill = disabledColor; }); _this.markers = new ListTemplate(marker); _this._disposers.push(new ListDisposer(_this.markers)); _this._disposers.push(_this.markers.template); // Create a legend background element var rectangle = marker.createChild(RoundedRectangle); rectangle.width = percent(100); rectangle.height = percent(100); rectangle.applyOnClones = true; rectangle.propertyFields.fill = "fill"; //othrwise old edge doesn't like as the same pattern is set both on parent and child https://codepen.io/team/amcharts/pen/72d7a98f3fb811d3118795220ff63182 rectangle.strokeOpacity = 0; // Create a template container and list for item labels var label = new Label(); label.text = "{name}"; label.margin(0, 5, 0, 5); label.valign = "middle"; label.applyOnClones = true; label.states.create("active").properties.fill = interfaceColors.getFor("disabledBackground"); _this.labels = new ListTemplate(label); _this._disposers.push(new ListDisposer(_this.labels)); _this._disposers.push(_this.labels.template); label.interactionsEnabled = false; label.truncate = true; label.fullWords = false; // Create a template container and list for item value labels var valueLabel = new Label(); valueLabel.margin(0, 5, 0, 0); valueLabel.valign = "middle"; valueLabel.width = 50; // to avoid rearranging legend entries when value changes. valueLabel.align = "right"; valueLabel.textAlign = "end"; valueLabel.applyOnClones = true; valueLabel.states.create("active").properties.fill = interfaceColors.getFor("disabledBackground"); valueLabel.interactionsEnabled = false; _this.valueLabels = new ListTemplate(valueLabel); _this._disposers.push(new ListDisposer(_this.valueLabels)); _this._disposers.push(_this.valueLabels.template); _this.position = "bottom"; // don't use setPropertyValue here! // Create a state for disabled legend items itemContainer.states.create("active"); itemContainer.setStateOnChildren = true; // Apply accessibility settings _this.role = "group"; _this.events.on("layoutvalidated", _this.handleScrollbar, _this, false); _this.applyTheme(); return _this; } /** * Sets defaults that instantiate some objects that rely on parent, so they * cannot be set in constructor. */ Legend.prototype.applyInternalDefaults = function () { _super.prototype.applyInternalDefaults.call(this); if (!$type.hasValue(this.readerTitle)) { this.readerTitle = this.language.translate("Legend"); } }; /** * Returns a new/empty DataItem of the type appropriate for this object. * * @see {@link DataItem} * @return Data Item */ Legend.prototype.createDataItem = function () { return new LegendDataItem(); }; /** * [validateDataElement description] * * @ignore Exclude from docs * @param dataItem Data item * @todo Description * @todo Figure out how to update appearance of legend item without losing focus * @todo Update legend marker appearance as apperance of related series changes */ Legend.prototype.validateDataElement = function (dataItem) { _super.prototype.validateDataElement.call(this, dataItem); // Get data item (legend item's) container var container = dataItem.itemContainer; var marker = dataItem.marker; $utils.used(dataItem.label); var valueLabel = dataItem.valueLabel; // Set parent and update current state container.readerChecked = dataItem.dataContext.visible; // Tell series its legend data item dataItem.dataContext.legendDataItem = dataItem; var tempMaxWidth = dataItem.label.maxWidth; dataItem.label.width = undefined; if (tempMaxWidth > 0) { dataItem.label.maxWidth = tempMaxWidth; } if (valueLabel.align == "right") { valueLabel.width = undefined; } var legendSettings = dataItem.dataContext.legendSettings; // If we are not using default markers, create a unique legend marker based // on the data item type var dataContext = dataItem.dataContext; if (dataContext.createLegendMarker && (!this.useDefaultMarker || !(dataContext instanceof Sprite))) { if (!dataItem.childrenCreated) { dataContext.createLegendMarker(marker); dataItem.childrenCreated = true; } } else { this.markers.template.propertyFields.fill = undefined; } if (dataContext.updateLegendValue) { dataContext.updateLegendValue(); // this solves issue with external legend, as legend is created after chart updates legend values } if (dataContext.component && dataContext.component.updateLegendValue) { dataContext.component.updateLegendValue(dataContext); } if (valueLabel.invalid) { valueLabel.validate(); } if (valueLabel.text == "" || valueLabel.text == undefined) { valueLabel.__disabled = true; } else { valueLabel.__disabled = false; } if (legendSettings && (legendSettings.itemValueText != undefined || legendSettings.valueText != undefined)) { valueLabel.__disabled = false; } var visible = dataItem.dataContext.visible; if (visible === undefined) { visible = true; } visible = $type.toBoolean(visible); dataItem.dataContext.visible = visible; container.events.disableType("toggled"); container.isActive = !visible; if (container.isActive) { container.setState("active", 0); } else { container.setState("default", 0); } container.events.enableType("toggled"); }; Legend.prototype.afterDraw = function () { var _this = this; var maxWidth = this.getPropertyValue("maxWidth"); var maxLabelWidth = 0; this.labels.each(function (label) { if (label.invalid) { label.validate(); } if (label.measuredWidth + label.pixelMarginLeft + label.pixelMarginRight > maxLabelWidth) { maxLabelWidth = label.measuredWidth + label.pixelMarginLeft + label.pixelMarginRight; } }); var maxValueLabelWidth = 0; this.valueLabels.each(function (label) { if (label.invalid) { label.validate(); } if (label.measuredWidth + label.pixelMarginLeft + label.pixelMarginRight > maxValueLabelWidth) { maxValueLabelWidth = label.measuredWidth + label.pixelMarginLeft + label.pixelMarginRight; } }); var maxMarkerWidth = 0; this.markers.each(function (marker) { if (marker.invalid) { marker.validate(); } if (marker.measuredWidth + marker.pixelMarginLeft + marker.pixelMarginRight > maxMarkerWidth) { maxMarkerWidth = marker.measuredWidth + marker.pixelMarginLeft + marker.pixelMarginRight; } }); var itemContainer = this.itemContainers.template; var margin = itemContainer.pixelMarginRight + itemContainer.pixelMarginLeft; var maxAdjustedLabelWidth; var trueMaxWidth = maxLabelWidth + maxValueLabelWidth + maxMarkerWidth; if (!$type.isNumber(maxWidth)) { maxAdjustedLabelWidth = maxLabelWidth; } else { maxWidth = maxWidth - margin; if (maxWidth > trueMaxWidth) { maxWidth = trueMaxWidth; } maxAdjustedLabelWidth = maxWidth - maxMarkerWidth - maxValueLabelWidth; } this.labels.each(function (label) { if (_this.valueLabels.template.align == "right" || label.measuredWidth > maxAdjustedLabelWidth) { label.width = Math.min(label.maxWidth, maxAdjustedLabelWidth - label.pixelMarginLeft - label.pixelMarginRight); } }); if (this.valueLabels.template.align == "right") { this.valueLabels.each(function (valueLabel) { valueLabel.width = maxValueLabelWidth - valueLabel.pixelMarginRight - valueLabel.pixelMarginLeft; }); } _super.prototype.afterDraw.call(this); }; Legend.prototype.handleScrollbar = function () { var scrollbar = this.scrollbar; if (this.scrollable && scrollbar) { scrollbar.height = this.measuredHeight; scrollbar.x = this.measuredWidth - scrollbar.pixelWidth - scrollbar.pixelMarginLeft; if (this.contentHeight > this.measuredHeight) { scrollbar.visible = true; scrollbar.thumb.height = scrollbar.height * this.measuredHeight / this.contentHeight; this.paddingRight = scrollbar.pixelWidth + scrollbar.pixelMarginLeft + +scrollbar.pixelMarginRight; } else { scrollbar.visible = false; } this.updateMasks(); } }; Object.defineProperty(Legend.prototype, "position", { /** * @return Position */ get: function () { return this.getPropertyValue("position"); }, /** * Position of the legend. * * Options: "left", "right", "top", "bottom" (default), or "absolute". * * IMPORTANT: [[MapChart]] will ignore this setting, as it is using different * layout structure than other charts. * * To position legend in [[MapChart]] set legend's `align` (`"left"` or * `"right"`) and `valign` (`"top"` or `"bottom"`) properties instead. * * @default "bottom" * @param value Position */ set: function (value) { if (this.setPropertyValue("position", value)) { if (value == "left" || value == "right") { this.margin(10, 5, 10, 10); this.valign = "middle"; this.contentAlign = "none"; this.valueLabels.template.align = "right"; if (!$type.isNumber(this.maxColumns)) { this.maxColumns = 1; } this.width = undefined; this.maxWidth = 220; } else { this.maxColumns = undefined; this.width = percent(100); this.valueLabels.template.align = "left"; } this.invalidate(); } }, enumerable: true, configurable: true }); Object.defineProperty(Legend.prototype, "useDefaultMarker", { /** * @return Use default marker? */ get: function () { return this.getPropertyValue("useDefaultMarker"); }, /** * Should legend try to mirror the look of the related item when building * the marker for legend item? * * If set to `false` it will try to make the marker look like its related * item. * * E.g. if an item is for a Line Series, it will display a line of the * same thickness, color, and will use the same bullets if series have them. * * If set to `true`, all markers will be shown as squares, regardless of te * series type. * * @default false * @param value Use default marker? */ set: function (value) { this.setPropertyValue("useDefaultMarker", value, true); }, enumerable: true, configurable: true }); Object.defineProperty(Legend.prototype, "scrollable", { /** * @return Legend Scrollable? */ get: function () { return this.getPropertyValue("scrollable"); }, /** * If set to `true` the Legend will display a scrollbar if its contents do * not fit into its `maxHeight`. * * Please note that `maxHeight` is automatically set for Legend when its * `position` is set to `"left"` or `"right"`. * * @default false * @since 4.8.0 * @param value Legend Scrollable? */ set: function (value) { if (this.setPropertyValue("scrollable", value, true)) { if (value) { var scrollbar = this.createChild(Scrollbar); this.scrollbar = scrollbar; scrollbar.isMeasured = false; scrollbar.orientation = "vertical"; scrollbar.endGrip.__disabled = true; scrollbar.startGrip.__disabled = true; scrollbar.visible = false; scrollbar.marginLeft = 5; this._mouseWheelDisposer = this.events.on("wheel", this.handleWheel, this, false); this._disposers.push(this._mouseWheelDisposer); this._disposers.push(scrollbar.events.on("rangechanged", this.updateMasks, this, false)); } else { if (this._mouseWheelDisposer) { this._mouseWheelDisposer.dispose(); if (this.scrollbar) { this.scrollbar.dispose(); this.scrollbar = undefined; } } } } }, enumerable: true, configurable: true }); /** * Handles mouse wheel scrolling of legend. * * @param event Event */ Legend.prototype.handleWheel = function (event) { var shift = event.shift.y; var scrollbar = this.scrollbar; if (scrollbar) { var ds = (shift / 1000 * this.measuredHeight / this.contentHeight); var delta = scrollbar.end - scrollbar.start; if (shift > 0) { scrollbar.start = $math.max(0, scrollbar.start - ds); scrollbar.end = scrollbar.start + delta; } else { scrollbar.end = $math.min(1, scrollbar.end - ds); scrollbar.start = scrollbar.end - delta; } } }; /** * @ignore */ Legend.prototype.updateMasks = function () { var _this = this; if (this.scrollbar) { this.itemContainers.each(function (itemContainer) { itemContainer.dy = -_this.scrollbar.thumb.pixelY * _this.contentHeight / _this.measuredHeight; itemContainer.maskRectangle = { x: 0, y: -itemContainer.dy, width: _this.measuredWidth, height: _this.measuredHeight }; }); } }; /** * Toggles a legend item. * * @ignore Exclude from docs * @param item Legend item * @todo Maybe do it with togglable instead */ Legend.prototype.toggleDataItem = function (item) { var dataContext = item.dataContext; if (!dataContext.visible || dataContext.isHiding || (dataContext instanceof Sprite && dataContext.isHidden)) { item.color = item.colorOrig; item.itemContainer.isActive = false; if (dataContext.hidden === true) { dataContext.hidden = false; } if (dataContext.show) { dataContext.show(); } else { dataContext.visible = true; } this.svgContainer.readerAlert(this.language.translate("%1 shown", this.language.locale, item.label.readerTitle)); } else { item.itemContainer.isActive = true; if (dataContext.hide) { dataContext.hide(); } else { dataContext.visible = false; } this.svgContainer.readerAlert(this.language.translate("%1 hidden", this.language.locale, item.label.readerTitle)); item.color = new InterfaceColorSet().getFor("disabledBackground"); } }; Object.defineProperty(Legend.prototype, "preloader", { /** * Override preloader method so that legend does not accidentally show its * own preloader. * * @ignore Exclude from docs * @return Always `undefined` */ get: function () { return; }, enumerable: true, configurable: true }); /** * [handleDataItemPropertyChange description] * * @ignore Exclude from docs */ Legend.prototype.handleDataItemPropertyChange = function (dataItem, name) { dataItem.valueLabel.invalidate(); dataItem.label.invalidate(); }; return Legend; }(Component)); export { Legend }; /** * Register class in system, so that it can be instantiated using its name from * anywhere. * * @ignore */ registry.registeredClasses["Legend"] = Legend; /** * Add default responsive rules */ /** * Move legend to below the chart if chart is narrow */ defaultRules.push({ relevant: ResponsiveBreakpoints.widthXS, state: function (target, stateId) { if (target instanceof Legend && (target.position == "left" || target.position == "right")) { var state = target.states.create(stateId); state.properties.position = "bottom"; return state; } return null; } }); /** * Move legend to the right if chart is very short */ defaultRules.push({ relevant: ResponsiveBreakpoints.heightXS, state: function (target, stateId) { if (target instanceof Legend && (target.position == "top" || target.position == "bottom")) { var state = target.states.create(stateId); state.properties.position = "right"; return state; } return null; } }); /** * Disable legend altogether on small charts */ defaultRules.push({ relevant: ResponsiveBreakpoints.isXS, state: function (target, stateId) { if (target instanceof Legend) { var state = target.states.create(stateId); state.properties.disabled = true; return state; } return null; } }); //# sourceMappingURL=Legend.js.map
var Code = require('code'), Lab = require('lab'), lab = exports.lab = Lab.script(), describe = lab.experiment, beforeEach = lab.beforeEach, afterEach = lab.afterEach, before = lab.before, after = lab.after, it = lab.test, expect = Code.expect, nock = require("nock"), sinon = require("sinon"), cache = require("../../lib/cache"), fixtures = require('../fixtures'); var User, spy; beforeEach(function(done) { User = new (require("../../models/user"))({ host: "https://user.com" }); spy = sinon.spy(function(a, b, c) {}); User.getMailchimp = function() { return { lists: { subscribe: spy } }; }; done(); }); afterEach(function(done) { User = null; done(); }); before(function(done) { process.env.USE_CACHE = 'true'; process.env.LICENSE_API = "https://license-api-example.com"; cache.configure({ redis: "redis://localhost:6379", ttl: 5, prefix: "cache:" }); done(); }); after(function(done) { delete process.env.USE_CACHE; cache.disconnect(); done(); }); describe("User", function() { describe("initialization", function() { it("defaults to process.env.USER_API as host", function(done) { var USER_API_OLD = process.env.USER_API; process.env.USER_API = "https://envy.com/"; expect(new (require("../../models/user"))().host).to.equal('https://envy.com/'); process.env.USER_API = USER_API_OLD; done(); }); it("accepts a custom host", function(done) { expect(User.host).to.equal('https://user.com'); done(); }); }); describe("login", function() { it("makes an external request for /{user}/login", function(done) { var userMock = nock(User.host) .post('/user/bob/login') .reply(200, fixtures.users.bob); var loginInfo = { name: 'bob', password: '12345' }; User.login(loginInfo, function(err, user) { expect(err).to.be.null(); expect(user).to.exist(); userMock.done(); done(); }); }); }); describe("verifyPassword", function() { it("is essentially login with separated params", function(done) { var bob = fixtures.users.bob; var userMock = nock(User.host) .post('/user/' + bob.name + '/login') .reply(200, bob); User.verifyPassword(bob.name, '12345', function(err, user) { expect(err).to.be.null(); expect(user).to.exist(); userMock.done(); done(); }); }); }); describe("generate options for user ACL", function() { it("formats the options object for request/cache", function(done) { var obj = User.generateUserACLOptions('foobar'); expect(obj).to.be.an.object(); expect(obj.url).to.equal('https://user.com/user/foobar'); expect(obj.json).to.be.true(); done(); }); }); describe("get()", function() { it("makes an external request for /{user} and returns the response body in the callback", function(done) { var userMock = nock(User.host) .get('/user/bob') .reply(200, fixtures.users.bob); var licenseMock = nock('https://license-api-example.com') .get('/customer/bob/stripe') .reply(404); User.dropCache(fixtures.users.bob.name, function(err) { expect(err).to.not.exist(); User.get(fixtures.users.bob.name, function(err, body) { userMock.done(); licenseMock.done(); expect(err).to.be.null(); expect(body).to.exist(); expect(body.name).to.equal("bob"); expect(body.email).to.exist(); expect(body.isPaid).to.be.false(); done(); }); }); }); it("doesn't make another external request due to caching", function(done) { // no need for nock because no request will be made User.get(fixtures.users.bob.name, function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); expect(body.name).to.equal("bob"); expect(body.email).to.exist(); expect(body.isPaid).to.exist(); done(); }); }); it("makes the external request again if the cache is dropped", function(done) { var userMock = nock(User.host) .get('/user/bob') .reply(200, fixtures.users.bob); var licenseMock = nock('https://license-api-example.com') .get('/customer/bob/stripe') .reply(200, fixtures.customers.bob); User.dropCache(fixtures.users.bob.name, function(err) { User.get(fixtures.users.bob.name, function(err, body) { expect(err).to.be.null(); expect(body.name).to.equal("bob"); expect(body.isPaid).to.be.true(); userMock.done(); licenseMock.done(); done(); }); }); }); it("returns an error in the callback if the request failed", function(done) { var userMock = nock(User.host) .get('/user/foo') .reply(404); var licenseMock = nock('https://license-api-example.com') .get('/customer/foo/stripe') .reply(404); User.get('foo', function(err, body) { expect(err).to.exist(); expect(err.message).to.equal("unexpected status code 404"); expect(body).to.not.exist(); userMock.done(); licenseMock.done(); done(); }); }); it("does not require a bearer token", function(done) { User.dropCache('hermione', function(err) { expect(err).to.not.exist(); var userMock = nock(User.host, { reqheaders: {} }) .get('/user/hermione') .reply(200); var licenseMock = nock('https://license-api-example.com') .get('/customer/hermione/stripe') .reply(404); User.get('hermione', function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); userMock.done(); licenseMock.done(); done(); }); }); }); }); describe("getPackages()", function() { var body = { items: [ { name: "foo", description: "It's a foo!", access: "restricted" }, { name: "bar", description: "It's a bar!", access: "public" } ], count: 2 }; it("makes an external request for /{user}/package", function(done) { var packageMock = nock(User.host) .get('/user/bob/package?format=mini&per_page=100&page=0') .reply(200, []); User.getPackages(fixtures.users.bob.name, function(err, body) { packageMock.done(); expect(err).to.be.null(); expect(body).to.exist(); done(); }); }); it("returns the response body in the callback", function(done) { var packageMock = nock(User.host) .get('/user/bob/package?format=mini&per_page=100&page=0') .reply(200, body); User.getPackages(fixtures.users.bob.name, function(err, body) { expect(err).to.be.null(); expect(body).to.be.an.object(); expect(body.items).to.be.an.array(); expect(body.items[0].name).to.equal("foo"); expect(body.items[1].name).to.equal("bar"); packageMock.done(); done(); }); }); it("updates privacy of packages", function(done) { var packageMock = nock(User.host) .get('/user/bob/package?format=mini&per_page=100&page=0') .reply(200, body); User.getPackages(fixtures.users.bob.name, function(err, body) { expect(err).to.be.null(); expect(body).to.be.an.object(); expect(body.items).to.be.an.array(); expect(body.items[0].isPrivate).to.be.true(); expect(body.items[1].isPrivate).to.not.exist(); packageMock.done(); done(); }); }); it("returns an error in the callback if the request failed", function(done) { var packageMock = nock(User.host) .get('/user/foo/package?format=mini&per_page=100&page=0') .reply(404); User.getPackages('foo', function(err, body) { expect(err).to.exist(); expect(err.message).to.equal("error getting packages for user foo"); expect(err.statusCode).to.equal(404); expect(body).to.not.exist(); packageMock.done(); done(); }); }); it("includes bearer token in request header if user is logged in", function(done) { User = new (require("../../models/user"))({ host: "https://user.com", bearer: "sally" }); var packageMock = nock(User.host, { reqheaders: { bearer: 'sally' } }) .get('/user/sally/package?format=mini&per_page=100&page=0') .reply(200, body); User.getPackages('sally', function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); packageMock.done(); done(); }); }); it("does not include bearer token in request header if user is not logged in", function(done) { var packageMock = nock(User.host) .get('/user/sally/package?format=mini&per_page=100&page=0') .reply(200, body); User.getPackages('sally', function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); packageMock.done(); done(); }); }); it("gets a specific page of packages", function(done) { var packageMock = nock(User.host) .get('/user/sally/package?format=mini&per_page=100&page=2') .reply(200, body); User.getPackages('sally', 2, function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); expect(body.hasMore).to.be.undefined(); packageMock.done(); done(); }); }); it("adds a `hasMore` key for groups that have more packages hiding", function(done) { var arr = []; for (var i = 0, l = 100; i < l; ++i) { arr.push({ name: "foo" + i, description: "It's a foo!", access: "public" }); } var body = { items: arr, count: 150 }; var packageMock = nock(User.host) .get('/user/sally/package?format=mini&per_page=100&page=0') .reply(200, body); User.getPackages('sally', 0, function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); expect(body.hasMore).to.be.true(); packageMock.done(); done(); }); }); }); describe("getStars()", function() { it("makes an external request for /{user}/stars?format=detailed", function(done) { var starMock = nock(User.host) .get('/user/bcoe/stars?format=detailed') .reply(200, ['lodash', 'nock', 'yargs']); User.getStars('bcoe', function(err, body) { starMock.done(); expect(err).to.be.null(); expect(body).to.exist(); done(); }); }); it("returns the response body in the callback", function(done) { var starMock = nock(User.host) .get('/user/ceej/stars?format=detailed') .reply(200, ['blade', 'minimist']); User.getStars('ceej', function(err, body) { expect(err).to.be.null(); expect(body).to.be.an.array(); expect(body[0]).to.equal("blade"); expect(body[1]).to.equal("minimist"); starMock.done(); done(); }); }); it("returns an error in the callback if the request failed", function(done) { var starMock = nock(User.host) .get('/user/zeke/stars?format=detailed') .reply(404); User.getStars('zeke', function(err, body) { starMock.done(); expect(err).to.exist(); expect(err.message).to.equal("error getting stars for user zeke"); expect(err.statusCode).to.equal(404); expect(body).to.not.exist(); done(); }); }); it("includes bearer token in request header if user is logged in", function(done) { User = new (require("../../models/user"))({ host: "https://user.com", bearer: "rod11" }); var starMock = nock(User.host, { reqheaders: { bearer: 'rod11' } }) .get('/user/rod11/stars?format=detailed') .reply(200, 'something'); User.getStars('rod11', function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); starMock.done(); done(); }); }); it("does not include bearer token in request header if user is not logged in", function(done) { var starMock = nock(User.host) .get('/user/rod11/stars?format=detailed') .reply(200, 'something'); User.getStars('rod11', function(err, body) { expect(err).to.be.null(); expect(body).to.exist(); starMock.done(); done(); }); }); }); describe("lookup users by email", function() { it("returns an error for invalid email addresses", function(done) { User.lookupEmail('barf', function(err, usernames) { expect(err).to.exist(); expect(err.statusCode).to.equal(400); expect(usernames).to.be.undefined(); done(); }); }); it("returns an array of email addresses", function(done) { var lookupMock = nock(User.host) .get('/user/[email protected]') .reply(200, ['user', 'user2']); User.lookupEmail('[email protected]', function(err, usernames) { expect(err).to.not.exist(); expect(usernames).to.be.an.array(); expect(usernames[0]).to.equal('user'); expect(usernames[1]).to.equal('user2'); lookupMock.done(); done(); }); }); it("passes any errors on to the controller", function(done) { var lookupMock = nock(User.host) .get('/user/[email protected]') .reply(400, []); User.lookupEmail('[email protected]', function(err, usernames) { expect(err).to.exist(); expect(err.statusCode).to.equal(400); expect(usernames).to.not.exist(); lookupMock.done(); done(); }); }); }); describe("signup", function() { var signupInfo = { name: 'hello', password: '12345', email: '[email protected]' }; var userObj = { name: signupInfo.name, email: "[email protected]" }; it("passes any errors along", function(done) { var signupMock = nock(User.host) .put('/user', signupInfo) .reply(400); User.signup(signupInfo, function(err, user) { expect(err).to.exist(); expect(err.statusCode).to.equal(400); expect(user).to.not.exist(); signupMock.done(); done(); }); }); it("returns a user object when successful", function(done) { var signupMock = nock(User.host) .put('/user', signupInfo) .reply(200, userObj); User.signup(signupInfo, function(err, user) { expect(err).to.not.exist(); expect(user).to.exist(); expect(user.name).to.equal(signupInfo.name); signupMock.done(); done(); }); }); describe('the mailing list checkbox', function() { var params = { id: 'e17fe5d778', email: { email: '[email protected]' } }; it('adds the user to the mailing list when checked', function(done) { var userMock = nock("https://user.com") .put('/user', { "name": "boom", "password": "12345", "verify": "12345", "email": "[email protected]" }) .reply(404) .put('/user', { "name": "boom", "password": "12345", "verify": "12345", "email": "[email protected]", "npmweekly": "on" }) .reply(201); spy.reset(); User.signup({ name: 'boom', password: '12345', verify: '12345', email: '[email protected]', npmweekly: "on" }, function(er, user) { expect(er).to.not.exist(); // userMock.done(); expect(spy.calledWith(params)).to.be.true(); done(); }); }); it('does not add the user to the mailing list when unchecked', function(done) { spy.reset(); User.getMailchimp = function() { return { lists: { subscribe: spy } }; }; User.signup({ name: 'boom', password: '12345', verify: '12345', email: '[email protected]' }, function(er, user) { expect(spy.called).to.be.false(); done(); }); }); }); }); describe("save", function() { var profile = { name: "npmjs", resources: { twitter: "npmjs", github: "" } }; var userObj = { name: "npmjs", email: "[email protected]", resources: { twitter: "npmjs", github: "" } }; it("bubbles up any errors that might occur", function(done) { var saveMock = nock(User.host) .post('/user/npmjs', profile) .reply(400); User.save(profile, function(err, user) { expect(err).to.exist(); expect(err.statusCode).to.equal(400); expect(user).to.not.exist(); saveMock.done(); done(); }); }); it("hits the save url", function(done) { var saveMock = nock(User.host) .post('/user/npmjs', profile) .reply(200, userObj); User.save(profile, function(err, user) { expect(err).to.not.exist(); expect(user).to.exist(); expect(user.name).to.equal('npmjs'); expect(user.email).to.equal('[email protected]'); saveMock.done(); done(); }); }); }); });
 angular.module('umbraco.resources') .factory('nuPickers.Shared.RelationMapping.RelationMappingResource', ['$http', 'editorState', function ($http, editorState) { return { getRelatedIds: function (model) { return $http({ method: 'GET', url: 'backoffice/nuPickers/RelationMappingApi/GetRelatedIds', params: { 'contextId': editorState.current.id, 'propertyAlias' : model.alias, 'relationTypeAlias': model.config.relationMapping.relationTypeAlias, 'relationsOnly' : model.config.saveFormat == 'relationsOnly' } }); } }; } ]);
$(function() { $('form').submit(function() { if (validateUsername() && validateUserPassword()) { $.post('auth.php',$('form').serialize(),function(response) { if (response == 'true') { showSuccess('You will be redirected in a moment'); } else { showError(response); } }); } function validateUsername() { if ($('#username').val().length == 0) { showError('Username cannot be empty'); return false; } else { return true; } }; function validateUserPassword() { if ($('#password').val().length == 0) { showError('password cannot be empty'); return false; } else { return true; } }; function showSuccess(message) { $('<div class="ui-loader ui-overlay-shadow ui_body_success ui-corner-all"><h1>' + message + '</h1></div>').css({ "display" : "block", "opacity" : 0.96, "background" : "orange", "font-size" : "12px", top : $(window).scrollTop() + 10 }).appendTo($.mobile.pageContainer).delay(2000).fadeOut(400, function() { $(this).remove(); }); }; function showError(message) { $('<div class="ui-loader ui-overlay-shadow ui_body_error ui-corner-all"><h1>' + message + '</h1></div>').css({ "display" : "block", "opacity" : 0.96, "background" : "orange", "font-size" : "12px", top : $(window).scrollTop() + 10 }).appendTo($.mobile.pageContainer).delay(2000).fadeOut(400, function() { $(this).remove(); }); }; return false; }); });
/** *Base.js 提供统一的接口,与具体的功能无关 */ /** * 全局变量对象 */ var MECHAT = {}; /** * 定义命名空间的变量 */ MECHAT.namespace = function(str) { var arr = str.split("."), o = MECHAT; for (i = (arr[0] == "MECHAT") ? 1 : 0; i < arr.length; i++) { o[arr[i]] = o[arr[i]] || {}; o = o[arr[i]]; } }; /** * Dom相关 */ MECHAT.namespace("Dom"); //定义命名空间 MECHAT.Dom.setOpacity = function(node, level) { if (document.all) { node.style.filter = 'alpha(opacity=' + level + ')'; } else { node.style.opacity = level / 100; } }; /** * 获取节点 * node 节点对象(#id,.class,element) 字符类型 * parent 节点的上层对象 */ MECHAT.Dom.get = function(node, parent) { parent = parent || document; if (node.indexOf("#") > -1) { //Id类型 node = node.replace("#", ""); node = parent.getElementById(node); } else if (node.indexOf(".") > -1) { //class类型 var tag = "*", arr = []; if (node.indexOf(".") != 0) { var sp = node.split("."); tag = sp[0]; node = sp[1]; } else { node = node.replace(".", ""); } var els = parent.getElementsByTagName(tag); for (var i = 0, n = els.length; i < n; i++) { for (var j = 0, k = els[i].className.split(" "), l = k.length; j < l; j++) { if (k[j] == node) { arr.push(els[i]); break; } } } node = arr; } else { //节点名称 node = parent.getElementsByTagName(node); } return node; }; /** * 对象的隐藏与显示 */ MECHAT.Dom.show = function(node) { node.style.display = "block"; }; MECHAT.Dom.hide = function(node) { node.style.display = "none"; }; /** * 动态加载JS */ MECHAT.Dom.loadScript = function(url) { var script = document.createElement("script"); script.type = "text/javascript"; script.src = url; document.body.appendChild(script); }; /** * 动态加载css */ MECHAT.Dom.loadStyle = function(css) { var style = document.createElement("style"); style.type = "text/css"; try { style.appendChild(document.createTextNode(css)); } catch (ex) { style.styleSheet.cssText = css; } var head = document.getElementsByTagName("head")[0]; head.appendChild(style); }; /** * style样式设置 * @Param el 节点对象 * @param attr css属性 * @param style 对应属性的样式 */ MECHAT.Dom.css = function(el, attr, style) { el.style[attr] = style; }; /** * 删除class */ MECHAT.Dom.rmClass = function(el, cls) { var c = el.getAttribute("class") || ''; if (c) { c = c.replace(cls, ''); el.setAttribute('class', c); } }; MECHAT.Dom.addClass = function(el, cls) { var c = el.getAttribute("class") || ''; c += " " + cls; el.setAttribute('class', c); }; /** * Bower 浏览器相关 */ MECHAT.namespace("Broswer"); //定义命名空间 MECHAT.Broswer = { IE6: "msie 6", IE7: "msie 7", IE8: "msie 8", IE9: "msie 9", IE10: "msie 10", IE11: "msie 11", Chrome: "chrome", Firefox: "firefox", Opera: "opera", Safari: "safari", Netscape: "netscape" }; //获取浏览器类型 MECHAT.Broswer.get = function() { var name = "netscape"; var ag = navigator.userAgent.toLowerCase(); if (/(msie|firefox|opera|chrome|netscape)\D+(\d[\d.*])/.test(ag)) { var n = RegExp.$1; var v = parseInt(RegExp.$2); name = n; if (n == "msie") { name += " " + v; } } else if (/version\D+(\d[\d.]*).*safari/.test(ag)) { name = "safari"; } return name; }; MECHAT.Broswer.isIE = function() { return ("ActiveXObject" in window); }; MECHAT.Broswer.parseQuerystring = function(str) { if ('string' !== typeof str) { return {}; } str = MECHAT.Lang.trim(str); if ('' === str) { return {}; } var obj = {}; try { var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); if (parts[0] && parts[1]) { obj[parts[0]] = decodeURIComponent(parts[1]) } } } catch (ex) { } return obj; }; MECHAT.Broswer.mc_getReferrer = function() { var ret = ''; // first, lookup at url query string if (location.search.length > 1) { var query_str = location.search.replace('?', ''); var query = this.parseQuerystring(query_str); if (query['_realref_']) { ret = query['_realref_']; return ret; } } // second, lookup at meta tag var metaRealRef = document.getElementById('_realref_'); if (metaRealRef) { ret = metaRealRef.getAttribute('realref') || ''; if (ret.length > 0) return ret; } // third, use js document.referrer return document.referrer; }; /** * 验证是否是苹果机 */ MECHAT.Broswer.isApple = function() { if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {   if (document.cookie.indexOf("iphone_redirect=false") == -1) {     return true;   } } return false; }; /** * 获取url中的主域名 */ MECHAT.Broswer.getPriDomain = function(url) { var host = "null"; if (typeof url == "undefined" || null == url) { url = window.location.href; } var regex = /.*\:\/\/([^\/]*).*/; var match = url.match(regex); if (typeof match != "undefined" && null != match) host = match[1]; if (host.indexOf(".") > 0) { var arr = host.split("."); var len = arr.length; if (len > 2) { host = arr[len - 2] + "." + arr[len - 1]; } } return host; }; /** * Event相关 */ MECHAT.namespace("Event"); //定义命名空间 MECHAT.Event.getEventTarget = function(e) { }; MECHAT.Event.stopPropagation = function(e) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } }; MECHAT.Event.on = function(node, eventType, handler) { node = typeof node == "string" ? document.getElementById(node) : node; if (node.addEventListener) { node.addEventListener(eventType, handler, false); } else if (node.attachEvent) { node.attachEvent("on" + eventType, handler); } else { node["on" + eventType] = handler; } }; MECHAT.Event.defautChnage = function(el, type, cb) { el.onfocus = function() { var val = el.defaultValue; var str = ''; if (type == 'div') { str = el.innerHTML; } else if (type == 'input') { str = el.value; } str = MECHAT.Lang.trim(str); if (!val || val == str) { el.defaultValue = str; if (type == 'div') { el.innerHTML = ''; } else if (type == 'input') { el.value = ''; } } //设置文字的颜色 el.setAttribute("style", "color:#333;"); if (cb) { cb(); } } el.onblur = function() { var str = ''; if (type == 'div') { str = el.innerHTML; } else if (type == 'input') { str = el.value; } str = MECHAT.Lang.trim(str); if (str.length == 0 || str == '<br>') { if (type == 'div') { el.innerHTML = el.defaultValue; el.setAttribute("style", "color:#999;"); } else if (type == 'input') { el.value = el.defaultValue; el.setAttribute("style", "color:#999;"); } } } }; /** * Lang相关 */ MECHAT.namespace("Lang"); //定义命名空间 MECHAT.Lang = { telRegFatory: function(reg) { return [ [RegExp('^' + reg + '$', 'gm'), "<a target='_blank' href=\"tel:$1\">$1</a>"], [RegExp('^' + reg + '(\\D)', 'gm'), "<a target='_blank' href=\"tel:$1\">$1</a>$2"], [RegExp('(\\D)' + reg + '$', 'gm'), "$1<a target='_blank' href=\"tel:$2\">$2</a>"], [RegExp('(\\D)' + reg + '(\\D)', 'gm'), "$1<a target='_blank' href=\"tel:$2\">$2</a>$3"] ] }, regUrl: [ [/((ftp:\/\/)[^\u4E00-\u9FA5 ]+)/ig, "<a target='_blank' href=\"$1\">$1</a>"], [/((http:\/\/|https:\/\/)[^\u4E00-\u9FA5 ]+)/ig, "<a target='_blank' href=\"$1\">$1</a>"], [/((www\.)[^\u4E00-\u9FA5 ]+)/ig, "<a target='_blank' href=\"http://$1\">$1</a>"], [/([\.A-Za-z0-9-]+?\.((com)|(net)|(im)|(cn)|(me)|(org)|(edu)|(cc)|(biz)|(info)|(tv)|(co)|(so)|(tel)|(mobi))[/?#][^\u4E00-\u9FA5, ]+)/img, "<a target='_blank' href=\"http://$1\">$1</a>"], [/([\.A-Za-z0-9-]+?\.((com)|(net)|(im)|(cn)|(me)|(org)|(edu)|(cc)|(biz)|(info)|(tv)|(co)|(so)|(tel)|(mobi))[/?#])/img, "<a target='_blank' href=\"http://$1\">$1</a>"], [/([\.A-Za-z0-9-]+?\.((com)|(net)|(im)|(cn)|(me)|(org)|(edu)|(cc)|(biz)|(info)|(tv)|(co)|(so)|(tel)|(mobi)))([0-9\s\u4E00-\u9FA5,]+)/img, "<a target='_blank' href=\"http://$1\">$1</a>$18"], [/([\.A-Za-z0-9-]+?\.((com)|(net)|(im)|(cn)|(me)|(org)|(edu)|(cc)|(biz)|(info)|(tv)|(co)|(so)|(tel)|(mobi)))$/img, "<a target='_blank' href=\"http://$1\">$1</a>"] ], regTel: [], regEmail: [ [/([A-Z0-9\._%+-]+@[A-Z0-9\.-]+\.[A-Z]{2,15})/img, '<a href="mailto:$1">$1</a>'] ] }; MECHAT.Lang.regTel = MECHAT.Lang.regTel.concat(MECHAT.Lang.telRegFatory('([1]\\d{10})')); MECHAT.Lang.regTel = MECHAT.Lang.regTel.concat(MECHAT.Lang.telRegFatory('([48]00\\d?-?\\d{3,4}-?\\d{3,4})')); MECHAT.Lang.regTel = MECHAT.Lang.regTel.concat(MECHAT.Lang.telRegFatory('(0\\d{2,3}-?\\d{7,8})')); MECHAT.Lang.regTel = MECHAT.Lang.regTel.concat(MECHAT.Lang.telRegFatory('(\\d{8})')); MECHAT.Lang.replace = function(text, regexp) { var ele = document.createElement('div'); ele.innerHTML = text; for (var i in ele.childNodes) { var el = ele.childNodes[i]; if (el.nodeType == 3) { var ele2 = document.createElement('em'); ele2.appendChild(el.cloneNode(true)); var oldHtml = ele2.innerHTML; ele2.innerHTML = ele2.innerHTML.replace(regexp[0], regexp[1]); if (ele2.innerHTML != oldHtml) { ele.replaceChild(ele2, el); } } } return ele.innerHTML.replace(/\<em\>/g, '').replace(/\<\/em\>/g, ''); }; MECHAT.Lang.replaceTel = function(text) { for (var i in this.regTel) { text = this.replace(text, this.regTel[i]); } return text; }; MECHAT.Lang.replaceUrl = function(text) { for (var i in this.regUrl) { text = this.replace(text, this.regUrl[i]); } return text; }; MECHAT.Lang.replaceEmail = function(text) { for (var i in this.regEmail) { text = this.replace(text, this.regEmail[i]); } return text; }; MECHAT.Lang.urlTelTrans = function(text) { text = this.replaceEmail(text); text = this.replaceUrl(text); text = this.replaceTel(text); return text; }; MECHAT.Lang.trim = function(s) { if (typeof s == 'undefined') { return ''; } // s = s.replace(/\<div\>\<br\>\<\/div\>/g,""); // s = s.replace(/&nbsp;/g,""); s = s.replace(/^\s*/g, ''); return s.replace(/\s*$/g, ''); }; MECHAT.Lang.isNumber = function(s) { return !isNaN(s); }; MECHAT.Lang.isEmail = function(str) { // var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; var reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return reg.test(str); }; MECHAT.Lang.isQQ = function(str) { var result = str.match(/[1-9][0-9]{4,}/); if (result == null) return false; return true; }; MECHAT.Lang.isImg = function(str) { var ext = str.substring(str.lastIndexOf('.') + 1, str.length); ext = ext.toLowerCase(); if (ext != 'jpg' && ext != 'jpeg' && ext != "png" && ext != "gif" && ext != "bmp") { return false; } return true; }; MECHAT.Lang.httpReplace = function(txt) { var regex = /(https?:\/\/)?(\w+\.?)+(\/[a-zA-Z0-9\?%=_\-\+\/]+)?/gi; return txt.replace(regex, function(match, capture) { if (capture) { return match } else { return 'http://' + match; } }); }; //换行的处理 MECHAT.Lang.html_enline = function(str) { if (typeof str != 'string') { return str; } var s = ""; if (!str || str.length == 0) return ""; s = str.replace(/\n/g, "<br>"); return s; }; /** * 获取后缀名 */ MECHAT.Lang.getSuffix = function(str) { return str.substring(str.lastIndexOf('.') + 1, str.length); }; //是否是座机 MECHAT.Lang.isTell = function(str) { // var result = str.match(/^(\d{2,4}[-_-—]?)?\d{3,8}([-_-—]?\d{3,8})?([-_-—]?\d{1,7})?$)|(^0?1[35]\d{9}$/); // var result = str.match(/^[0-9]{3,4}\-[0-9]{7,8}$)|(^[0-9]{7,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$/); var result = str.match(/\d{3}-\d{8}|\d{4}-\d{7}/); if (result == null) return false; return true; }; MECHAT.Lang.isPhone = function(str) { var result = str.match(/1[3-8]+\d{9}/); if (result == null) return false; return true; }; MECHAT.Lang.isMac = function() { if (navigator.userAgent.indexOf("Mac OS X") > 0) { return true; } return false; }; MECHAT.Lang.html_encode = function(str) { var s = ""; if (str.length == 0) return ""; s = str.replace(/&/g, "&amp;"); s = s.replace(/</g, "&lt;"); s = s.replace(/>/g, "&gt;"); s = s.replace(/\'/g, "&#39;"); s = s.replace(/\"/g, "&quot;"); s = s.replace(/\n/g, "<br>"); return s; }; //时间的格式化 Date.prototype.format = function(format) { var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": this.getHours(), //hour "m+": this.getMinutes(), //minute "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() //millisecond } if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; //时间的转换 MECHAT.Lang.fromNow = function(date) { var now = new Date; var now_d = now.getDate(); var t; var format = function(n, unit) { return n + " " + unit; } // past / future var diff = date > now ? date - now : now - date; date = new Date(date); var y = date.getFullYear(); //获取完整的年份(4位,1970-????) var mon = date.getMonth() + 1; //获取当前月份(0-11,0代表1月) var d = date.getDate(); //获取当前日(1-31) var h = date.getHours(); //获取当前小时数(0-23) var m = date.getMinutes(); //获取当前分钟数(0-59) h = h < 10 ? ("0" + h) : h; m = m < 10 ? ("0" + m) : m; var d_s = now_d - d; if (d_s == 0) { return format("今天", h + ":" + m); } else if (d_s == 1) { return format("昨天", h + ":" + m); } else { return format(mon + "月" + d + "日", h + ":" + m); } return format(y + "年" + mon + "月" + d + "日", h + ":" + m); }; //unicode的转换 MECHAT.Lang.uc2encode = function(str) { var t = escape(str); t = t.replace(/\%u/g, '\\u'); return t; }; /** * 将对象转为字符串 */ MECHAT.Lang.objToStr = function(obj) { var str = ''; if (typeof obj == "object") { for (var k in obj) { var v = obj[k]; str += k + "[@]" + v + "[#]"; } } else { str = obj; } return str; }; /** * 按照自定义的规则,把字符串拆分成对象 */ MECHAT.Lang.strToObj = function(str) { var obj = {}; if (typeof str == "string" && str.indexOf("#") > 0) { str = str.split('[#]'); for (var i = 0, len = str.length; i < len; i++) { var s = str[i]; if (s.indexOf("[@]") > 0) { s = s.split("[@]"); obj[s[0]] = s[1]; } } } else { obj = str; } return obj; }; /** * Obj 对象相关 */ MECHAT.namespace("Obj"); //定义命名空间 //将origin的属性设置到obj上 MECHAT.Obj.setProperty = function(obj, origin) { for (var v in origin) { if (obj.hasOwnProperty(v) && origin[v]) { obj[v] = origin[v]; } }; }; /* *Common.js 可覆用性的组件 2014-10-19合并过来 */ /** * Cookie相关操作 */ MECHAT.namespace("Cookie"); MECHAT.Cookie = { read: function(key, dc) { key = encodeURIComponent(key) + "="; var cookieStr = document.cookie, cookieValue = null; var start = cookieStr.indexOf(key), end = cookieStr.indexOf(";", start), end = end == -1 ? cookieStr.length : end; if (start > -1) { cookieValue = cookieStr.substring(start + key.length, end); if (!dc) { cookieValue = decodeURIComponent(cookieValue); } } return cookieValue; }, readObj: function(key) { var val = this.read(key, true); var obj = {}; if (val) { val = val.split('&'); for (var i = 0, len = val.length; i < len; i++) { var v = val[i]; v = v.split("="); obj[decodeURIComponent(v[0])] = decodeURIComponent(v[1]); }; } return obj; }, set: function(key, value, expires, path, domain, secure) { var cookieText = encodeURIComponent(key) + "=", subCookieParts = new Array(); switch (typeof value) { case 'object': for (var subName in value) { if (subName.length > 0 && value.hasOwnProperty(subName)) { subCookieParts.push(encodeURIComponent(subName) + "=" + encodeURIComponent(value[subName])); } } if (subCookieParts.length > 0) { cookieText += subCookieParts.join('&'); } break; default: cookieText += encodeURIComponent(value); break; } if (!expires) { expires = new Date(); expires.setTime(expires.getTime() + 90 * 24 * 3600 * 1000); //默认cookie存放时间 } if (expires instanceof Date) { cookieText += "; expires=" + expires.toGMTString(); } if (path) { cookieText += "; path=" + path; } if (domain) { cookieText += "; domain=" + domain; } if (secure) { cookieText += "; secure"; } document.cookie = cookieText; } }; /** * Ajax相关 */ MECHAT.namespace("Ajax"); MECHAT.Ajax.createCORSRequest = function() { if (typeof XMLHttpRequest != "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject != "undefined") { if (typeof arguments.callee.activeXString != "string") { var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len; for (i = 0, len = versions.length; i < len; i++) { try { new ActiveXObject(versions[i]); arguments.callee.activeXString = versions[i]; break; } catch (ex) {} } } return new ActiveXObject(arguments.callee.activeXString); } return xhr; }; MECHAT.Ajax.makeQuery = function(json) { json = json || {}; var query_arr = []; json.__ = new Date().getTime(); for (var key in json) { var val = json[key]; query_arr.push(key + '=' + encodeURIComponent(val)); } var query = query_arr.join('&').replace(/%20/g, '+'); return query; }; //param 参考包括success,error,timeout,timeoutBack MECHAT.Ajax.post = function(url, data, param) { var xhr = this.createCORSRequest(); var timeEr = null; try { if (param.timeout) { //超时断开访问 timeEr = setTimeout(function() { param.timeoutBack(); //调用回调函数 xhr.abort(); }, param.timeout); } var sendStr = data; if (typeof data == 'object') { sendStr = this.makeQuery(data); } xhr.open('post', url, true); if (param.author) { xhr.setRequestHeader("Authorization", param.author); } var contet_type = param.type || "application/x-www-form-urlencoded; charset=UTF-8"; xhr.setRequestHeader("Content-Type", contet_type); xhr.send(sendStr); if (typeof param.success != 'undefined') { //设置执行成功后的函数 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { if (timeEr) { clearTimeout(timeEr); } param.success(xhr.responseText); } } }; } } catch (ex) { if (timeEr) { clearTimeout(timeEr); } if (param.timeoutBack) { param.timeoutBack(); xhr.abort(); } } }; MECHAT.Ajax.get = function(url, data, param) { try { var xhr = this.createCORSRequest(); url += "?" + this.makeQuery(data); xhr.open("get", url, false); if (typeof param.success != 'undefined') { //设置执行成功后的函数 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { param.success(xhr.responseText); } } }; } xhr.send(null); } catch (ex) { if (param.timeoutBack) { param.timeoutBack(); } } }; MECHAT.Ajax.jsonp = function(url, data, callback, param) { if (param && param.timeout) { setTimeout(function() { param.timeoutBack(); }, param.timeout); } var query = this.makeQuery(data) + '&callback=' + callback; var script = document.createElement("script"); script.src = url + "?" + query; try { document.body.appendChild(script); } catch (e) { } }; //文件的上传 MECHAT.Ajax.fileUp = function() { }; /** * Drag 拖拽相关 */ MECHAT.namespace("Drag"); /** * Animation 动画相关 */ MECHAT.namespace("Ani"); /** * 动画移动效果 * @param element执行动画的对象 * @param position 移动的位置、方向{left:120},{top:120} * @param speed 移动的速度1~100 默认为30 * @param callback 回调函数 */ MECHAT.Ani.move = function(element, position, speed, callback) { if (!element.effect) { element.effect = {}; element.effect.move = 0; } clearInterval(element.effect.move); var speed = speed || 30; //因为element.offsetBottom 没有值,所以使用了固定值 var start = { left: element.offsetLeft, bottom: position.b, top: element.offsetTop, right: position.r }; var style = element.style; var parr = new Array(), p, len, bol; if (typeof(position.left) == 'number') { parr.push('left'); p = 'left'; } if (typeof(position.right) == 'number') { parr.push('right'); p = 'right'; } if (typeof(position.bottom) == 'number') { parr.push('bottom'); p = 'bottom'; } if (typeof(position.top) == 'number') { parr.push('top'); p = 'top'; } element.effect.move = setInterval(function() { for (var i = 0; i < parr.length; i++) { start[parr[i]] += (position[parr[i]] - start[parr[i]]) * speed / 100; style[parr[i]] = start[parr[i]] + 'px'; } for (var i = 0; i < parr.length; i++) { if (Math.round(start[parr[i]]) == position[parr[i]]) { if (i != parr.length - 1) { continue; } } else { break; } for (var i = 0; i < parr.length; i++) { style[parr[i]] = position[parr[i]] + 'px' }; clearInterval(element.effect.move); if (callback) { callback(); } } }, 20); }; /** * Color 颜色相关 */ MECHAT.namespace("Color"); MECHAT.Color = { blue: ['#067ab4', '#0c90c2'], gray: ['#616161', '#797979'], green: ['#69b40f', '#81c21d'], initial: ['#47c1a8', '#61cdb8'], red: ['#f23f3f', '#f45959'], rosered: ['#ea4c89', '#ee659d'], yellow: ['#ff8000', '#ff9500'], get: function(k) { k = k.toLowerCase(); return this[k]; } };
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utility methods to deal with CSS3 transitions * programmatically. */ goog.provide('goog.style.transition'); goog.provide('goog.style.transition.Css3Property'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom.vendor'); goog.require('goog.style'); goog.require('goog.userAgent'); /** * A typedef to represent a CSS3 transition property. Duration and delay * are both in seconds. Timing is CSS3 timing function string, such as * 'easein', 'linear'. * * Alternatively, specifying string in the form of '[property] [duration] * [timing] [delay]' as specified in CSS3 transition is fine too. * * @typedef { { * property: string, * duration: number, * timing: string, * delay: number * } | string } */ goog.style.transition.Css3Property; /** * Sets the element CSS3 transition to properties. * @param {Element} element The element to set transition on. * @param {goog.style.transition.Css3Property| * Array.<goog.style.transition.Css3Property>} properties A single CSS3 * transition property or array of properties. */ goog.style.transition.set = function(element, properties) { if (!goog.isArray(properties)) { properties = [properties]; } goog.asserts.assert( properties.length > 0, 'At least one Css3Property should be specified.'); var values = goog.array.map( properties, function(p) { if (goog.isString(p)) { return p; } else { goog.asserts.assertObject(p, 'Expected css3 property to be an object.'); var propString = p.property + ' ' + p.duration + 's ' + p.timing + ' ' + p.delay + 's'; goog.asserts.assert(p.property && goog.isNumber(p.duration) && p.timing && goog.isNumber(p.delay), 'Unexpected css3 property value: %s', propString); return propString; } }); goog.style.transition.setPropertyValue_(element, values.join(',')); }; /** * Removes any programmatically-added CSS3 transition in the given element. * @param {Element} element The element to remove transition from. */ goog.style.transition.removeAll = function(element) { goog.style.transition.setPropertyValue_(element, ''); }; /** * @return {boolean} Whether CSS3 transition is supported. */ goog.style.transition.isSupported = function() { if (!goog.isDef(goog.style.transition.css3TransitionSupported_)) { // Since IE would allow any attribute, we need to explicitly check the // browser version here instead. if (goog.userAgent.IE) { goog.style.transition.css3TransitionSupported_ = goog.userAgent.isVersionOrHigher('10.0'); } else { // We create a test element with style=-vendor-transition // We then detect whether those style properties are recognized and // available from js. var el = document.createElement('div'); var transition = 'transition:opacity 1s linear;'; var vendorPrefix = goog.dom.vendor.getVendorPrefix(); var vendorTransition = vendorPrefix ? vendorPrefix + '-' + transition : ''; el.innerHTML = '<div style="' + vendorTransition + transition + '">'; var testElement = /** @type {Element} */ (el.firstChild); goog.asserts.assert(testElement.nodeType == Node.ELEMENT_NODE); goog.style.transition.css3TransitionSupported_ = goog.style.getStyle(testElement, 'transition') != ''; } } return goog.style.transition.css3TransitionSupported_; }; /** * Whether CSS3 transition is supported. * @type {boolean} * @private */ goog.style.transition.css3TransitionSupported_; /** * Sets CSS3 transition property value to the given value. * @param {Element} element The element to set transition on. * @param {string} transitionValue The CSS3 transition property value. * @private */ goog.style.transition.setPropertyValue_ = function(element, transitionValue) { goog.style.setStyle(element, 'transition', transitionValue); };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ActionInfoOutline = _react2.default.createClass({ displayName: 'ActionInfoOutline', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.createElement('path', { d: 'M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z' }) ); } }); exports.default = ActionInfoOutline; module.exports = exports['default'];
define({ "showLegend": "Hiện chú giải", "controlPopupMenuTitle": "Chọn tác vụ sẽ được hiển thị trên menu ngữ cảnh lớp.", "zoomto": "Phóng tới", "transparency": "Độ trong suốt", "controlPopup": "Bật / Tắt Cửa sổ pop-up", "moveUpAndDown": "Di chuyển lên / Di chuyển xuống", "attributeTable": "Mở Bảng Thuộc tính", "url": "Thông tin mô tả / Hiện Thông tin chi tiết Mục / Tải về", "layerSelectorTitle": "Chọn lớp sẽ được hiển thị trên danh sách." });
var moose = require("../../../../lib"), mysql = moose.adapters.mysql, types = mysql.types; exports.up = function() { moose.createTable("employee", function(table) { table.column("id", types.INT({allowNull : false, autoIncrement : true})); table.column("firstname", types.VARCHAR({length : 20, allowNull : false})); table.column("lastname", types.VARCHAR({length : 20, allowNull : false})); table.column("midinitial", types.CHAR({length : 1})); table.column("gender", types.ENUM({enums : ["M", "F"], allowNull : false})); table.column("street", types.VARCHAR({length : 50, allowNull : false})); table.column("city", types.VARCHAR({length : 20, allowNull : false})); table.primaryKey("id"); }); }; exports.down = function() { moose.dropTable("employee"); };
var util = require('util'), JavaScript = require('../assets/JavaScript'), uglifyJs = JavaScript.uglifyJs, uglifyAst = JavaScript.uglifyAst, extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'), Relation = require('./Relation'); function JavaScriptGetStaticUrl(config) { Relation.call(this, config); } util.inherits(JavaScriptGetStaticUrl, Relation); extendWithGettersAndSetters(JavaScriptGetStaticUrl.prototype, { inline: function () { Relation.prototype.inline.call(this); var newNode; if (this.omitFunctionCall) { newNode = this.to.toAst(); } else { if (this.node instanceof uglifyJs.AST_Call) { this.node.args = [this.to.toAst()]; } else { newNode = new uglifyJs.AST_Call({ expression: new uglifyJs.AST_SymbolRef({ name: 'GETSTATICURL' }), args: [this.to.toAst()] }); } } if (newNode) { uglifyAst.replaceDescendantNode(this.parentNode, this.node, newNode); this.node = newNode; } this.from.markDirty(); return this; }, attach: function () { throw new Error('Not implemented'); }, detach: function () { throw new Error('Not implemented'); } }); module.exports = JavaScriptGetStaticUrl;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Description of a NotificationHub ApnsCredential. * */ class ApnsCredential { /** * Create a ApnsCredential. * @member {string} [apnsCertificate] The APNS certificate. * @member {string} [certificateKey] The certificate key. * @member {string} [endpoint] The endpoint of this credential. * @member {string} [thumbprint] The Apns certificate Thumbprint * @member {string} [keyId] A 10-character key identifier (kid) key, obtained * from your developer account * @member {string} [appName] The name of the application * @member {string} [appId] The issuer (iss) registered claim key, whose * value is your 10-character Team ID, obtained from your developer account * @member {string} [token] Provider Authentication Token, obtained through * your developer account */ constructor() { } /** * Defines the metadata of ApnsCredential * * @returns {object} metadata of ApnsCredential * */ mapper() { return { required: false, serializedName: 'ApnsCredential', type: { name: 'Composite', className: 'ApnsCredential', modelProperties: { apnsCertificate: { required: false, serializedName: 'properties.apnsCertificate', type: { name: 'String' } }, certificateKey: { required: false, serializedName: 'properties.certificateKey', type: { name: 'String' } }, endpoint: { required: false, serializedName: 'properties.endpoint', type: { name: 'String' } }, thumbprint: { required: false, serializedName: 'properties.thumbprint', type: { name: 'String' } }, keyId: { required: false, serializedName: 'properties.keyId', type: { name: 'String' } }, appName: { required: false, serializedName: 'properties.appName', type: { name: 'String' } }, appId: { required: false, serializedName: 'properties.appId', type: { name: 'String' } }, token: { required: false, serializedName: 'properties.token', type: { name: 'String' } } } } }; } } module.exports = ApnsCredential;
//! moment.js locale configuration //! locale : Swedish [sv] //! author : Jens Alm : https://github.com/ulmus import moment from '../moment'; export default moment.defineLocale('sv', { months : 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'), monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), weekdays : 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), weekdaysShort : 'sön_mån_tis_ons_tor_fre_lör'.split('_'), weekdaysMin : 'sö_må_ti_on_to_fr_lö'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY-MM-DD', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [kl.] HH:mm', LLLL : 'dddd D MMMM YYYY [kl.] HH:mm', lll : 'D MMM YYYY HH:mm', llll : 'ddd D MMM YYYY HH:mm' }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: '[På] dddd LT', lastWeek: '[I] dddd[s] LT', sameElse: 'L' }, relativeTime : { future : 'om %s', past : 'för %s sedan', s : 'några sekunder', m : 'en minut', mm : '%d minuter', h : 'en timme', hh : '%d timmar', d : 'en dag', dd : '%d dagar', M : 'en månad', MM : '%d månader', y : 'ett år', yy : '%d år' }, ordinalParse: /\d{1,2}(e|a)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
var urls = require("../../urls"); var url = require("url"); var path = require("path"); var fs = require("fs"); var Immutable = require("immutable"); const PLUGIN_NAME = "Connections"; /** * Use heart-beated data to decorate clients * @param clients * @param clientsInfo * @returns {*} */ function decorateClients(clients, clientsInfo) { return clients.map(function (item) { clientsInfo.forEach(function (client) { if (client.id === item.id) { item.data = client.data; return false; } }); return item; }); } /** * @param socket * @param connectedClients */ function sendUpdated(socket, connectedClients) { socket.emit("cp:connections:update", connectedClients); } /** * @type {{plugin: Function, plugin:name: string, markup: string}} */ module.exports = { /** * @param cp * @param bs */ "plugin": function (cp, bs) { var uaParser = new bs.utils.UAParser(); var currentConnections = []; cp.clients.on("connection", function (client) { client.on("client:heartbeat", function (data) { var match; if (currentConnections.some(function (item, index) { if (item.id === client.id) { match = index; return true; } return false; })) { if (typeof match === "number") { currentConnections[match].timestamp = new Date().getTime(); currentConnections[match].data = data; } } else { currentConnections.push({ id: client.id, timestamp: new Date().getTime(), browser: uaParser.setUA(client.handshake.headers["user-agent"]).getBrowser(), data: data }); } }); }); cp.socket.on("connection", function (client) { client.on("cp:highlight", highlightClient.bind(null, cp.clients)); client.on("cp:get:clients", function () { client.emit("cp:receive:clients", registry || []); }); }); var registry; var temp; var count = 0; var initialSent; setInterval(function () { if (cp.clients.sockets.length) { temp = Immutable.List(cp.clients.sockets.map(function (client) { return Immutable.fromJS({ id: client.id, browser: uaParser.setUA(client.handshake.headers["user-agent"]).getBrowser() }); })); if (!registry) { registry = temp; sendUpdated(cp.socket, decorateClients(registry.toJS(), currentConnections)); } else { if (Immutable.is(registry, temp)) { if (!initialSent) { sendUpdated(cp.socket, decorateClients(registry.toJS(), currentConnections)); initialSent = true; } } else { registry = temp; sendUpdated(cp.socket, decorateClients(registry.toJS(), currentConnections)); } } } else { sendUpdated(cp.socket, []); } }, 1000); }, /** * Hooks */ "hooks": { //"markup": fs.readFileSync(path.join(__dirname, "connections.html")), "client:js": require("fs").readFileSync(__dirname + "/connections.client.js"), "templates": [ path.join(__dirname, "/connections.directive.html") ] //"page": { // path: "/connections", // title: PLUGIN_NAME, // template: "connections.html", // controller: PLUGIN_NAME + "Controller", // order: 3, // icon: "devices" //} }, /** * Plugin name */ "plugin:name": PLUGIN_NAME }; /** * @param clients * @param data */ function highlightClient (clients, data) { var socket; if (socket = getClientById(clients, data.id)) { socket.emit("highlight"); } } /** * @param clients * @param id */ function getClientById (clients, id) { var match; clients.sockets.some(function (item, i) { if (item.id === id) { match = clients.sockets[i]; return true; } }); return match; }
// import * as actions from '../examples/actions'; // import Component from '../components/component.react'; // import DocumentTitle from 'react-document-title'; // import Editable from '../components/editable.react'; // import React from 'react'; // import immutable from 'immutable'; // import {msg} from '../intl/store'; // export default class Index extends Component { // static propTypes = { // examples: React.PropTypes.instanceOf(immutable.Map).isRequired, // pendingActions: React.PropTypes.instanceOf(immutable.Map).isRequired // }; // render() { // const {examples, pendingActions} = this.props; // const editableState = examples.getIn(['editable', 'state']); // const editableText = examples.getIn(['editable', 'text']); // const editableFor = (id, name) => // <Editable // disabled={pendingActions.has(actions.onEditableSave.toString())} // id={id} // name={name} // onSave={actions.onEditableSave} // onState={actions.onEditableState} // showEditButtons // showViewButtons // state={editableState} // text={editableText} // type="textarea" // />; // return ( // <DocumentTitle title={msg('pages.examples.title')}> // <div className="examples-page"> // <h2>editable.react.js</h2> // {editableFor(1, 'example')} // </div> // </DocumentTitle> // ); // } // }
var net = require('net'); var util = require('util'); var EventEmitter = require('events').EventEmitter; var shared = require('../shared/tcp'); // Client Transport's data handling function, bound to the TcpTransport // instance when attached to the data event handler function onDataCallback(message) { if(message && this.requests[message.id]) { var request = this.requests[message.id]; delete this.requests[message.id]; request.callback(message); } } var onClose; // At the interval specified by the user, attempt to reestablish the // connection var connect = function connect(toReconnect) { this.logger('onClose.reconnect - old con is: ' + (this.con && this.con.random)); var oldPort = this.con && this.con.random; // Set the connection reference to the new connection if (this.con) { this.logger('ERRORRORO connection should not be set'); this.con.destroy(); this.con = null; } this.con = net.connect(this.tcpConfig, function() { this.logger('net.connect.callback - new con: ' + (this.con && this.con.random) + '. old con: ' + oldPort); // Clear the reconnect interval if successfully reconnected if(this.reconnectInterval) { clearInterval(this.reconnectInterval); delete this.reconnectInterval; } if(this.stopBufferingAfter) { clearTimeout(this.stopBufferingTimeout); delete this.stopBufferingTimeout; } if (this._request) { this.request = this._request; delete this._request; } this.retry = 0; this.reconnect++; if(toReconnect) { // Get the list of all pending requests, place them in a private // variable, and reset the requests object var oldReqs = this.requests; this.requests = {}; // Then requeue the old requests, but only after a run through the // implicit event loop. Why? Because ``this.con`` won't be the // correct connection object until *after* this callback function // is called. process.nextTick(function() { Object.keys(oldReqs).forEach(function(key) { this.request(oldReqs[key].body, oldReqs[key].callback); }.bind(this)); }.bind(this)); } }.bind(this)); this.con.random = Math.random(); this.logger('new.con.created - con: ' + (this.con && this.con.random)); // Reconnect the data and end event handlers to the new connection object this.con.on('data', shared.createDataHandler(this, onDataCallback.bind(this))); this.con.on('end', function() { this.logger('con.end - ' + (this.con && this.con.random)); this.con.destroy(); }.bind(this)); this.con.on('error', function() { this.logger('con.error - ' + (this.con && this.con.random)); this.con.destroy(); }.bind(this)); this.con.on('close', function () { this.logger('con.close - ' + (this.con && this.con.random)); if(this.con) { this.con.destroy(); this.con = null; onClose.call(this); } }.bind(this)); }; // The handler for a connection close. Will try to reconnect if configured // to do so and it hasn't tried "too much," otherwise mark the connection // dead. onClose = function onClose() { this.logger('onClose ' + (this.con && this.con.random)); // Attempting to reconnect if(this.retries && this.retry < this.retries && this.reconnect < this.reconnects) { this.logger('onClose if (retries) - old con is: ' + (this.con && this.con.random)); this.emit('retry'); // When reconnecting, all previous buffered data is invalid, so wipe // it out, and then increment the retry flag this.retry++; // If this is the first try, attempt to reconnect immediately if(this.retry === 1) { this.logger('call onClose.reconnect for retry === 1 - old con: ' + (this.con && this.con.random)); connect.call(this, true); } if(typeof(this.stopBufferingAfter) === 'number' && this.stopBufferingAfter !== 0 && !this.stopBufferingTimeout) { this.stopBufferingTimeout = setTimeout(this.stopBuffering.bind(this), this.stopBufferingAfter); } if(!this.reconnectInterval) { this.reconnectInterval = setInterval(function() { this.logger('call onClose.reconnect from reconnectInterval - old con: ' + (this.con && this.con.random)); connect.call(this, true); }.bind(this), this.retryInterval); } } else { // Too many tries, or not allowed to retry, mark the connection as dead this.emit('end'); this.con = undefined; } }; // The Client TcpTransport constructor function function TcpTransport(tcpConfig, config) { // Shim to support old-style call if (typeof tcpConfig === 'string') { tcpConfig = { host: arguments[0], port: arguments[1] }; config = arguments[2]; } // Initialize the Node EventEmitter on this EventEmitter.call(this); // Attach the config object (or an empty object if not defined, as well // as the server and port config = config || {}; this.retries = config.retries || Infinity; this.reconnects = config.reconnects || Infinity; this.reconnectClearInterval = config.reconnectClearInterval || 0; this.retry = 0; this.reconnect = -1; this.retryInterval = config.retryInterval || 250; this.stopBufferingAfter = config.stopBufferingAfter || 0; this.stopBufferingTimeout = null; this.reconnectInterval = null; this.logger = config.logger || function() {}; // Set up the server connection and request-handling properties this.tcpConfig = tcpConfig; this.requests = {}; // Set up the garbage collector for requests that never receive a response // and build the buffer this.timeout = config.timeout || 30*1000; this.sweepIntervalMs = config.sweepIntervalMs || 1*1000; this.sweepInterval = setInterval(this.sweep.bind(this), this.sweepIntervalMs); if (this.reconnectClearInterval > 0 && this.reconnectClearInterval !== Infinity) { this.reconnectClearTimer = setInterval(this.clearReconnects.bind(this), this.reconnectClearInterval); } connect.call(this, false); return this; } // Attach the EventEmitter prototype as the TcpTransport's prototype's prototype util.inherits(TcpTransport, EventEmitter); TcpTransport.prototype.stopBuffering = function stopBuffering() { this.logger('Stopping the buffering of requests on ' + (this.con && this.con.random)); this._request = this.request; this.request = function fakeRequest(body, callback) { callback({ error: 'Connection Unavailable' }); }; }; // The request logic is relatively straightforward, given the request // body and callback function, register the request with the requests // object, then if there is a valid connection at the moment, send the // request to the server with a null terminator attached. This ordering // guarantees that requests called during a connection issue won't be // lost while a connection is re-established. TcpTransport.prototype.request = function request(body, callback) { this.requests[body.id] = { callback: callback, body: body, timestamp: Date.now() }; if(this.con) this.con.write(shared.formatMessage(body, this)); }; // The sweep function looks at the timestamps for each request, and any // request that is longer lived than the timeout (default 2 min) will be // culled and assumed lost. TcpTransport.prototype.sweep = function sweep() { var now = new Date().getTime(); var cannedRequests = {}; for(var key in this.requests) { if(this.requests[key].timestamp && this.requests[key].timestamp + this.timeout < now) { this.requests[key].callback({ error: 'Request Timed Out' }); cannedRequests[key] = this.requests[key]; delete this.requests[key]; } } this.emit('sweep', cannedRequests); }; // The clearReconnects function periodically resets the internal counter // of how many times we have re-established a connection to the server. // If the connection is currently dead (undefined), it attempts a reconnect. TcpTransport.prototype.clearReconnects = function clearReconnects() { this.reconnect = -1; if (this.con === undefined) { connect.call(this, true); } }; // When shutting down the client connection, the sweep is turned off, the // requests are removed, the number of allowed retries is set to zero, the // connection is ended, and a callback, if any, is called. TcpTransport.prototype.shutdown = function shutdown(done) { clearInterval(this.sweepInterval); if(this.reconnectInterval) clearInterval(this.reconnectInterval); if(this.reconnectClearTimer) clearInterval(this.reconnectClearTimer); this.requests = {}; this.retries = 0; if(this.con) this.con.destroy(); this.emit('shutdown'); if(done instanceof Function) done(); }; // Export the client TcpTransport module.exports = TcpTransport;
/*global defineSuite*/ defineSuite([ 'Core/GeometryInstance', 'Core/BoundingSphere', 'Core/Cartesian3', 'Core/ComponentDatatype', 'Core/Geometry', 'Core/GeometryAttribute', 'Core/GeometryInstanceAttribute', 'Core/Matrix4', 'Core/PrimitiveType' ], function( GeometryInstance, BoundingSphere, Cartesian3, ComponentDatatype, Geometry, GeometryAttribute, GeometryInstanceAttribute, Matrix4, PrimitiveType) { 'use strict'; it('constructor', function() { var geometry = new Geometry({ attributes : { position : new GeometryAttribute({ componentDatatype : ComponentDatatype.DOUBLE, componentsPerAttribute : 3, values : new Float64Array([ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0 ]) }) }, indices : new Uint16Array([0, 1, 2]), primitiveType : PrimitiveType.TRIANGLES, boundingSphere : new BoundingSphere(new Cartesian3(0.5, 0.5, 0.0), 1.0) }); var modelMatrix = Matrix4.multiplyByTranslation(Matrix4.IDENTITY, new Cartesian3(0.0, 0.0, 9000000.0), new Matrix4()); var attributes = { color : new GeometryInstanceAttribute({ componentDatatype : ComponentDatatype.UNSIGNED_BYTE, componentsPerAttribute : 4, normalize : true, value : new Uint8Array([255, 255, 0, 255]) }) }; var instance = new GeometryInstance({ geometry : geometry, modelMatrix : modelMatrix, id : 'geometry', attributes : attributes }); expect(instance.geometry).toBe(geometry); expect(instance.modelMatrix).toEqual(modelMatrix); expect(instance.id).toEqual('geometry'); expect(attributes).toBe(attributes); }); it('constructor throws without geometry', function() { expect(function() { return new GeometryInstance(); }).toThrowDeveloperError(); }); });
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.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. ****************************************************************************/ /** * Base class for ccs.ComRender * @class * @extends ccs.Component */ ccs.ComRender = ccs.Component.extend(/** @lends ccs.ComRender# */{ _render: null, ctor: function (node, comName) { cc.Component.prototype.ctor.call(this); this._render = node; this._name = comName; }, onEnter: function () { if (this._owner) { this._owner.addChild(this._render); } }, onExit: function () { if (this._owner) { this._owner.removeChild(this._render, true); this._render = null; } }, /** * Node getter * @returns {cc.Node} */ getNode: function () { return this._render; }, /** * Node setter * @param {cc.Node} node */ setNode: function (node) { this._render = node; } }); /** * allocates and initializes a ComRender. * @constructs * @return {ccs.ComRender} * @example * // example * var com = ccs.ComRender.create(); */ ccs.ComRender.create = function (node, comName) { var com = new ccs.ComRender(node, comName); if (com && com.init()) { return com; } return null; };
'use strict'; // Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'production'; process.env.NODE_ENV = 'production'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', err => { throw err; }); // Ensure environment variables are read. require('../config/env'); const chalk = require('chalk'); const fs = require('fs-extra'); const webpack = require('webpack'); const config = require('../config/webpack.config.prod'); const paths = require('../config/paths'); const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); const printBuildError = require('react-dev-utils/printBuildError'); const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild; const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; // These sizes are pretty large. We'll warn for bundles exceeding them. const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appLibIndexJs])) { process.exit(1); } // First, read the current file sizes in lib directory. // This lets us display how much they changed later. measureFileSizesBeforeBuild(paths.appBuild) .then(previousFileSizes => { // Remove all content but keep the directory so that // if you're in it, you don't end up in Trash fs.emptyDirSync(paths.appBuild); // Start the webpack build return build(previousFileSizes); }) .then( ({ stats, previousFileSizes, warnings }) => { if (warnings.length) { console.log(chalk.yellow('Compiled with warnings.\n')); console.log(warnings.join('\n\n')); console.log( '\nSearch for the ' + chalk.underline(chalk.yellow('keywords')) + ' to learn more about each warning.' ); console.log( 'To ignore, add ' + chalk.cyan('// eslint-disable-next-line') + ' to the line before.\n' ); } else { console.log(chalk.green('Compiled successfully.\n')); } console.log('File sizes after gzip:\n'); printFileSizesAfterBuild( stats, previousFileSizes, paths.appBuild, WARN_AFTER_BUNDLE_GZIP_SIZE, WARN_AFTER_CHUNK_GZIP_SIZE ); console.log(); }, err => { console.log(chalk.red('Failed to compile.\n')); printBuildError(err); process.exit(1); } ); // Create the production build and print the deployment instructions. function build(previousFileSizes) { console.log('Creating an optimized production build...'); let compiler = webpack(config); return new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err) { return reject(err); } const messages = formatWebpackMessages(stats.toJson({}, true)); if (messages.errors.length) { // Only keep the first error. Others are often indicative // of the same problem, but confuse the reader with noise. if (messages.errors.length > 1) { messages.errors.length = 1; } return reject(new Error(messages.errors.join('\n\n'))); } if ( process.env.CI && (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') && messages.warnings.length ) { console.log( chalk.yellow( '\nTreating warnings as errors because process.env.CI = true.\n' + 'Most CI servers set it automatically.\n' ) ); return reject(new Error(messages.warnings.join('\n\n'))); } return resolve({ stats, previousFileSizes, warnings: messages.warnings, }); }); }); }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.9.4.1_A1_T3; * @section: 15.9.4.1; * @assertion: The Date property "prototype" has { DontEnum, DontDelete, ReadOnly } attributes; * @description: Checking DontEnum attribute; */ if (Date.propertyIsEnumerable('prototype')) { $ERROR('#1: The Date.prototype property has the attribute DontEnum'); } for(x in Date) { if(x === "prototype") { $ERROR('#2: The Date.prototype has the attribute DontEnum'); } }
require([ 'gridx/Grid', 'gridx/core/model/cache/Async', 'gridx/modules/RowLock', 'gridx/modules/RowHeader', // 'gridx/tests/support/data/MusicData', 'gridx/tests/support/data/TestData', 'gridx/tests/support/stores/ItemFileWriteStore', // 'gridx/tests/support/stores/JsonRest', 'gridx/tests/support/TestPane', 'dijit/form/NumberSpinner' ], function(Grid, Cache, RowLock, RowHeader, dataSource, storeFactory, TestPane){ grid = new Grid({ id: 'grid', cacheClass: Cache, store: storeFactory({ path: './support/stores', dataSource: dataSource, size: 100 }), rowLockCount: 2, structure: dataSource.layouts[0], modules: [RowLock, RowHeader] }); grid.placeAt('gridContainer'); grid.startup(); //Test buttons var tp = new TestPane({}); tp.placeAt('ctrlPane'); tp.addTestSet('Lock/Unlock Rows', [ '<label for="integerspinner">Rows to lock:</label><input id="integerspinner1" data-dojo-type="dijit.form.NumberSpinner" data-dojo-props="constraints:{max:10,min: 1},name:\'integerspinner1\', value: 1"/>', '<div data-dojo-type="dijit.form.Button" data-dojo-props="onClick: lockRows">Lock Rows</div>', '<div data-dojo-type="dijit.form.Button" data-dojo-props="onClick: unlockRows">Unlock</div>' ].join('')); tp.startup(); }); function lockRows(){ var c = dijit.byId('integerspinner1').get('value'); grid.rowLock.lock(c); } function unlockRows(){ grid.rowLock.unlock(); }
import Ember from 'ember'; import GoogleArrayMixin from 'ember-google-map/mixins/google-array'; import helpers from 'ember-google-map/core/helpers'; var computed = Ember.computed; /** * @class GoogleMapPolylinePathController * @extends Ember.ArrayController */ export default Ember.ArrayController.extend(GoogleArrayMixin, { model: computed.alias('parentController.path'), googleItemFactory: helpers._latLngToGoogle, emberItemFactory: function (googleLatLng) { return Ember.Object.create(helpers._latLngFromGoogle(googleLatLng)); }, observeEmberProperties: ['lat', 'lng'] });
version https://git-lfs.github.com/spec/v1 oid sha256:6a3349ea92d42c45ab6b3c4609eb49e26176ac1643c00933213096dfc4086ebd size 856
/** @license * @pnp/odata v1.1.5-5 - pnp - provides shared odata functionality and base classes * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { RuntimeConfig, dateAdd, PnPClientStorage, isFunc, hOP, extend, combine, mergeOptions, objectDefinedNotNull, getGUID } from '@pnp/common'; import { __decorate } from 'tslib'; import { Logger } from '@pnp/logging'; class CachingOptions { constructor(key) { this.key = key; this.expiration = dateAdd(new Date(), "second", RuntimeConfig.defaultCachingTimeoutSeconds); this.storeName = RuntimeConfig.defaultCachingStore; } get store() { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } } } CachingOptions.storage = new PnPClientStorage(); class CachingParserWrapper { constructor(parser, cacheOptions) { this.parser = parser; this.cacheOptions = cacheOptions; } parse(response) { return this.parser.parse(response).then(r => this.cacheData(r)); } cacheData(data) { if (this.cacheOptions.store !== null) { this.cacheOptions.store.put(this.cacheOptions.key, data, this.cacheOptions.expiration); } return data; } } class ODataParserBase { parse(r) { return new Promise((resolve, reject) => { if (this.handleError(r, reject)) { this.parseImpl(r, resolve, reject); } }); } parseImpl(r, resolve, reject) { if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) { resolve({}); } else { // patch to handle cases of 200 response with no or whitespace only bodies (#487 & #545) r.text() .then(txt => txt.replace(/\s/ig, "").length > 0 ? JSON.parse(txt) : {}) .then(json => resolve(this.parseODataJSON(json))) .catch(e => reject(e)); } } /** * Handles a response with ok === false by parsing the body and creating a ProcessHttpClientResponseException * which is passed to the reject delegate. This method returns true if there is no error, otherwise false * * @param r Current response object * @param reject reject delegate for the surrounding promise */ handleError(r, reject) { if (!r.ok) { // read the response as text, it may not be valid json r.json().then(json => { // include the headers as they contain diagnostic information const data = { responseBody: json, responseHeaders: r.headers, }; reject(new Error(`Error making HttpClient request in queryable: [${r.status}] ${r.statusText} ::> ${JSON.stringify(data)}`)); }).catch(e => { reject(new Error(`Error making HttpClient request in queryable: [${r.status}] ${r.statusText} ::> ${e}`)); }); } return r.ok; } /** * Normalizes the json response by removing the various nested levels * * @param json json object to parse */ parseODataJSON(json) { let result = json; if (hOP(json, "d")) { if (hOP(json.d, "results")) { result = json.d.results; } else { result = json.d; } } else if (hOP(json, "value")) { result = json.value; } return result; } } class ODataDefaultParser extends ODataParserBase { } class TextParser extends ODataParserBase { parseImpl(r, resolve) { r.text().then(resolve); } } class BlobParser extends ODataParserBase { parseImpl(r, resolve) { r.blob().then(resolve); } } class JSONParser extends ODataParserBase { parseImpl(r, resolve) { r.json().then(resolve); } } class BufferParser extends ODataParserBase { parseImpl(r, resolve) { if (isFunc(r.arrayBuffer)) { r.arrayBuffer().then(resolve); } else { r.buffer().then(resolve); } } } class LambdaParser { constructor(parser) { this.parser = parser; } parse(r) { return this.parser(r); } } /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { Logger.log({ data: Logger.activeLogLevel === 0 /* Verbose */ ? context.result : {}, level: 1 /* Info */, message: `[${context.requestId}] (${(new Date()).getTime()}) Returning result from pipeline. Set logging to verbose to see data.`, }); return Promise.resolve(context.result || null); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise((resolve) => { context.result = value; context.hasResult = true; resolve(context); }); } /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { if (c.pipeline.length > 0) { return c.pipeline.shift()(c); } else { return Promise.resolve(c); } } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { if (context.pipeline.length < 1) { Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Request pipeline contains no methods!`, 2 /* Warning */); } const promise = next(context).then(ctx => returnResult(ctx)).catch((e) => { Logger.error(e); throw e; }); if (context.isBatched) { // this will block the batch's execute method from returning until the child requets have been resolved context.batch.addResolveBatchDependency(promise); } return promise; } /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun = false) { return (target, propertyKey, descriptor) => { const method = descriptor.value; descriptor.value = function (...args) { // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && hOP(args[0], "hasResult") && args[0].hasResult) { Logger.write(`[${args[0].requestId}] (${(new Date()).getTime()}) Skipping request pipeline method ${propertyKey}, existing result in pipeline.`, 0 /* Verbose */); return Promise.resolve(args[0]); } // apply the tagged method Logger.write(`[${args[0].requestId}] (${(new Date()).getTime()}) Calling request pipeline method ${propertyKey}.`, 0 /* Verbose */); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then((ctx) => next(ctx)); }; }; } /** * Contains the methods used within the request pipeline */ class PipelineMethods { /** * Logs the start of the request */ static logStart(context) { return new Promise(resolve => { Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: `[${context.requestId}] (${(new Date()).getTime()}) Beginning ${context.verb} request (${context.requestAbsoluteUrl})`, }); resolve(context); }); } /** * Handles caching of the request */ static caching(context) { return new Promise(resolve => { // handle caching, if applicable if (context.isCached) { Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Caching is enabled for request, checking cache...`, 1 /* Info */); let cacheOptions = new CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (context.cachingOptions !== undefined) { cacheOptions = extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return let data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any held batch dependency we are resolving from the cache Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : data, level: 1 /* Info */, message: `[${context.requestId}] (${(new Date()).getTime()}) Value returned from cache.`, }); if (isFunc(context.batchDependency)) { context.batchDependency(); } // handle the case where a parser needs to take special actions with a cached result if (hOP(context.parser, "hydrate")) { data = context.parser.hydrate(data); } return setResult(context, data).then(ctx => resolve(ctx)); } } Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Value not found in cache.`, 1 /* Info */); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); } /** * Sends the request */ static send(context) { return new Promise((resolve, reject) => { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise const p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser, context.requestId); // we release the dependency here to ensure the batch does not execute until the request is added to the batch if (isFunc(context.batchDependency)) { context.batchDependency(); } Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Batching request in batch ${context.batch.batchId}.`, 1 /* Info */); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Sending request.`, 1 /* Info */); // we are not part of a batch, so proceed as normal const client = context.clientFactory(); const opts = extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(response => context.parser.parse(response)) .then(result => setResult(context, result)) .then(ctx => resolve(ctx)) .catch(e => reject(e)); } }); } /** * Logs the end of the request */ static logEnd(context) { return new Promise(resolve => { if (context.isBatched) { Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: `[${context.requestId}] (${(new Date()).getTime()}) ${context.verb} request will complete in batch ${context.batch.batchId}.`, }); } else { Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: `[${context.requestId}] (${(new Date()).getTime()}) Completing ${context.verb} request.`, }); } resolve(context); }); } } __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "caching", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "send", null); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); function getDefaultPipeline() { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ].slice(0); } class Queryable { constructor() { this._query = new Map(); this._options = {}; this._url = ""; this._parentUrl = ""; this._useCaching = false; this._cachingOptions = null; } /** * Gets the currentl url * */ toUrl() { return this._url; } /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ concat(pathPart) { this._url += pathPart; return this; } /** * Provides access to the query builder for this url * */ get query() { return this._query; } /** * Sets custom options for current object and all derived objects accessible via chaining * * @param options custom options */ configure(options) { mergeOptions(this._options, options); return this; } /** * Configures this instance from the configure options of the supplied instance * * @param o Instance from which options should be taken */ configureFrom(o) { mergeOptions(this._options, o._options); return this; } /** * Enables caching for this request * * @param options Defines the options used when caching this request */ usingCaching(options) { if (!RuntimeConfig.globalCacheDisable) { this._useCaching = true; if (options !== undefined) { this._cachingOptions = options; } } return this; } getCore(parser = new JSONParser(), options = {}) { return this.toRequestContext("GET", options, parser, getDefaultPipeline()).then(context => pipe(context)); } postCore(options = {}, parser = new JSONParser()) { return this.toRequestContext("POST", options, parser, getDefaultPipeline()).then(context => pipe(context)); } patchCore(options = {}, parser = new JSONParser()) { return this.toRequestContext("PATCH", options, parser, getDefaultPipeline()).then(context => pipe(context)); } deleteCore(options = {}, parser = new JSONParser()) { return this.toRequestContext("DELETE", options, parser, getDefaultPipeline()).then(context => pipe(context)); } putCore(options = {}, parser = new JSONParser()) { return this.toRequestContext("PUT", options, parser, getDefaultPipeline()).then(context => pipe(context)); } /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ append(pathPart) { this._url = combine(this._url, pathPart); } /** * Gets the parent url used when creating this instance * */ get parentUrl() { return this._parentUrl; } /** * Extends this queryable from the provided parent * * @param parent Parent queryable from which we will derive a base url * @param path Additional path */ extend(parent, path) { this._parentUrl = parent._url; this._url = combine(this._parentUrl, path); this.configureFrom(parent); } } class ODataQueryable extends Queryable { constructor() { super(); this._batch = null; } /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ inBatch(batch) { if (this.batch !== null) { throw new Error("This query is already part of a batch."); } this._batch = batch; return this; } /** * Gets the currentl url * */ toUrl() { return this._url; } /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ get(parser = new ODataDefaultParser(), options = {}) { return this.getCore(parser, options); } getCore(parser = new ODataDefaultParser(), options = {}) { return this.toRequestContext("GET", options, parser, getDefaultPipeline()).then(context => pipe(context)); } postCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("POST", options, parser, getDefaultPipeline()).then(context => pipe(context)); } patchCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("PATCH", options, parser, getDefaultPipeline()).then(context => pipe(context)); } deleteCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("DELETE", options, parser, getDefaultPipeline()).then(context => pipe(context)); } putCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("PUT", options, parser, getDefaultPipeline()).then(context => pipe(context)); } /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ addBatchDependency() { if (this._batch !== null) { return this._batch.addDependency(); } return () => null; } /** * Indicates if the current query has a batch associated * */ get hasBatch() { return objectDefinedNotNull(this._batch); } /** * The batch currently associated with this query or null * */ get batch() { return this.hasBatch ? this._batch : null; } } class ODataBatch { constructor(_batchId = getGUID()) { this._batchId = _batchId; this._reqs = []; this._deps = []; this._rDeps = []; } get batchId() { return this._batchId; } /** * The requests contained in this batch */ get requests() { return this._reqs; } /** * * @param url Request url * @param method Request method (GET, POST, etc) * @param options Any request options * @param parser The parser used to handle the eventual return from the query * @param id An identifier used to track a request within a batch */ add(url, method, options, parser, id) { const info = { id, method: method.toUpperCase(), options, parser, reject: null, resolve: null, url, }; const p = new Promise((resolve, reject) => { info.resolve = resolve; info.reject = reject; }); this._reqs.push(info); return p; } /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ addDependency() { let resolver = () => void (0); this._deps.push(new Promise((resolve) => { resolver = resolve; })); return resolver; } /** * The batch's execute method will not resolve util any promises added here resolve * * @param p The dependent promise */ addResolveBatchDependency(p) { this._rDeps.push(p); } /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ execute() { // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added during the first set resolving return Promise.all(this._deps) .then(() => Promise.all(this._deps)) .then(() => this.executeImpl()) .then(() => Promise.all(this._rDeps)) .then(() => void (0)); } } export { CachingOptions, CachingParserWrapper, ODataParserBase, ODataDefaultParser, TextParser, BlobParser, JSONParser, BufferParser, LambdaParser, setResult, pipe, requestPipelineMethod, PipelineMethods, getDefaultPipeline, Queryable, ODataQueryable, ODataBatch }; //# sourceMappingURL=odata.js.map
const globalSetup = require("../global-setup"); const app = globalSetup.app; describe("Clock module", function () { this.timeout(20000); describe("with default 24hr clock config", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_24hr.js"; }); beforeEach(function (done) { app.start().then(function() { done(); } ); }); afterEach(function (done) { app.stop().then(function() { done(); }); }); it("shows date with correct format", function () { const dateRegex = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?:January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4}$/; return app.client.waitUntilWindowLoaded() .getText(".clock .date").should.eventually.match(dateRegex); }); it("shows time in 24hr format", function() { const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/ return app.client.waitUntilWindowLoaded() .getText(".clock .time").should.eventually.match(timeRegex); }); }); describe("with default 12hr clock config", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_12hr.js"; }); beforeEach(function (done) { app.start().then(function() { done(); } ); }); afterEach(function (done) { app.stop().then(function() { done(); }); }); it("shows date with correct format", function () { const dateRegex = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?:January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4}$/; return app.client.waitUntilWindowLoaded() .getText(".clock .date").should.eventually.match(dateRegex); }); it("shows time in 12hr format", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[ap]m$/; return app.client.waitUntilWindowLoaded() .getText(".clock .time").should.eventually.match(timeRegex); }); }); describe("with showPeriodUpper config enabled", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_showPeriodUpper.js"; }); beforeEach(function (done) { app.start().then(function() { done(); } ); }); afterEach(function (done) { app.stop().then(function() { done(); }); }); it("shows 12hr time with upper case AM/PM", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[AP]M$/; return app.client.waitUntilWindowLoaded() .getText(".clock .time").should.eventually.match(timeRegex); }); }); describe("with displaySeconds config disabled", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_displaySeconds_false.js"; }); beforeEach(function (done) { app.start().then(function() { done(); } ); }); afterEach(function (done) { app.stop().then(function() { done(); }); }); it("shows 12hr time without seconds am/pm", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[ap]m$/; return app.client.waitUntilWindowLoaded() .getText(".clock .time").should.eventually.match(timeRegex); }); }); describe("with showWeek config enabled", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_showWeek.js"; }); beforeEach(function (done) { app.start().then(function() { done(); } ); }); afterEach(function (done) { app.stop().then(function() { done(); }); }); it("shows week with correct format", function() { const weekRegex = /^Week [0-9]{1,2}$/; return app.client.waitUntilWindowLoaded() .getText(".clock .week").should.eventually.match(weekRegex); }); it("shows week with correct number of week of year", function() { it("FIXME: if the day is a sunday this not match"); // const currentWeekNumber = require("current-week-number")(); // const weekToShow = "Week " + currentWeekNumber; // return app.client.waitUntilWindowLoaded() // .getText(".clock .week").should.eventually.equal(weekToShow); }); }); });
/* * Coroutine with initial bound function. */ /*=== mythread starting object mythis ["FOO","BAR","foo"] 1 2 3 undefined ===*/ function test() { function mythread(a,b,c) { print('mythread starting'); print(typeof this, this); print(JSON.stringify([a,b,c])); Duktape.Thread.yield(1); Duktape.Thread.yield(2); Duktape.Thread.yield(3); } var T = new Duktape.Thread(mythread.bind('mythis', 'FOO', 'BAR')); // Only one argument can be given for the initial call, but the bound // arguments are still prepended as normal. print(Duktape.Thread.resume(T, 'foo')); // No difference in further resumes. print(Duktape.Thread.resume(T, 'foo')); print(Duktape.Thread.resume(T, 'foo')); print(Duktape.Thread.resume(T, 'foo')); } try { test(); } catch (e) { print(e.stack || e); }
QUnit.test( "Binding", function( assert ){ assert.expect(10); Q.innerHTML = '<div class="slider"></div>'; var sliders = Q.querySelectorAll('.slider'), slider = sliders[0]; noUiSlider.create(slider, { start: [ 2, 5 ], range: { 'min': 0, 'max': 10 } }); var count = 0; // Fires on bind, for every handle (2+2) slider.noUiSlider.on('update', function( values, handle ){ assert.deepEqual(values, ['2.00', '5.00']); assert.ok(count++ === handle); }); slider.noUiSlider.off('update'); count = 0; slider.noUiSlider.on('set', function( values, handle ){ assert.deepEqual(values, ['1.00', '6.00']); assert.ok(count++ === handle); }); // Setting a value triggers 'set' for each handle (2+2) slider.noUiSlider.set([1,6]); slider.noUiSlider.off('set'); // Run set again, 'set' shouldn't fire now. slider.noUiSlider.set([1,9]); count = 0; // Fires once on click (1) slider.noUiSlider.on('set.namespace', function( values, handle ){ assert.ok(true); }); // Fires once on click (1) slider.noUiSlider.on('change.namespace', function( values, handle ){ assert.ok(true); }); document.body.addEventListener('mousedown', function(e){ console.log(e.clientX, e.clientY); }); function offset ( el ) { var rect = el.getBoundingClientRect() return { top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft }; } simulant.fire( slider.querySelectorAll('.noUi-origin')[1], 'mousedown', { button: 1, // middle-click clientX: offset(slider).left + 100, clientY: offset(slider).top + 8 }); slider.noUiSlider.off('.namespace'); // Doesn't trigger 'set' again slider.noUiSlider.set([5, 7]); });
module.exports = 'okok'