code
stringlengths
2
1.05M
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'bidi', 'pt-br', { ltr: 'Direção do texto da esquerda para a direita', rtl: 'Direção do texto da direita para a esquerda' });
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); function preload() { game.load.image('bisley', 'assets/pics/alex-bisleys_horsy_5.png'); } var picture; function create() { game.stage.backgroundColor = '#6688ee'; picture = game.add.sprite(game.world.centerX, game.world.centerY, 'bisley'); picture.anchor.setTo(0.5, 0.5); // Here we'll create a basic timed event. This is a one-off event, it won't repeat or loop: // The first parameter is how long to wait before the event fires. In this case 4 seconds (you could pass in 4000 as the value as well.) // The next parameter is the function to call ('fadePicture') and finally the context under which that will happen. game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this); } function fadePicture() { game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); } function render() { game.debug.renderText("Time until event: " + game.time.events.duration, 32, 32); }
/// <reference path="../../observable.ts"/> /// <reference path="../../concurrency/scheduler.ts" /> (function () { var o; Rx.Observable.repeat(42, 4, Rx.Scheduler.async); Rx.Observable.repeat(42, null, Rx.Scheduler.async); Rx.Observable.repeat(42); }); //# sourceMappingURL=repeat.js.map
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v21.1.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var selectionController_1 = require("../selectionController"); var valueService_1 = require("../valueService/valueService"); var columnController_1 = require("../columnController/columnController"); var columnApi_1 = require("../columnController/columnApi"); var context_1 = require("../context/context"); var constants_1 = require("../constants"); var valueCache_1 = require("../valueService/valueCache"); var gridApi_1 = require("../gridApi"); var utils_1 = require("../utils"); var RowNode = /** @class */ (function () { function RowNode() { /** Children mapped by the pivot columns */ this.childrenMapped = {}; /** True by default - can be overridden via gridOptions.isRowSelectable(rowNode) */ this.selectable = true; /** Used by sorting service - to give deterministic sort to groups. Previously we * just id for this, however id is a string and had slower sorting compared to numbers. */ this.__objectId = RowNode.OBJECT_ID_SEQUENCE++; /** True when nodes with the same id are being removed and added as part of the same batch transaction */ this.alreadyRendered = false; this.selected = false; } RowNode.prototype.setData = function (data) { var oldData = this.data; this.data = data; this.valueCache.onDataChanged(); this.updateDataOnDetailNode(); this.checkRowSelectable(); var event = this.createDataChangedEvent(data, oldData, false); this.dispatchLocalEvent(event); }; // when we are doing master / detail, the detail node is lazy created, but then kept around. // so if we show / hide the detail, the same detail rowNode is used. so we need to keep the data // in sync, otherwise expand/collapse of the detail would still show the old values. RowNode.prototype.updateDataOnDetailNode = function () { if (this.detailNode) { this.detailNode.data = this.data; } }; RowNode.prototype.createDataChangedEvent = function (newData, oldData, update) { return { type: RowNode.EVENT_DATA_CHANGED, node: this, oldData: oldData, newData: newData, update: update }; }; RowNode.prototype.createLocalRowEvent = function (type) { return { type: type, node: this }; }; // similar to setRowData, however it is expected that the data is the same data item. this // is intended to be used with Redux type stores, where the whole data can be changed. we are // guaranteed that the data is the same entity (so grid doesn't need to worry about the id of the // underlying data changing, hence doesn't need to worry about selection). the grid, upon receiving // dataChanged event, will refresh the cells rather than rip them all out (so user can show transitions). RowNode.prototype.updateData = function (data) { var oldData = this.data; this.data = data; this.updateDataOnDetailNode(); this.checkRowSelectable(); this.updateDataOnDetailNode(); var event = this.createDataChangedEvent(data, oldData, true); this.dispatchLocalEvent(event); }; RowNode.prototype.getRowIndexString = function () { if (this.rowPinned === constants_1.Constants.PINNED_TOP) { return 't-' + this.rowIndex; } else if (this.rowPinned === constants_1.Constants.PINNED_BOTTOM) { return 'b-' + this.rowIndex; } else { return this.rowIndex.toString(); } }; RowNode.prototype.createDaemonNode = function () { var oldNode = new RowNode(); this.context.wireBean(oldNode); // just copy the id and data, this is enough for the node to be used // in the selection controller (the selection controller is the only // place where daemon nodes can live). oldNode.id = this.id; oldNode.data = this.data; oldNode.daemon = true; oldNode.selected = this.selected; oldNode.level = this.level; return oldNode; }; RowNode.prototype.setDataAndId = function (data, id) { var oldNode = utils_1._.exists(this.id) ? this.createDaemonNode() : null; var oldData = this.data; this.data = data; this.updateDataOnDetailNode(); this.setId(id); this.selectionController.syncInRowNode(this, oldNode); this.checkRowSelectable(); var event = this.createDataChangedEvent(data, oldData, false); this.dispatchLocalEvent(event); }; RowNode.prototype.checkRowSelectable = function () { var isRowSelectableFunc = this.gridOptionsWrapper.getIsRowSelectableFunc(); var shouldInvokeIsRowSelectable = isRowSelectableFunc && utils_1._.exists(this); this.setRowSelectable(shouldInvokeIsRowSelectable ? isRowSelectableFunc(this) : true); }; RowNode.prototype.setRowSelectable = function (newVal) { if (this.selectable !== newVal) { this.selectable = newVal; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_SELECTABLE_CHANGED)); } } }; RowNode.prototype.setId = function (id) { // see if user is providing the id's var getRowNodeId = this.gridOptionsWrapper.getRowNodeIdFunc(); if (getRowNodeId) { // if user is providing the id's, then we set the id only after the data has been set. // this is important for virtual pagination and viewport, where empty rows exist. if (this.data) { this.id = getRowNodeId(this.data); } else { // this can happen if user has set blank into the rowNode after the row previously // having data. this happens in virtual page row model, when data is delete and // the page is refreshed. this.id = undefined; } } else { this.id = id; } }; RowNode.prototype.isPixelInRange = function (pixel) { return pixel >= this.rowTop && pixel < (this.rowTop + this.rowHeight); }; RowNode.prototype.clearRowTop = function () { this.oldRowTop = this.rowTop; this.setRowTop(null); }; RowNode.prototype.setFirstChild = function (firstChild) { if (this.firstChild === firstChild) { return; } this.firstChild = firstChild; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_FIRST_CHILD_CHANGED)); } }; RowNode.prototype.setLastChild = function (lastChild) { if (this.lastChild === lastChild) { return; } this.lastChild = lastChild; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_LAST_CHILD_CHANGED)); } }; RowNode.prototype.setChildIndex = function (childIndex) { if (this.childIndex === childIndex) { return; } this.childIndex = childIndex; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_CHILD_INDEX_CHANGED)); } }; RowNode.prototype.setRowTop = function (rowTop) { if (this.rowTop === rowTop) { return; } this.rowTop = rowTop; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_TOP_CHANGED)); } }; RowNode.prototype.setDragging = function (dragging) { if (this.dragging === dragging) { return; } this.dragging = dragging; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_DRAGGING_CHANGED)); } }; RowNode.prototype.setAllChildrenCount = function (allChildrenCount) { if (this.allChildrenCount === allChildrenCount) { return; } this.allChildrenCount = allChildrenCount; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_ALL_CHILDREN_COUNT_CHANGED)); } }; RowNode.prototype.setRowHeight = function (rowHeight, estimated) { if (estimated === void 0) { estimated = false; } this.rowHeight = rowHeight; this.rowHeightEstimated = estimated; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_HEIGHT_CHANGED)); } }; RowNode.prototype.setRowIndex = function (rowIndex) { this.rowIndex = rowIndex; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_ROW_INDEX_CHANGED)); } }; RowNode.prototype.setUiLevel = function (uiLevel) { if (this.uiLevel === uiLevel) { return; } this.uiLevel = uiLevel; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_UI_LEVEL_CHANGED)); } }; RowNode.prototype.setExpanded = function (expanded) { if (this.expanded === expanded) { return; } this.expanded = expanded; if (this.eventService) { this.eventService.dispatchEvent(this.createLocalRowEvent(RowNode.EVENT_EXPANDED_CHANGED)); } var event = this.createGlobalRowEvent(events_1.Events.EVENT_ROW_GROUP_OPENED); this.mainEventService.dispatchEvent(event); if (this.gridOptionsWrapper.isGroupIncludeFooter()) { this.gridApi.redrawRows({ rowNodes: [this] }); } }; RowNode.prototype.createGlobalRowEvent = function (type) { var event = { type: type, node: this, data: this.data, rowIndex: this.rowIndex, rowPinned: this.rowPinned, context: this.gridOptionsWrapper.getContext(), api: this.gridOptionsWrapper.getApi(), columnApi: this.gridOptionsWrapper.getColumnApi() }; return event; }; RowNode.prototype.dispatchLocalEvent = function (event) { if (this.eventService) { this.eventService.dispatchEvent(event); } }; // we also allow editing the value via the editors. when it is done via // the editors, no 'cell changed' event gets fired, as it's assumed that // the cell knows about the change given it's in charge of the editing. // this method is for the client to call, so the cell listens for the change // event, and also flashes the cell when the change occurs. RowNode.prototype.setDataValue = function (colKey, newValue) { var column = this.columnController.getPrimaryColumn(colKey); this.valueService.setValue(this, column, newValue); this.dispatchCellChangedEvent(column, newValue); }; RowNode.prototype.setGroupValue = function (colKey, newValue) { var column = this.columnController.getGridColumn(colKey); if (utils_1._.missing(this.groupData)) { this.groupData = {}; } this.groupData[column.getColId()] = newValue; this.dispatchCellChangedEvent(column, newValue); }; // sets the data for an aggregation RowNode.prototype.setAggData = function (newAggData) { var _this = this; // find out all keys that could potentially change var colIds = utils_1._.getAllKeysInObjects([this.aggData, newAggData]); this.aggData = newAggData; // if no event service, nobody has registered for events, so no need fire event if (this.eventService) { colIds.forEach(function (colId) { var column = _this.columnController.getGridColumn(colId); var value = _this.aggData ? _this.aggData[colId] : undefined; _this.dispatchCellChangedEvent(column, value); }); } }; RowNode.prototype.hasChildren = function () { // we need to return true when this.group=true, as this is used by server side row model // (as children are lazy loaded and stored in a cache anyway). otherwise we return true // if children exist. return this.group || (this.childrenAfterGroup && this.childrenAfterGroup.length > 0); }; RowNode.prototype.isEmptyRowGroupNode = function () { return this.group && utils_1._.missingOrEmpty(this.childrenAfterGroup); }; RowNode.prototype.dispatchCellChangedEvent = function (column, newValue) { var cellChangedEvent = { type: RowNode.EVENT_CELL_CHANGED, node: this, column: column, newValue: newValue }; this.dispatchLocalEvent(cellChangedEvent); }; RowNode.prototype.resetQuickFilterAggregateText = function () { this.quickFilterAggregateText = null; }; RowNode.prototype.isExpandable = function () { return this.hasChildren() || this.master; }; RowNode.prototype.isSelected = function () { // for footers, we just return what our sibling selected state is, as cannot select a footer if (this.footer) { return this.sibling.isSelected(); } return this.selected; }; RowNode.prototype.depthFirstSearch = function (callback) { if (this.childrenAfterGroup) { this.childrenAfterGroup.forEach(function (child) { return child.depthFirstSearch(callback); }); } callback(this); }; // + rowController.updateGroupsInSelection() // + selectionController.calculatedSelectedForAllGroupNodes() RowNode.prototype.calculateSelectedFromChildren = function () { var atLeastOneSelected = false; var atLeastOneDeSelected = false; var atLeastOneMixed = false; var newSelectedValue; if (this.childrenAfterGroup) { for (var i = 0; i < this.childrenAfterGroup.length; i++) { var child = this.childrenAfterGroup[i]; // skip non-selectable nodes to prevent inconsistent selection values if (!child.selectable) { continue; } var childState = child.isSelected(); switch (childState) { case true: atLeastOneSelected = true; break; case false: atLeastOneDeSelected = true; break; default: atLeastOneMixed = true; break; } } } if (atLeastOneMixed) { newSelectedValue = undefined; } else if (atLeastOneSelected && !atLeastOneDeSelected) { newSelectedValue = true; } else if (!atLeastOneSelected && atLeastOneDeSelected) { newSelectedValue = false; } else { newSelectedValue = undefined; } this.selectThisNode(newSelectedValue); }; RowNode.prototype.setSelectedInitialValue = function (selected) { this.selected = selected; }; RowNode.prototype.setSelected = function (newValue, clearSelection, suppressFinishActions) { if (clearSelection === void 0) { clearSelection = false; } if (suppressFinishActions === void 0) { suppressFinishActions = false; } this.setSelectedParams({ newValue: newValue, clearSelection: clearSelection, suppressFinishActions: suppressFinishActions, rangeSelect: false }); }; RowNode.prototype.isRowPinned = function () { return this.rowPinned === constants_1.Constants.PINNED_TOP || this.rowPinned === constants_1.Constants.PINNED_BOTTOM; }; // to make calling code more readable, this is the same method as setSelected except it takes names parameters RowNode.prototype.setSelectedParams = function (params) { var groupSelectsChildren = this.gridOptionsWrapper.isGroupSelectsChildren(); var newValue = params.newValue === true; var clearSelection = params.clearSelection === true; var suppressFinishActions = params.suppressFinishActions === true; var rangeSelect = params.rangeSelect === true; // groupSelectsFiltered only makes sense when group selects children var groupSelectsFiltered = groupSelectsChildren && (params.groupSelectsFiltered === true); if (this.id === undefined) { console.warn('ag-Grid: cannot select node until id for node is known'); return 0; } if (this.rowPinned) { console.warn('ag-Grid: cannot select pinned rows'); return 0; } // if we are a footer, we don't do selection, just pass the info // to the sibling (the parent of the group) if (this.footer) { var count = this.sibling.setSelectedParams(params); return count; } if (rangeSelect) { var newRowClicked = this.selectionController.getLastSelectedNode() !== this; var allowMultiSelect = this.gridOptionsWrapper.isRowSelectionMulti(); if (newRowClicked && allowMultiSelect) { return this.doRowRangeSelection(); } } var updatedCount = 0; // when groupSelectsFiltered, then this node may end up intermediate despite // trying to set it to true / false. this group will be calculated further on // down when we call calculatedSelectedForAllGroupNodes(). we need to skip it // here, otherwise the updatedCount would include it. var skipThisNode = groupSelectsFiltered && this.group; if (!skipThisNode) { var thisNodeWasSelected = this.selectThisNode(newValue); if (thisNodeWasSelected) { updatedCount++; } } if (groupSelectsChildren && this.group) { updatedCount += this.selectChildNodes(newValue, groupSelectsFiltered); } // clear other nodes if not doing multi select if (!suppressFinishActions) { var clearOtherNodes = newValue && (clearSelection || !this.gridOptionsWrapper.isRowSelectionMulti()); if (clearOtherNodes) { updatedCount += this.selectionController.clearOtherNodes(this); } // only if we selected something, then update groups and fire events if (updatedCount > 0) { this.selectionController.updateGroupsFromChildrenSelections(); // this is the very end of the 'action node', so we are finished all the updates, // include any parent / child changes that this method caused var event_1 = { type: events_1.Events.EVENT_SELECTION_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.mainEventService.dispatchEvent(event_1); } // so if user next does shift-select, we know where to start the selection from if (newValue) { this.selectionController.setLastSelectedNode(this); } } return updatedCount; }; // selects all rows between this node and the last selected node (or the top if this is the first selection). // not to be mixed up with 'cell range selection' where you drag the mouse, this is row range selection, by // holding down 'shift'. RowNode.prototype.doRowRangeSelection = function () { var updatedCount = 0; var groupsSelectChildren = this.gridOptionsWrapper.isGroupSelectsChildren(); var lastSelectedNode = this.selectionController.getLastSelectedNode(); var nodesToSelect = this.rowModel.getNodesInRangeForSelection(this, lastSelectedNode); nodesToSelect.forEach(function (rowNode) { if (rowNode.group && groupsSelectChildren) { return; } var nodeWasSelected = rowNode.selectThisNode(true); if (nodeWasSelected) { updatedCount++; } }); this.selectionController.updateGroupsFromChildrenSelections(); var event = { type: events_1.Events.EVENT_SELECTION_CHANGED, api: this.gridApi, columnApi: this.columnApi }; this.mainEventService.dispatchEvent(event); return updatedCount; }; RowNode.prototype.isParentOfNode = function (potentialParent) { var parentNode = this.parent; while (parentNode) { if (parentNode === potentialParent) { return true; } parentNode = parentNode.parent; } return false; }; RowNode.prototype.selectThisNode = function (newValue) { if (!this.selectable || this.selected === newValue) { return false; } this.selected = newValue; if (this.eventService) { this.dispatchLocalEvent(this.createLocalRowEvent(RowNode.EVENT_ROW_SELECTED)); } var event = this.createGlobalRowEvent(events_1.Events.EVENT_ROW_SELECTED); this.mainEventService.dispatchEvent(event); return true; }; RowNode.prototype.selectChildNodes = function (newValue, groupSelectsFiltered) { var children = groupSelectsFiltered ? this.childrenAfterFilter : this.childrenAfterGroup; var updatedCount = 0; if (utils_1._.missing(children)) { return; } for (var i = 0; i < children.length; i++) { updatedCount += children[i].setSelectedParams({ newValue: newValue, clearSelection: false, suppressFinishActions: true, groupSelectsFiltered: groupSelectsFiltered }); } return updatedCount; }; RowNode.prototype.addEventListener = function (eventType, listener) { if (!this.eventService) { this.eventService = new eventService_1.EventService(); } this.eventService.addEventListener(eventType, listener); }; RowNode.prototype.removeEventListener = function (eventType, listener) { this.eventService.removeEventListener(eventType, listener); }; RowNode.prototype.onMouseEnter = function () { this.dispatchLocalEvent(this.createLocalRowEvent(RowNode.EVENT_MOUSE_ENTER)); }; RowNode.prototype.onMouseLeave = function () { this.dispatchLocalEvent(this.createLocalRowEvent(RowNode.EVENT_MOUSE_LEAVE)); }; RowNode.prototype.getFirstChildOfFirstChild = function (rowGroupColumn) { var currentRowNode = this; // if we are hiding groups, then if we are the first child, of the first child, // all the way up to the column we are interested in, then we show the group cell. var isCandidate = true; var foundFirstChildPath = false; var nodeToSwapIn; while (isCandidate && !foundFirstChildPath) { var parentRowNode = currentRowNode.parent; var firstChild = utils_1._.exists(parentRowNode) && currentRowNode.firstChild; if (firstChild) { if (parentRowNode.rowGroupColumn === rowGroupColumn) { foundFirstChildPath = true; nodeToSwapIn = parentRowNode; } } else { isCandidate = false; } currentRowNode = parentRowNode; } return foundFirstChildPath ? nodeToSwapIn : null; }; RowNode.OBJECT_ID_SEQUENCE = 0; RowNode.EVENT_ROW_SELECTED = 'rowSelected'; RowNode.EVENT_DATA_CHANGED = 'dataChanged'; RowNode.EVENT_CELL_CHANGED = 'cellChanged'; RowNode.EVENT_ALL_CHILDREN_COUNT_CHANGED = 'allChildrenCountChanged'; RowNode.EVENT_MOUSE_ENTER = 'mouseEnter'; RowNode.EVENT_MOUSE_LEAVE = 'mouseLeave'; RowNode.EVENT_HEIGHT_CHANGED = 'heightChanged'; RowNode.EVENT_TOP_CHANGED = 'topChanged'; RowNode.EVENT_FIRST_CHILD_CHANGED = 'firstChildChanged'; RowNode.EVENT_LAST_CHILD_CHANGED = 'lastChildChanged'; RowNode.EVENT_CHILD_INDEX_CHANGED = 'childIndexChanged'; RowNode.EVENT_ROW_INDEX_CHANGED = 'rowIndexChanged'; RowNode.EVENT_EXPANDED_CHANGED = 'expandedChanged'; RowNode.EVENT_SELECTABLE_CHANGED = 'selectableChanged'; RowNode.EVENT_UI_LEVEL_CHANGED = 'uiLevelChanged'; RowNode.EVENT_DRAGGING_CHANGED = 'draggingChanged'; __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], RowNode.prototype, "mainEventService", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], RowNode.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata("design:type", selectionController_1.SelectionController) ], RowNode.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], RowNode.prototype, "columnController", void 0); __decorate([ context_1.Autowired('valueService'), __metadata("design:type", valueService_1.ValueService) ], RowNode.prototype, "valueService", void 0); __decorate([ context_1.Autowired('rowModel'), __metadata("design:type", Object) ], RowNode.prototype, "rowModel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], RowNode.prototype, "context", void 0); __decorate([ context_1.Autowired('valueCache'), __metadata("design:type", valueCache_1.ValueCache) ], RowNode.prototype, "valueCache", void 0); __decorate([ context_1.Autowired('columnApi'), __metadata("design:type", columnApi_1.ColumnApi) ], RowNode.prototype, "columnApi", void 0); __decorate([ context_1.Autowired('gridApi'), __metadata("design:type", gridApi_1.GridApi) ], RowNode.prototype, "gridApi", void 0); return RowNode; }()); exports.RowNode = RowNode;
/** * DataZoom component entry */ import * as echarts from '../echarts'; import preprocessor from './visualMap/preprocessor'; import './visualMap/typeDefaulter'; import './visualMap/visualEncoding'; import './visualMap/PiecewiseModel'; import './visualMap/PiecewiseView'; import './visualMap/visualMapAction'; echarts.registerPreprocessor(preprocessor);
module.exports = { kolibriName: 'kolibriCoreAppGlobal', };
define("gridx/core/Cell", [ "dojo/_base/declare" ], function(declare){ return declare(/*===== "gridx.core.Cell", =====*/[], { // summary: // Represents a cell of a grid // description: // An instance of this class represents a grid cell. // This class should not be directly instantiated by users. It should be returned by grid APIs. /*===== // row: [readonly] gridx.core.Row // Reference to the row of this cell row: null, // column [readonly] gridx.core.Column // Reference to the column of this cell column: null, // grid: [readonly] gridx.Grid // Reference to the grid grid: null, // model: [readonly] grid.core.model.Model // Reference to this grid model model: null, =====*/ constructor: function(grid, row, column){ var t = this; t.grid = grid; t.model = grid.model; t.row = row; t.column = column; }, data: function(){ // summary: // Get the grid data of this cell. // description: // Grid data means the result of the formatter functions (if exist). // It can be different from store data (a.k.a. raw data). // returns: // The grid data in this cell return this.model.byId(this.row.id).data[this.column.id]; //String|Number }, rawData: function(){ // summary: // Get the store data of this cell. // description: // If the column of this cell has a store field, then this method can return the store data of this cell. // returns: // The store data of this cell var t = this, f = t.column.field(); return f && t.model.byId(t.row.id).rawData[f]; //anything }, setRawData: function(rawData){ // summary: // Set new raw data to this cell. // rawData: // Anything that store can recognize as data // returns: // If using server side store, a Deferred object is returned to indicate when the operation is finished. var obj = {}, field = this.column.field(); if(field){ obj[field] = rawData; return this.row.setRawData(obj); //dojo.Deferred } } }); });
//USERS $(function() { //DISABLE NAV TAB $.cms.disableNavTab(); //SAVE AND CONTINUE $.cms.saveContinue(); });
/** * checks if a given react wrapper wraps an intrinsic element i.e. a DOM node * @param {import('enzyme').ReactWrapper} reactWrapper * @returns {boolean} true if the given reactWrapper wraps an intrinsic element */ export function wrapsIntrinsicElement(reactWrapper) { return typeof reactWrapper.type() === 'string'; } /** * like ReactWrapper#getDOMNode() but returns a ReactWrapper * @param {import('enzyme').ReactWrapper} reactWrapper * @returns {import('enzyme').ReactWrapper} the wrapper for the outermost DOM node */ export default function findOutermostIntrinsic(reactWrapper) { return reactWrapper.findWhere((n) => n.exists() && wrapsIntrinsicElement(n)).first(); }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; const RelayTransformError = require('./RelayTransformError'); const util = require('util'); /** * In case of an error during transform, determine if it should be logged * to the console and/or printed in the source. */ function createTransformError(error: any): string { if (error instanceof RelayTransformError) { return `Relay Transform Error: ${error.message}`; } const {sourceText, validationErrors} = error; if (validationErrors && sourceText) { const sourceLines = sourceText.split('\n'); return validationErrors .map(({message, locations}) => { return ( 'GraphQL Validation Error: ' + message + '\n' + locations .map(location => { const preview = sourceLines[location.line - 1]; return ( preview && [ '>', '> ' + preview, '> ' + ' '.repeat(location.column - 1) + '^^^', ].join('\n') ); }) .filter(Boolean) .join('\n') ); }) .join('\n'); } return util.format( 'Relay Transform Error: %s\n\n%s', error.message, error.stack, ); } module.exports = createTransformError;
/** * Module dependencies. */ var _ = require('underscore'); var debug = require('debug')('auth0-lock:mode-reset'); var $ = require('../bonzo-augmented'); var Emitter = require('events').EventEmitter; var create = require('../object-create'); var stop = require('../stop-event'); var bind = require('../bind'); var template = require('./reset.ejs'); var regex = require('../regex'); var PasswordStrength = require('../password-strength'); var ValidationError = require('../errors/ValidationError'); var empty = regex.empty; var trim = require('trim'); var email_parser = regex.email_parser; var slice = Array.prototype.slice; /** * Expose ResetPanel */ module.exports = ResetPanel; /** * Create `ResetPanel` * * @param {Auth0Lock} widget * @param {Object} options * @constructor */ function ResetPanel(widget, options) { if (!(this instanceof ResetPanel)) { return new ResetPanel(widget, options); } // Both `widget` and `options` are required if (2 !== arguments.length) { throw new Error('Missing parameters for ResetPanel'); } this.name = 'reset'; this.widget = widget; this.options = this.resolveOptions(options); this.el = null; Emitter.call(this); } /** * Inherit from `EventEmitter` */ ResetPanel.prototype = create(Emitter.prototype); /** * Query for elements at `this.el` context * * @param {String} selector * @return {BonzoAugmented} * @public */ ResetPanel.prototype.query = function(selector) { if (!this.el) throw new Error('Can\'t get element since no `el` is set to local context'); return $(selector, this.el); }; /** * Create `el` * * @param {Object} options * @return {NodeElement} * @public */ ResetPanel.prototype.create = function(options) { var opts = this.resolveOptions(options); var widget = this.widget; this.el = $.create(widget.render(template, opts))[0]; this.bindAll(); return this.el; }; /** * Return `el` or create it * * @param {Object} options * @return {NodeElement} * @public */ ResetPanel.prototype.render = function() { return null != this.el ? this.el : this.create.apply(this, arguments); }; /** * Resolves login options passed to template * * @param {Object} options * @return {Object} * @private */ ResetPanel.prototype.resolveOptions = function(options) { return _.extend({}, this.widget.options, this.options, options); }; /** * Bind events to `this.el`, like submit * * @return {ResetPanel} * @private */ ResetPanel.prototype.bindAll = function() { var options = this.options; // hide only and only if set to false this.query('.a0-options') .toggleClass('a0-hide', !options.showResetAction); this.query('form') .a0_off('submit') .a0_on('submit', bind(this.onsubmit, this)); this.query('.a0-options .a0-cancel') .a0_on('click', bind(this.oncancel, this)); this.query('input[name=email]') .a0_on('input', bind(this.onemailinput, this)); var passwordStrength = new PasswordStrength(this.query('.a0-password_policy'), this.query('#a0-reset_easy_password'), this.options); return this; }; /** * Handler for email input event * * @param {Event} e * @private */ ResetPanel.prototype.onemailinput = function() { var mailField = this.query('input[name=email]'); var email = mailField.val(); if (this.options._isConnectionEmail(email)) { var widget = this.widget; widget._setPreviousPanel('reset'); widget._showSuccess(); widget._showError(); widget._focusError(); widget._signinPanel(); widget._setEmail(email); return; } }; /** * Handler for `submit` form event * * @param {Event} e * @private */ ResetPanel.prototype.onsubmit = function(e) { stop(e); if (!this.valid()) { return; } this.submit(); }; /** * Handler for `cancel` event click * * @param {Event} e * @private */ ResetPanel.prototype.oncancel = function(e) { stop(e); var widget = this.widget; widget._showSuccess(); widget._showError(); widget._focusError(); widget._signinPanel(); }; /** * Validate form for errros before `submit` * * @private */ ResetPanel.prototype.valid = function () { var ok = true; var email_input = this.query('input[name=email]'); var email = trim(email_input.val()); var email_empty = empty.test(email); var email_parsed = email_parser.exec(email.toLowerCase()); var validate_username = this.options._isUsernameRequired(); var username_parsed = regex.username_parser.exec(email_input.val().toLowerCase()); var password_input = this.query('input[name=password]'); var password = password_input.val(); var password_empty = empty.test(password); var repeat_password_input = this.query('input[name=repeat_password]'); var repeat_password = repeat_password_input.val(); var repeat_password_empty = empty.test(repeat_password); var widget = this.widget; // asume valid by default // and reset errors widget._showError(); widget._focusError(); if (email_empty) { var error_message = validate_username ? 'username empty' : 'email empty'; widget.emit('reset error', new ValidationError(error_message)); widget._focusError(email_input); ok = false; } if (!email_parsed && !email_empty) { ok = false || (validate_username && username_parsed); if (!ok) { var invalid_error = validate_username ? 'username invalid' : 'email invalid'; widget.emit('reset error', new ValidationError(invalid_error)); widget._focusError(email_input, widget.options.i18n.t('invalid')); } } if (password_empty) { widget.emit('reset error', new ValidationError('password empty')); widget._focusError(password_input); ok = false; } if (repeat_password_empty) { widget.emit('reset error', new ValidationError('repeat password empty')); widget._focusError(repeat_password_input); ok = false; } if (repeat_password_input.val() !== password_input.val()) { widget.emit('reset error', new ValidationError('password missmatch')); widget._focusError(repeat_password_input, widget.options.i18n.t('mustMatch')); ok = false; } return ok; }; /** * Submit validated form to Auth0 for password reset * * @private */ ResetPanel.prototype.submit = function () { var panel = this; var widget = panel.widget; var email_input = this.query('input[name=email]'); var username = email_input.val(); var password_input = this.query('input[name=password]'); var password = password_input.val(); var repeat_password_input = this.query('input[name=repeat_password]'); var connection = this.options._getAuth0Connection(); var callback = panel.options.popupCallback; widget._loadingPanel({ mode: 'reset' }); widget.emit('reset submit', widget.options); widget.$auth0.changePassword({ connection: connection.name, username: username, password: password }, function (err) { var args = slice.call(arguments, 0); if (!widget.$container) { return debug('changePassword ended but this.widget has been detached from DOM: %o', arguments); } // This is now dummy, and should no longer exist since all // dom events keep a reference to widget.$container if (widget.query()[0] !== widget.$container.childNodes[0]) { return debug('this password reset was triggered from another node instance', arguments); } // clean password input either there is an error or not password_input.val(''); repeat_password_input.val(''); if (!err) { email_input.val(''); widget._signinPanel(panel.options); widget._showSuccess(widget.options.i18n.t('reset:successText')); widget.emit('reset success'); return 'function' === typeof callback ? callback.apply(widget, args) : null; } widget.emit('reset error', err); widget.setPanel(panel); if (400 === err.status) { if ('invalid_password' === err.name) { widget._focusError(email_input); widget._showError(widget.options.i18n.t('reset:invalidPassword')); return; } widget._focusError(email_input); widget._showError(widget.options.i18n.t('reset:userDoesNotExistErrorText')); } else { widget._showError(widget.options.i18n.t('reset:serverErrorText')); } return 'function' === typeof callback ? callback.apply(widget, args) : null; }); };
// A2Z F15 // Daniel Shiffman // https://github.com/shiffman/A2Z-F15 // This sheet // | ----------------| // | label | number | // | ----------------| // | apple | 9 | // | ----------------| // | pear | 4 | // | ----------------| // | orange | 3 | // | ----------------| // Turns into: // [ { label: apple, number: 9 }, { label: pear, number: 4 }, { label: orange, number: 3 } ] function setup() { // This is the URL for my google sheet // The sheet is generated from this form: http://goo.gl/forms/0X67GZJTZJ // The sheet must set to File --> Published for the Web var url = 'https://docs.google.com/spreadsheets/d/1YQ7js53a5Gdidi3XS5HxkDvHWgmAS1kCCi9NnmH7Uc0/pubhtml'; // Tabletop expects some settings var settings = { key: url, // The url of the published google sheet callback: gotData, // A callback for when the data comes in simpleSheet: true // This makes things simpler for just a single worksheet of rows } // Make the request Tabletop.init(settings); // The data comes back as an array of objects // Each object contains all the data for one row of the sheet // See comment above function gotData(data) { // Look at the data in the console console.log(data); // Make an HTML list var list = createElement('ol'); list.parent('data'); for (var i = 0; i < data.length; i++) { var item = createElement('li', data[i].label + ': ' + data[i].Number + ", submited at " + data[i].Timestamp); item.parent(list); } } }
(function() { var callWithJQuery; callWithJQuery = function(pivotModule) { if (typeof exports === "object" && typeof module === "object") { return pivotModule(require("jquery")); } else if (typeof define === "function" && define.amd) { return define(["jquery"], pivotModule); } else { return pivotModule(jQuery); } }; callWithJQuery(function($) { return $.pivotUtilities.export_renderers = { "TSV Export": function(pivotData, opts) { var agg, colAttrs, colKey, colKeys, defaults, i, j, k, l, len, len1, len2, len3, len4, len5, m, n, r, result, row, rowAttr, rowAttrs, rowKey, rowKeys, text; defaults = { localeStrings: {} }; opts = $.extend(true, {}, defaults, opts); rowKeys = pivotData.getRowKeys(); if (rowKeys.length === 0) { rowKeys.push([]); } colKeys = pivotData.getColKeys(); if (colKeys.length === 0) { colKeys.push([]); } rowAttrs = pivotData.rowAttrs; colAttrs = pivotData.colAttrs; result = []; row = []; for (i = 0, len = rowAttrs.length; i < len; i++) { rowAttr = rowAttrs[i]; row.push(rowAttr); } if (colKeys.length === 1 && colKeys[0].length === 0) { row.push(pivotData.aggregatorName); } else { for (j = 0, len1 = colKeys.length; j < len1; j++) { colKey = colKeys[j]; row.push(colKey.join("-")); } } result.push(row); for (k = 0, len2 = rowKeys.length; k < len2; k++) { rowKey = rowKeys[k]; row = []; for (l = 0, len3 = rowKey.length; l < len3; l++) { r = rowKey[l]; row.push(r); } for (m = 0, len4 = colKeys.length; m < len4; m++) { colKey = colKeys[m]; agg = pivotData.getAggregator(rowKey, colKey); if (agg.value() != null) { row.push(agg.value()); } else { row.push(""); } } result.push(row); } text = ""; for (n = 0, len5 = result.length; n < len5; n++) { r = result[n]; text += r.join("\t") + "\n"; } return $("<textarea>").text(text).css({ width: ($(window).width() / 2) + "px", height: ($(window).height() / 2) + "px" }); } }; }); }).call(this); //# sourceMappingURL=export_renderers.js.map
var gulp = require('gulp'); var notify = require('../'); var through = require('through2'); var plumber = require('gulp-plumber'); gulp.task("multiple", function () { gulp.src("../test/fixtures/*") .pipe(notify()); }); gulp.task("one", function () { gulp.src("../test/fixtures/1.txt") .pipe(notify()); }); gulp.task("message", function () { gulp.src("../test/fixtures/1.txt") .pipe(notify("This is a message.")); }); gulp.task("customReporter", function () { var custom = notify.withReporter(function (options, callback) { console.log("Title:", options.title); console.log("Message:", options.message); callback(); }); gulp.src("../test/fixtures/1.txt") .pipe(custom("This is a message.")); }); gulp.task("template", function () { gulp.src("../test/fixtures/1.txt") .pipe(notify("Template: <%= file.relative %>")); }); gulp.task("templateadv", function () { gulp.src("../test/fixtures/1.txt") .pipe(notify({ message: "Template: <%= file.relative %>", title: function (file) { if(file.isNull()) { return "Folder:"; } return "File: <%= file.relative %> <%= options.extra %>"; }, templateOptions: { extra: "foo" } })); }); gulp.task("function", function () { gulp.src("../test/fixtures/1.txt") .pipe(notify(function(file) { return "Some file: " + file.relative; })); }); gulp.task("onlast", function () { gulp.src("../test/fixtures/*") .pipe(notify({ onLast: true, message: function(file) { return "Some file: " + file.relative; } })); }); gulp.task("error", function () { gulp.src("../test/fixtures/*") .pipe(through.obj(function (file, enc, callback) { this.emit("error", new Error("Something happend: Error message!")); callback(); })) .on("error", notify.onError('Error: <%= error.message %>')) .on("error", function (err) { console.log("Error:", err); }) }); gulp.task("customError", function () { var custom = notify.withReporter(function (options, callback) { console.log("Title:", options.title); console.log("Message:", options.message); callback(); }); gulp.src("../test/fixtures/*") .pipe(custom('<%= file.relative %>')) .pipe(through.obj(function (file, enc, callback) { this.emit("error", new Error("Something happend: Error message!")); callback(); })) .on("error", custom.onError('Error: <%= error.message %>')) .on("error", function (err) { console.log("Error:", err); }) });
angular.module('chat').config( ['$routeProvider', function($routeProvider) { $routeProvider. when('/chat', { templateUrl: 'chat/views/chat.client.view.html' }); } ]);
/*! * jQuery JavaScript Library v2.1.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-deprecated,-dimensions,-event-alias,-offset * 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:15Z */ (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 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-deprecated,-dimensions,-event-alias,-offset", // 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; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // 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(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } 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#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // 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 + "*" ), 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" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, 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<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint 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 (jQuery #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 ) && testContext( 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]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ 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; }; /** * 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 hasCompare, 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 !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", 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 = rnative.test( doc.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 msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // 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: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + 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.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 ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.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 ? 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 = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // 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 || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected 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 ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; 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 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; 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 while ( (node = elem[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 (jQuery #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[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[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // 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 negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { 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; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // 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(); tokenize = Sizzle.tokenize = function( 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 oldCache, outerCache, newCache = [ 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 ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { 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 multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } 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 ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (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; } } // 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, match /* 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 ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and 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; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } 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 ) && testContext( 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 if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); 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 elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); 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; 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 ); } }); 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(); } }); 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 ); }; 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(); } }); // 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 ); }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; // 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; }));
/* * Globalize Culture sms-FI * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "sms-FI", "default", { name: "sms-FI", englishName: "Sami, Skolt (Finland)", nativeName: "sääm´ǩiõll (Lää´ddjânnam)", language: "sms", numberFormat: { ",": " ", ".": ",", percent: { ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ",": " ", ".": ",", symbol: "€" } }, calendars: { standard: { "/": ".", firstDay: 1, days: { names: ["pâ´sspei´vv","vuõssargg","mââibargg","seärad","nelljdpei´vv","piâtnâc","sue´vet"], namesAbbr: ["pâ","vu","mâ","se","ne","pi","su"], namesShort: ["p","v","m","s","n","p","s"] }, months: { names: ["ođđee´jjmään","tä´lvvmään","pâ´zzlâšttammään","njuhččmään","vue´ssmään","ǩie´ssmään","suei´nnmään","på´rǧǧmään","čõhččmään","kålggmään","skamm´mään","rosttovmään",""], namesAbbr: ["ođjm","tä´lvv","pâzl","njuh","vue","ǩie","suei","på´r","čõh","kålg","ska","rost",""] }, monthsGenitive: { names: ["ođđee´jjmannu","tä´lvvmannu","pâ´zzlâšttammannu","njuhččmannu","vue´ssmannu","ǩie´ssmannu","suei´nnmannu","på´rǧǧmannu","čõhččmannu","kålggmannu","skamm´mannu","rosttovmannu",""], namesAbbr: ["ođjm","tä´lvv","pâzl","njuh","vue","ǩie","suei","på´r","čõh","kålg","ska","rost",""] }, AM: null, PM: null, patterns: { d: "d.M.yyyy", D: "MMMM d'. p. 'yyyy", t: "H:mm", T: "H:mm:ss", f: "MMMM d'. p. 'yyyy H:mm", F: "MMMM d'. p. 'yyyy H:mm:ss", M: "MMMM d'. p. '", Y: "MMMM yyyy" } } } }); }( this ));
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "a.m.", "p.m." ], "DAY": [ "domingo", "lunes", "martes", "mi\u00e9rcoles", "jueves", "viernes", "s\u00e1bado" ], "MONTH": [ "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" ], "SHORTDAY": [ "dom", "lun", "mar", "mi\u00e9", "jue", "vie", "s\u00e1b" ], "SHORTMONTH": [ "ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic" ], "fullDate": "EEEE, d 'de' MMMM 'de' y", "longDate": "d 'de' MMMM 'de' y", "medium": "d/MM/yyyy HH:mm:ss", "mediumDate": "d/MM/yyyy", "mediumTime": "HH:mm:ss", "short": "d/MM/yy HH:mm", "shortDate": "d/MM/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "es-gt", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
var eq = require('../shared/eq'); var _ = require('../../source/__'); var _curry2 = require('../../source/internal/_curry2'); describe('_curry2', function() { it('supports R.__ placeholder', function() { var f = function(a, b) { return [a, b]; }; var g = _curry2(f); eq(g(1)(2), [1, 2]); eq(g(1, 2), [1, 2]); eq(g(_, 2)(1), [1, 2]); eq(g(1, _)(2), [1, 2]); eq(g(_, _)(1)(2), [1, 2]); eq(g(_, _)(1, 2), [1, 2]); eq(g(_, _)(_)(1, 2), [1, 2]); eq(g(_, _)(_, 2)(1), [1, 2]); }); });
(function (root) { "use strict"; var buster = root.buster || require("buster"); var sinon = root.sinon || require("../lib/sinon"); var assert = buster.assert; var refute = buster.refute; var fail = buster.referee.fail; buster.testCase("sinon.stub", { "is spy": function () { var stub = sinon.stub.create(); assert.isFalse(stub.called); assert.isFunction(stub.calledWith); assert.isFunction(stub.calledOn); }, "should contain asynchronous versions of callsArg*, and yields* methods": function () { var stub = sinon.stub.create(); var syncVersions = 0; var asyncVersions = 0; for (var method in stub) { if (stub.hasOwnProperty(method) && method.match(/^(callsArg|yields)/)) { if (!method.match(/Async/)) { syncVersions++; } else if (method.match(/Async/)) { asyncVersions++; } } } assert.same(syncVersions, asyncVersions, "Stub prototype should contain same amount of synchronous and asynchronous methods"); }, "should allow overriding async behavior with sync behavior": function () { var stub = sinon.stub(); var callback = sinon.spy(); stub.callsArgAsync(1); stub.callsArg(1); stub(1, callback); assert(callback.called); }, ".returns": { "returns specified value": function () { var stub = sinon.stub.create(); var object = {}; stub.returns(object); assert.same(stub(), object); }, "returns should return stub": function () { var stub = sinon.stub.create(); assert.same(stub.returns(""), stub); }, "returns undefined": function () { var stub = sinon.stub.create(); refute.defined(stub()); }, "supersedes previous throws": function () { var stub = sinon.stub.create(); stub.throws().returns(1); refute.exception(function () { stub(); }); } }, ".returnsArg": { "returns argument at specified index": function () { var stub = sinon.stub.create(); stub.returnsArg(0); var object = {}; assert.same(stub(object), object); }, "returns stub": function () { var stub = sinon.stub.create(); assert.same(stub.returnsArg(0), stub); }, "throws if no index is specified": function () { var stub = sinon.stub.create(); assert.exception(function () { stub.returnsArg(); }, "TypeError"); }, "throws if index is not number": function () { var stub = sinon.stub.create(); assert.exception(function () { stub.returnsArg({}); }, "TypeError"); } }, ".returnsThis": { "stub returns this": function () { var instance = {}; instance.stub = sinon.stub.create(); instance.stub.returnsThis(); assert.same(instance.stub(), instance); }, "stub returns undefined when detached": { requiresSupportFor: { strictMode: (function () { return this; }()) === undefined }, "": function () { var stub = sinon.stub.create(); stub.returnsThis(); // Due to strict mode, would be `global` otherwise assert.same(stub(), undefined); } }, "stub respects call/apply": function () { var stub = sinon.stub.create(); stub.returnsThis(); var object = {}; assert.same(stub.call(object), object); assert.same(stub.apply(object), object); }, "returns stub": function () { var stub = sinon.stub.create(); assert.same(stub.returnsThis(), stub); } }, ".throws": { "throws specified exception": function () { var stub = sinon.stub.create(); var error = new Error(); stub.throws(error); try { stub(); fail("Expected stub to throw"); } catch (e) { assert.same(e, error); } }, "returns stub": function () { var stub = sinon.stub.create(); assert.same(stub.throws({}), stub); }, "sets type of exception to throw": function () { var stub = sinon.stub.create(); var exceptionType = "TypeError"; stub.throws(exceptionType); assert.exception(function () { stub(); }, exceptionType); }, "specifies exception message": function () { var stub = sinon.stub.create(); var message = "Oh no!"; stub.throws("Error", message); try { stub(); buster.referee.fail("Expected stub to throw"); } catch (e) { assert.equals(e.message, message); } }, "does not specify exception message if not provided": function () { var stub = sinon.stub.create(); stub.throws("Error"); try { stub(); buster.referee.fail("Expected stub to throw"); } catch (e) { assert.equals(e.message, ""); } }, "throws generic error": function () { var stub = sinon.stub.create(); stub.throws(); assert.exception(function () { stub(); }, "Error"); }, "resets 'invoking' flag": function () { var stub = sinon.stub.create(); stub.throws(); try { stub(); } catch (e) { refute.defined(stub.invoking); } } }, ".callsArg": { setUp: function () { this.stub = sinon.stub.create(); }, "calls argument at specified index": function () { this.stub.callsArg(2); var callback = sinon.stub.create(); this.stub(1, 2, callback); assert(callback.called); }, "returns stub": function () { assert.isFunction(this.stub.callsArg(2)); }, "throws if argument at specified index is not callable": function () { this.stub.callsArg(0); assert.exception(function () { this.stub(1); }, "TypeError"); }, "throws if no index is specified": function () { var stub = this.stub; assert.exception(function () { stub.callsArg(); }, "TypeError"); }, "throws if index is not number": function () { var stub = this.stub; assert.exception(function () { stub.callsArg({}); }, "TypeError"); } }, ".callsArgWith": { setUp: function () { this.stub = sinon.stub.create(); }, "calls argument at specified index with provided args": function () { var object = {}; this.stub.callsArgWith(1, object); var callback = sinon.stub.create(); this.stub(1, callback); assert(callback.calledWith(object)); }, "returns function": function () { var stub = this.stub.callsArgWith(2, 3); assert.isFunction(stub); }, "calls callback without args": function () { this.stub.callsArgWith(1); var callback = sinon.stub.create(); this.stub(1, callback); assert(callback.calledWith()); }, "calls callback with multiple args": function () { var object = {}; var array = []; this.stub.callsArgWith(1, object, array); var callback = sinon.stub.create(); this.stub(1, callback); assert(callback.calledWith(object, array)); }, "throws if no index is specified": function () { var stub = this.stub; assert.exception(function () { stub.callsArgWith(); }, "TypeError"); }, "throws if index is not number": function () { var stub = this.stub; assert.exception(function () { stub.callsArgWith({}); }, "TypeError"); } }, ".callsArgOn": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "calls argument at specified index": function () { this.stub.callsArgOn(2, this.fakeContext); var callback = sinon.stub.create(); this.stub(1, 2, callback); assert(callback.called); assert(callback.calledOn(this.fakeContext)); }, "returns stub": function () { var stub = this.stub.callsArgOn(2, this.fakeContext); assert.isFunction(stub); }, "throws if argument at specified index is not callable": function () { this.stub.callsArgOn(0, this.fakeContext); assert.exception(function () { this.stub(1); }, "TypeError"); }, "throws if no index is specified": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOn(); }, "TypeError"); }, "throws if no context is specified": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOn(3); }, "TypeError"); }, "throws if index is not number": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOn(this.fakeContext, 2); }, "TypeError"); }, "throws if context is not an object": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOn(2, 2); }, "TypeError"); } }, ".callsArgOnWith": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "calls argument at specified index with provided args": function () { var object = {}; this.stub.callsArgOnWith(1, this.fakeContext, object); var callback = sinon.stub.create(); this.stub(1, callback); assert(callback.calledWith(object)); assert(callback.calledOn(this.fakeContext)); }, "returns function": function () { var stub = this.stub.callsArgOnWith(2, this.fakeContext, 3); assert.isFunction(stub); }, "calls callback without args": function () { this.stub.callsArgOnWith(1, this.fakeContext); var callback = sinon.stub.create(); this.stub(1, callback); assert(callback.calledWith()); assert(callback.calledOn(this.fakeContext)); }, "calls callback with multiple args": function () { var object = {}; var array = []; this.stub.callsArgOnWith(1, this.fakeContext, object, array); var callback = sinon.stub.create(); this.stub(1, callback); assert(callback.calledWith(object, array)); assert(callback.calledOn(this.fakeContext)); }, "throws if no index is specified": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOnWith(); }, "TypeError"); }, "throws if no context is specified": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOnWith(3); }, "TypeError"); }, "throws if index is not number": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOnWith({}); }, "TypeError"); }, "throws if context is not an object": function () { var stub = this.stub; assert.exception(function () { stub.callsArgOnWith(2, 2); }, "TypeError"); } }, ".objectMethod": { setUp: function () { this.method = function () {}; this.object = { method: this.method }; this.wrapMethod = sinon.wrapMethod; }, tearDown: function () { sinon.wrapMethod = this.wrapMethod; }, "returns function from wrapMethod": function () { var wrapper = function () {}; sinon.wrapMethod = function () { return wrapper; }; var result = sinon.stub(this.object, "method"); assert.same(result, wrapper); }, "passes object and method to wrapMethod": function () { var wrapper = function () {}; var args; sinon.wrapMethod = function () { args = arguments; return wrapper; }; sinon.stub(this.object, "method"); assert.same(args[0], this.object); assert.same(args[1], "method"); }, "uses provided function as stub": function () { var called = false; var stub = sinon.stub(this.object, "method", function () { called = true; }); stub(); assert(called); }, "wraps provided function": function () { var customStub = function () {}; var stub = sinon.stub(this.object, "method", customStub); refute.same(stub, customStub); assert.isFunction(stub.restore); }, "throws if third argument is provided but not a function or proprety descriptor": function () { var object = this.object; assert.exception(function () { sinon.stub(object, "method", 1); }, "TypeError"); }, "stubbed method should be proper stub": function () { var stub = sinon.stub(this.object, "method"); assert.isFunction(stub.returns); assert.isFunction(stub.throws); }, "custom stubbed method should not be proper stub": function () { var stub = sinon.stub(this.object, "method", function () {}); refute.defined(stub.returns); refute.defined(stub.throws); }, "stub should be spy": function () { var stub = sinon.stub(this.object, "method"); this.object.method(); assert(stub.called); assert(stub.calledOn(this.object)); }, "custom stubbed method should be spy": function () { var stub = sinon.stub(this.object, "method", function () {}); this.object.method(); assert(stub.called); assert(stub.calledOn(this.object)); }, "stub should affect spy": function () { var stub = sinon.stub(this.object, "method"); stub.throws("TypeError"); try { this.object.method(); } catch (e) {} // eslint-disable-line no-empty assert(stub.threw("TypeError")); }, "returns standalone stub without arguments": function () { var stub = sinon.stub(); assert.isFunction(stub); assert.isFalse(stub.called); }, "throws if property is not a function": function () { var obj = { someProp: 42 }; assert.exception(function () { sinon.stub(obj, "someProp"); }); assert.equals(obj.someProp, 42); }, "successfully stubs falsey properties": function () { var obj = { 0: function () { } }; sinon.stub(obj, 0, function () { return "stubbed value"; }); assert.equals(obj[0](), "stubbed value"); }, "does not stub function object": function () { assert.exception(function () { sinon.stub(function () {}); }); } }, everything: { "stubs all methods of object without property": function () { var obj = { func1: function () {}, func2: function () {}, func3: function () {} }; sinon.stub(obj); assert.isFunction(obj.func1.restore); assert.isFunction(obj.func2.restore); assert.isFunction(obj.func3.restore); }, "stubs prototype methods": function () { function Obj() {} Obj.prototype.func1 = function () {}; var obj = new Obj(); sinon.stub(obj); assert.isFunction(obj.func1.restore); }, "returns object": function () { var object = {}; assert.same(sinon.stub(object), object); }, "only stubs functions": function () { var object = { foo: "bar" }; sinon.stub(object); assert.equals(object.foo, "bar"); }, "handles non-enumerable properties": function () { var obj = { func1: function () {}, func2: function () {} }; Object.defineProperty(obj, "func3", { value: function () {}, writable: true, configurable: true }); sinon.stub(obj); assert.isFunction(obj.func1.restore); assert.isFunction(obj.func2.restore); assert.isFunction(obj.func3.restore); }, "handles non-enumerable properties on prototypes": function () { function Obj() {} Object.defineProperty(Obj.prototype, "func1", { value: function () {}, writable: true, configurable: true }); var obj = new Obj(); sinon.stub(obj); assert.isFunction(obj.func1.restore); }, "does not stub non-enumerable properties from Object.prototype": function () { var obj = {}; sinon.stub(obj); refute.isFunction(obj.toString.restore); refute.isFunction(obj.toLocaleString.restore); refute.isFunction(obj.propertyIsEnumerable.restore); }, "does not fail on overrides": function () { var parent = { func: function () {} }; var child = sinon.create(parent); child.func = function () {}; refute.exception(function () { sinon.stub(child); }); } }, "stubbed function": { "throws if stubbing non-existent property": function () { var myObj = {}; assert.exception(function () { sinon.stub(myObj, "ouch"); }); refute.defined(myObj.ouch); }, "has toString method": function () { var obj = { meth: function () {} }; sinon.stub(obj, "meth"); assert.equals(obj.meth.toString(), "meth"); }, "toString should say 'stub' when unable to infer name": function () { var stub = sinon.stub(); assert.equals(stub.toString(), "stub"); }, "toString should prefer property name if possible": function () { var obj = {}; obj.meth = sinon.stub(); obj.meth(); assert.equals(obj.meth.toString(), "meth"); } }, ".yields": { "invokes only argument as callback": function () { var stub = sinon.stub().yields(); var spy = sinon.spy(); stub(spy); assert(spy.calledOnce); assert.equals(spy.args[0].length, 0); }, "throws understandable error if no callback is passed": function () { var stub = sinon.stub().yields(); try { stub(); throw new Error(); } catch (e) { assert.equals(e.message, "stub expected to yield, but no callback was passed."); } }, "includes stub name and actual arguments in error": function () { var myObj = { somethingAwesome: function () {} }; var stub = sinon.stub(myObj, "somethingAwesome").yields(); try { stub(23, 42); throw new Error(); } catch (e) { assert.equals(e.message, "somethingAwesome expected to yield, but no callback " + "was passed. Received [23, 42]"); } }, "invokes last argument as callback": function () { var stub = sinon.stub().yields(); var spy = sinon.spy(); stub(24, {}, spy); assert(spy.calledOnce); assert.equals(spy.args[0].length, 0); }, "invokes first of two callbacks": function () { var stub = sinon.stub().yields(); var spy = sinon.spy(); var spy2 = sinon.spy(); stub(24, {}, spy, spy2); assert(spy.calledOnce); assert(!spy2.called); }, "invokes callback with arguments": function () { var obj = { id: 42 }; var stub = sinon.stub().yields(obj, "Crazy"); var spy = sinon.spy(); stub(spy); assert(spy.calledWith(obj, "Crazy")); }, "throws if callback throws": function () { var obj = { id: 42 }; var stub = sinon.stub().yields(obj, "Crazy"); var callback = sinon.stub().throws(); assert.exception(function () { stub(callback); }); }, "plays nice with throws": function () { var stub = sinon.stub().throws().yields(); var spy = sinon.spy(); assert.exception(function () { stub(spy); }); assert(spy.calledOnce); }, "plays nice with returns": function () { var obj = {}; var stub = sinon.stub().returns(obj).yields(); var spy = sinon.spy(); assert.same(stub(spy), obj); assert(spy.calledOnce); }, "plays nice with returnsArg": function () { var stub = sinon.stub().returnsArg(0).yields(); var spy = sinon.spy(); assert.same(stub(spy), spy); assert(spy.calledOnce); }, "plays nice with returnsThis": function () { var obj = {}; var stub = sinon.stub().returnsThis().yields(); var spy = sinon.spy(); assert.same(stub.call(obj, spy), obj); assert(spy.calledOnce); } }, ".yieldsRight": { "invokes only argument as callback": function () { var stub = sinon.stub().yieldsRight(); var spy = sinon.spy(); stub(spy); assert(spy.calledOnce); assert.equals(spy.args[0].length, 0); }, "throws understandable error if no callback is passed": function () { var stub = sinon.stub().yieldsRight(); try { stub(); throw new Error(); } catch (e) { assert.equals(e.message, "stub expected to yield, but no callback was passed."); } }, "includes stub name and actual arguments in error": function () { var myObj = { somethingAwesome: function () {} }; var stub = sinon.stub(myObj, "somethingAwesome").yieldsRight(); try { stub(23, 42); throw new Error(); } catch (e) { assert.equals(e.message, "somethingAwesome expected to yield, but no callback " + "was passed. Received [23, 42]"); } }, "invokes last argument as callback": function () { var stub = sinon.stub().yieldsRight(); var spy = sinon.spy(); stub(24, {}, spy); assert(spy.calledOnce); assert.equals(spy.args[0].length, 0); }, "invokes the last of two callbacks": function () { var stub = sinon.stub().yieldsRight(); var spy = sinon.spy(); var spy2 = sinon.spy(); stub(24, {}, spy, spy2); assert(!spy.called); assert(spy2.calledOnce); }, "invokes callback with arguments": function () { var obj = { id: 42 }; var stub = sinon.stub().yieldsRight(obj, "Crazy"); var spy = sinon.spy(); stub(spy); assert(spy.calledWith(obj, "Crazy")); }, "throws if callback throws": function () { var obj = { id: 42 }; var stub = sinon.stub().yieldsRight(obj, "Crazy"); var callback = sinon.stub().throws(); assert.exception(function () { stub(callback); }); }, "plays nice with throws": function () { var stub = sinon.stub().throws().yieldsRight(); var spy = sinon.spy(); assert.exception(function () { stub(spy); }); assert(spy.calledOnce); }, "plays nice with returns": function () { var obj = {}; var stub = sinon.stub().returns(obj).yieldsRight(); var spy = sinon.spy(); assert.same(stub(spy), obj); assert(spy.calledOnce); }, "plays nice with returnsArg": function () { var stub = sinon.stub().returnsArg(0).yieldsRight(); var spy = sinon.spy(); assert.same(stub(spy), spy); assert(spy.calledOnce); }, "plays nice with returnsThis": function () { var obj = {}; var stub = sinon.stub().returnsThis().yieldsRight(); var spy = sinon.spy(); assert.same(stub.call(obj, spy), obj); assert(spy.calledOnce); } }, ".yieldsOn": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "invokes only argument as callback": function () { var spy = sinon.spy(); this.stub.yieldsOn(this.fakeContext); this.stub(spy); assert(spy.calledOnce); assert(spy.calledOn(this.fakeContext)); assert.equals(spy.args[0].length, 0); }, "throws if no context is specified": function () { assert.exception(function () { this.stub.yieldsOn(); }, "TypeError"); }, "throws understandable error if no callback is passed": function () { this.stub.yieldsOn(this.fakeContext); try { this.stub(); throw new Error(); } catch (e) { assert.equals(e.message, "stub expected to yield, but no callback was passed."); } }, "includes stub name and actual arguments in error": function () { var myObj = { somethingAwesome: function () {} }; var stub = sinon.stub(myObj, "somethingAwesome").yieldsOn(this.fakeContext); try { stub(23, 42); throw new Error(); } catch (e) { assert.equals(e.message, "somethingAwesome expected to yield, but no callback " + "was passed. Received [23, 42]"); } }, "invokes last argument as callback": function () { var spy = sinon.spy(); this.stub.yieldsOn(this.fakeContext); this.stub(24, {}, spy); assert(spy.calledOnce); assert(spy.calledOn(this.fakeContext)); assert.equals(spy.args[0].length, 0); }, "invokes first of two callbacks": function () { var spy = sinon.spy(); var spy2 = sinon.spy(); this.stub.yieldsOn(this.fakeContext); this.stub(24, {}, spy, spy2); assert(spy.calledOnce); assert(spy.calledOn(this.fakeContext)); assert(!spy2.called); }, "invokes callback with arguments": function () { var obj = { id: 42 }; var spy = sinon.spy(); this.stub.yieldsOn(this.fakeContext, obj, "Crazy"); this.stub(spy); assert(spy.calledWith(obj, "Crazy")); assert(spy.calledOn(this.fakeContext)); }, "throws if callback throws": function () { var obj = { id: 42 }; var callback = sinon.stub().throws(); this.stub.yieldsOn(this.fakeContext, obj, "Crazy"); assert.exception(function () { this.stub(callback); }); } }, ".yieldsTo": { "yields to property of object argument": function () { var stub = sinon.stub().yieldsTo("success"); var callback = sinon.spy(); stub({ success: callback }); assert(callback.calledOnce); assert.equals(callback.args[0].length, 0); }, "throws understandable error if no object with callback is passed": function () { var stub = sinon.stub().yieldsTo("success"); try { stub(); throw new Error(); } catch (e) { assert.equals(e.message, "stub expected to yield to 'success', but no object " + "with such a property was passed."); } }, "includes stub name and actual arguments in error": function () { var myObj = { somethingAwesome: function () {} }; var stub = sinon.stub(myObj, "somethingAwesome").yieldsTo("success"); try { stub(23, 42); throw new Error(); } catch (e) { assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " + "no object with such a property was passed. " + "Received [23, 42]"); } }, "invokes property on last argument as callback": function () { var stub = sinon.stub().yieldsTo("success"); var callback = sinon.spy(); stub(24, {}, { success: callback }); assert(callback.calledOnce); assert.equals(callback.args[0].length, 0); }, "invokes first of two possible callbacks": function () { var stub = sinon.stub().yieldsTo("error"); var callback = sinon.spy(); var callback2 = sinon.spy(); stub(24, {}, { error: callback }, { error: callback2 }); assert(callback.calledOnce); assert(!callback2.called); }, "invokes callback with arguments": function () { var obj = { id: 42 }; var stub = sinon.stub().yieldsTo("success", obj, "Crazy"); var callback = sinon.spy(); stub({ success: callback }); assert(callback.calledWith(obj, "Crazy")); }, "throws if callback throws": function () { var obj = { id: 42 }; var stub = sinon.stub().yieldsTo("error", obj, "Crazy"); var callback = sinon.stub().throws(); assert.exception(function () { stub({ error: callback }); }); } }, ".yieldsToOn": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "yields to property of object argument": function () { this.stub.yieldsToOn("success", this.fakeContext); var callback = sinon.spy(); this.stub({ success: callback }); assert(callback.calledOnce); assert(callback.calledOn(this.fakeContext)); assert.equals(callback.args[0].length, 0); }, "throws if no context is specified": function () { assert.exception(function () { this.stub.yieldsToOn("success"); }, "TypeError"); }, "throws understandable error if no object with callback is passed": function () { this.stub.yieldsToOn("success", this.fakeContext); try { this.stub(); throw new Error(); } catch (e) { assert.equals(e.message, "stub expected to yield to 'success', but no object " + "with such a property was passed."); } }, "includes stub name and actual arguments in error": function () { var myObj = { somethingAwesome: function () {} }; var stub = sinon.stub(myObj, "somethingAwesome").yieldsToOn("success", this.fakeContext); try { stub(23, 42); throw new Error(); } catch (e) { assert.equals(e.message, "somethingAwesome expected to yield to 'success', but " + "no object with such a property was passed. " + "Received [23, 42]"); } }, "invokes property on last argument as callback": function () { var callback = sinon.spy(); this.stub.yieldsToOn("success", this.fakeContext); this.stub(24, {}, { success: callback }); assert(callback.calledOnce); assert(callback.calledOn(this.fakeContext)); assert.equals(callback.args[0].length, 0); }, "invokes first of two possible callbacks": function () { var callback = sinon.spy(); var callback2 = sinon.spy(); this.stub.yieldsToOn("error", this.fakeContext); this.stub(24, {}, { error: callback }, { error: callback2 }); assert(callback.calledOnce); assert(callback.calledOn(this.fakeContext)); assert(!callback2.called); }, "invokes callback with arguments": function () { var obj = { id: 42 }; var callback = sinon.spy(); this.stub.yieldsToOn("success", this.fakeContext, obj, "Crazy"); this.stub({ success: callback }); assert(callback.calledOn(this.fakeContext)); assert(callback.calledWith(obj, "Crazy")); }, "throws if callback throws": function () { var obj = { id: 42 }; var callback = sinon.stub().throws(); this.stub.yieldsToOn("error", this.fakeContext, obj, "Crazy"); assert.exception(function () { this.stub({ error: callback }); }); } }, ".withArgs": { "defines withArgs method": function () { var stub = sinon.stub(); assert.isFunction(stub.withArgs); }, "creates filtered stub": function () { var stub = sinon.stub(); var other = stub.withArgs(23); refute.same(other, stub); assert.isFunction(stub.returns); assert.isFunction(other.returns); }, "filters return values based on arguments": function () { var stub = sinon.stub().returns(23); stub.withArgs(42).returns(99); assert.equals(stub(), 23); assert.equals(stub(42), 99); }, "filters exceptions based on arguments": function () { var stub = sinon.stub().returns(23); stub.withArgs(42).throws(); refute.exception(stub); assert.exception(function () { stub(42); }); } }, ".callsArgAsync": { setUp: function () { this.stub = sinon.stub.create(); }, "asynchronously calls argument at specified index": function (done) { this.stub.callsArgAsync(2); var callback = sinon.spy(done); this.stub(1, 2, callback); assert(!callback.called); } }, ".callsArgWithAsync": { setUp: function () { this.stub = sinon.stub.create(); }, "asynchronously calls callback at specified index with multiple args": function (done) { var object = {}; var array = []; this.stub.callsArgWithAsync(1, object, array); var callback = sinon.spy(done(function () { assert(callback.calledWith(object, array)); })); this.stub(1, callback); assert(!callback.called); } }, ".callsArgOnAsync": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "asynchronously calls argument at specified index with specified context": function (done) { var context = this.fakeContext; this.stub.callsArgOnAsync(2, context); var callback = sinon.spy(done(function () { assert(callback.calledOn(context)); })); this.stub(1, 2, callback); assert(!callback.called); } }, ".callsArgOnWithAsync": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "asynchronously calls argument at specified index with provided context and args": function (done) { var object = {}; var context = this.fakeContext; this.stub.callsArgOnWithAsync(1, context, object); var callback = sinon.spy(done(function () { assert(callback.calledOn(context)); assert(callback.calledWith(object)); })); this.stub(1, callback); assert(!callback.called); } }, ".yieldsAsync": { "asynchronously invokes only argument as callback": function (done) { var stub = sinon.stub().yieldsAsync(); var spy = sinon.spy(done); stub(spy); assert(!spy.called); } }, ".yieldsOnAsync": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "asynchronously invokes only argument as callback with given context": function (done) { var context = this.fakeContext; this.stub.yieldsOnAsync(context); var spy = sinon.spy(done(function () { assert(spy.calledOnce); assert(spy.calledOn(context)); assert.equals(spy.args[0].length, 0); })); this.stub(spy); assert(!spy.called); } }, ".yieldsToAsync": { "asynchronously yields to property of object argument": function (done) { var stub = sinon.stub().yieldsToAsync("success"); var callback = sinon.spy(done(function () { assert(callback.calledOnce); assert.equals(callback.args[0].length, 0); })); stub({ success: callback }); assert(!callback.called); } }, ".yieldsToOnAsync": { setUp: function () { this.stub = sinon.stub.create(); this.fakeContext = { foo: "bar" }; }, "asynchronously yields to property of object argument with given context": function (done) { var context = this.fakeContext; this.stub.yieldsToOnAsync("success", context); var callback = sinon.spy(done(function () { assert(callback.calledOnce); assert(callback.calledOn(context)); assert.equals(callback.args[0].length, 0); })); this.stub({ success: callback }); assert(!callback.called); } }, ".onCall": { "can be used with returns to produce sequence": function () { var stub = sinon.stub().returns(3); stub.onFirstCall().returns(1) .onCall(2).returns(2); assert.same(stub(), 1); assert.same(stub(), 3); assert.same(stub(), 2); assert.same(stub(), 3); }, "can be used with returnsArg to produce sequence": function () { var stub = sinon.stub().returns("default"); stub.onSecondCall().returnsArg(0); assert.same(stub(1), "default"); assert.same(stub(2), 2); assert.same(stub(3), "default"); }, "can be used with returnsThis to produce sequence": function () { var instance = {}; instance.stub = sinon.stub().returns("default"); instance.stub.onSecondCall().returnsThis(); assert.same(instance.stub(), "default"); assert.same(instance.stub(), instance); assert.same(instance.stub(), "default"); }, "can be used with throwsException to produce sequence": function () { var stub = sinon.stub(); var error = new Error(); stub.onSecondCall().throwsException(error); stub(); try { stub(); fail("Expected stub to throw"); } catch (e) { assert.same(e, error); } }, "in combination with withArgs": { "can produce a sequence for a fake": function () { var stub = sinon.stub().returns(0); stub.withArgs(5).returns(-1) .onFirstCall().returns(1) .onSecondCall().returns(2); assert.same(stub(0), 0); assert.same(stub(5), 1); assert.same(stub(0), 0); assert.same(stub(5), 2); assert.same(stub(5), -1); }, "falls back to stub default behaviour if fake does not have its own default behaviour": function () { var stub = sinon.stub().returns(0); stub.withArgs(5) .onFirstCall().returns(1); assert.same(stub(5), 1); assert.same(stub(5), 0); }, "falls back to stub behaviour for call if fake does not have its own behaviour for call": function () { var stub = sinon.stub().returns(0); stub.withArgs(5).onFirstCall().returns(1); stub.onSecondCall().returns(2); assert.same(stub(5), 1); assert.same(stub(5), 2); assert.same(stub(4), 0); }, "defaults to undefined behaviour once no more calls have been defined": function () { var stub = sinon.stub(); stub.withArgs(5).onFirstCall().returns(1) .onSecondCall().returns(2); assert.same(stub(5), 1); assert.same(stub(5), 2); refute.defined(stub(5)); }, "does not create undefined behaviour just by calling onCall": function () { var stub = sinon.stub().returns(2); stub.onFirstCall(); assert.same(stub(6), 2); }, "works with fakes and reset": function () { var stub = sinon.stub(); stub.withArgs(5).onFirstCall().returns(1); stub.withArgs(5).onSecondCall().returns(2); assert.same(stub(5), 1); assert.same(stub(5), 2); refute.defined(stub(5)); stub.reset(); assert.same(stub(5), 1); assert.same(stub(5), 2); refute.defined(stub(5)); }, "throws an understandable error when trying to use withArgs on behavior": function () { try { sinon.stub().onFirstCall().withArgs(1); } catch (e) { assert.match(e.message, /not supported/); } } }, "can be used with yields* to produce a sequence": function () { var context = { foo: "bar" }; var obj = { method1: sinon.spy(), method2: sinon.spy() }; var obj2 = { method2: sinon.spy() }; var stub = sinon.stub().yieldsToOn("method2", context, 7, 8); stub.onFirstCall().yields(1, 2) .onSecondCall().yieldsOn(context, 3, 4) .onThirdCall().yieldsTo("method1", 5, 6) .onCall(3).yieldsToOn("method2", context, 7, 8); var spy1 = sinon.spy(); var spy2 = sinon.spy(); stub(spy1); stub(spy2); stub(obj); stub(obj); stub(obj2); // should continue with default behavior assert(spy1.calledOnce); assert(spy1.calledWithExactly(1, 2)); assert(spy2.calledOnce); assert(spy2.calledAfter(spy1)); assert(spy2.calledOn(context)); assert(spy2.calledWithExactly(3, 4)); assert(obj.method1.calledOnce); assert(obj.method1.calledAfter(spy2)); assert(obj.method1.calledWithExactly(5, 6)); assert(obj.method2.calledOnce); assert(obj.method2.calledAfter(obj.method1)); assert(obj.method2.calledOn(context)); assert(obj.method2.calledWithExactly(7, 8)); assert(obj2.method2.calledOnce); assert(obj2.method2.calledAfter(obj.method2)); assert(obj2.method2.calledOn(context)); assert(obj2.method2.calledWithExactly(7, 8)); }, "can be used with callsArg* to produce a sequence": function () { var spy1 = sinon.spy(); var spy2 = sinon.spy(); var spy3 = sinon.spy(); var spy4 = sinon.spy(); var spy5 = sinon.spy(); var decoy = sinon.spy(); var context = { foo: "bar" }; var stub = sinon.stub().callsArgOnWith(3, context, "c", "d"); stub.onFirstCall().callsArg(0) .onSecondCall().callsArgWith(1, "a", "b") .onThirdCall().callsArgOn(2, context) .onCall(3).callsArgOnWith(3, context, "c", "d"); stub(spy1); stub(decoy, spy2); stub(decoy, decoy, spy3); stub(decoy, decoy, decoy, spy4); stub(decoy, decoy, decoy, spy5); // should continue with default behavior assert(spy1.calledOnce); assert(spy2.calledOnce); assert(spy2.calledAfter(spy1)); assert(spy2.calledWithExactly("a", "b")); assert(spy3.calledOnce); assert(spy3.calledAfter(spy2)); assert(spy3.calledOn(context)); assert(spy4.calledOnce); assert(spy4.calledAfter(spy3)); assert(spy4.calledOn(context)); assert(spy4.calledWithExactly("c", "d")); assert(spy5.calledOnce); assert(spy5.calledAfter(spy4)); assert(spy5.calledOn(context)); assert(spy5.calledWithExactly("c", "d")); assert(decoy.notCalled); }, "can be used with yields* and callsArg* in combination to produce a sequence": function () { var stub = sinon.stub().yields(1, 2); stub.onSecondCall().callsArg(1) .onThirdCall().yieldsTo("method") .onCall(3).callsArgWith(2, "a", "b"); var obj = { method: sinon.spy() }; var spy1 = sinon.spy(); var spy2 = sinon.spy(); var spy3 = sinon.spy(); var decoy = sinon.spy(); stub(spy1); stub(decoy, spy2); stub(obj); stub(decoy, decoy, spy3); assert(spy1.calledOnce); assert(spy2.calledOnce); assert(spy2.calledAfter(spy1)); assert(obj.method.calledOnce); assert(obj.method.calledAfter(spy2)); assert(spy3.calledOnce); assert(spy3.calledAfter(obj.method)); assert(spy3.calledWithExactly("a", "b")); assert(decoy.notCalled); }, "should interact correctly with assertions (GH-231)": function () { var stub = sinon.stub(); var spy = sinon.spy(); stub.callsArgWith(0, "a"); stub(spy); assert(spy.calledWith("a")); stub(spy); assert(spy.calledWith("a")); stub.onThirdCall().callsArgWith(0, "b"); stub(spy); assert(spy.calledWith("b")); } }, "reset only resets call history": function () { var obj = { a: function () {} }; var spy = sinon.spy(); sinon.stub(obj, "a").callsArg(1); obj.a(null, spy); obj.a.reset(); obj.a(null, spy); assert(spy.calledTwice); }, ".resetBehavior": { "clears yields* and callsArg* sequence": function () { var stub = sinon.stub().yields(1); stub.onFirstCall().callsArg(1); stub.resetBehavior(); stub.yields(3); var spyWanted = sinon.spy(); var spyNotWanted = sinon.spy(); stub(spyWanted, spyNotWanted); assert(spyNotWanted.notCalled); assert(spyWanted.calledOnce); assert(spyWanted.calledWithExactly(3)); }, "cleans 'returns' behavior": function () { var stub = sinon.stub().returns(1); stub.resetBehavior(); refute.defined(stub()); }, "cleans behavior of fakes returned by withArgs": function () { var stub = sinon.stub(); stub.withArgs("lolz").returns(2); stub.resetBehavior(); refute.defined(stub("lolz")); }, "does not clean parents' behavior when called on a fake returned by withArgs": function () { var parentStub = sinon.stub().returns(false); var childStub = parentStub.withArgs("lolz").returns(true); childStub.resetBehavior(); assert.same(parentStub("lolz"), false); assert.same(parentStub(), false); }, "cleans 'returnsArg' behavior": function () { var stub = sinon.stub().returnsArg(0); stub.resetBehavior(); refute.defined(stub("defined")); }, "cleans 'returnsThis' behavior": function () { var instance = {}; instance.stub = sinon.stub.create(); instance.stub.returnsThis(); instance.stub.resetBehavior(); refute.defined(instance.stub()); }, "does not touch properties that are reset by 'reset'": { ".calledOnce": function () { var stub = sinon.stub(); stub(1); stub.resetBehavior(); assert(stub.calledOnce); }, "called multiple times": function () { var stub = sinon.stub(); stub(1); stub(2); stub(3); stub.resetBehavior(); assert(stub.called); assert.equals(stub.args.length, 3); assert.equals(stub.returnValues.length, 3); assert.equals(stub.exceptions.length, 3); assert.equals(stub.thisValues.length, 3); assert.defined(stub.firstCall); assert.defined(stub.secondCall); assert.defined(stub.thirdCall); assert.defined(stub.lastCall); }, "call order state": function () { var stubs = [sinon.stub(), sinon.stub()]; stubs[0](); stubs[1](); stubs[0].resetBehavior(); assert(stubs[0].calledBefore(stubs[1])); }, "fakes returned by withArgs": function () { var stub = sinon.stub(); var fakeA = stub.withArgs("a"); var fakeB = stub.withArgs("b"); stub("a"); stub("b"); stub("c"); var fakeC = stub.withArgs("c"); stub.resetBehavior(); assert(fakeA.calledOnce); assert(fakeB.calledOnce); assert(fakeC.calledOnce); } } }, ".length": { "is zero by default": function () { var stub = sinon.stub(); assert.equals(stub.length, 0); }, "matches the function length": function () { var api = { someMethod: function (a, b, c) {} }; // eslint-disable-line no-unused-vars var stub = sinon.stub(api, "someMethod"); assert.equals(stub.length, 3); } } }); }(this));
function runGa4ghTests() { oauth.google.apiKey = 'AIzaSyDUUAUFpQEN4mumeMNIRWXSiTh5cPtUAD0'; asyncTest("variantSet metadata", function () { var reader = new igv.Ga4ghVariantReader({ type: "vcf", url: "https://genomics.googleapis.com/v1", variantSetId: "10473108253681171589" }); reader.readMetadata().then(function (json) { ok(json); start(); }) }); asyncTest("search readGroupSets ", function () { var provider = igv.ga4gh.providers[0], datasetId = provider.datasets[0].id, url = provider.url; igv.ga4ghSearchReadGroupSets({ url: url, datasetId: datasetId, success: function (results) { equal(results.length, 16); start(); } }); }); asyncTest("search variantsets ", function () { var provider = igv.ga4gh.providers[0], datasetId = provider.datasets[0].id, url = provider.url; igv.ga4ghSearchVariantSets({ url: url, datasetId: datasetId, success: function (results) { equal(results.length, 1); start(); } }); }); /** * Search for callsets by a dataset id. Must first get the variant sets, then use these to search for * call sets */ asyncTest("search callsets ", function () { var provider = igv.ga4gh.providers[0], datasetId = provider.datasets[0].id, url = provider.url; igv.ga4ghSearchCallSets({ url: url, datasetId: datasetId, success: function (results) { equal(results.length, 17); start(); } }); }); //10473108253681171589-2 asyncTest("variant search with callset", function () { var reader = new igv.Ga4ghVariantReader({ type: "vcf", url: "https://genomics.googleapis.com/v1", variantSetId: "10473108253681171589", callSetIds: ["10473108253681171589-2"] }), chr = "1", bpStart = 155158585, bpEnd = 155158624; reader.readFeatures(chr, bpStart, bpEnd, function (variants) { ok(variants); equal(variants.length, 2); start(); }) }); /** * Search for callsets by a dataset id. Must first get the variant sets, then use these to search for * call sets */ asyncTest("search callsets ", function () { var provider = igv.ga4gh.providers[0], datasetId = provider.datasets[0].id, url = provider.url; igv.ga4ghSearchReadAndCallSets({ url: url, datasetId: datasetId, success: function (results) { equal(results.length, 16); start(); } }); }); // Query over wide region -- this takes some time, mainly here as a performance test // asyncTest("variant search muc1", function () { // // var reader = new igv.Ga4ghVariantReader({ // type: "vcf", // url: "https://genomics.googleapis.com/v1", // variantSetId: "10473108253681171589" // }), // chr = "1", // bpStart = 155156300, // bpEnd = 155164706; // // var t0 = (new Date()).getTime(); // // reader.readFeatures(chr, bpStart, bpEnd, function (variants) { // // ok(variants); // equal(variants.length, 77); // var dt = (new Date()).getTime() - t0; // console.log("T = " + (dt / 1000)); // // start(); // // }) // }); //asyncTest("readGroupSet metadata", function () { // // var reader = new igv.Ga4ghAlignmentReader({ // type: "bam", // url: "https://genomics.googleapis.com/v1", // readGroupSetIds: 'CMvnhpKTFhCjz9_25e_lCw' // }); // // reader.readMetadata(function (json) { // // ok(json); // // start(); // // }) //}); //test("Decode bam header", function () { // // var sampleJson = { // "id": "CMvnhpKTFhCjz9_25e_lCw", // "name": "HG01440", // "datasetId": "10473108253681171589", // "fileData": [ // { // "filename": "HG01440.mapped.ILLUMINA.bwa.CLM.low_coverage.20120522.bam", // "headers": [ // { // "version": "1.0", // "sortingOrder": "coordinate" // } // ], // "refSequences": [ // { // "name": "1", // "length": 249250621, // "md5Checksum": "1b22b98cdeb4a9304cb5d48026a85128", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "2", // "length": 243199373, // "md5Checksum": "a0d9851da00400dec1098a9255ac712e", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "3", // "length": 198022430, // "md5Checksum": "fdfd811849cc2fadebc929bb925902e5", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "4", // "length": 191154276, // "md5Checksum": "23dccd106897542ad87d2765d28a19a1", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "5", // "length": 180915260, // "md5Checksum": "0740173db9ffd264d728f32784845cd7", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "6", // "length": 171115067, // "md5Checksum": "1d3a93a248d92a729ee764823acbbc6b", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "7", // "length": 159138663, // "md5Checksum": "618366e953d6aaad97dbe4777c29375e", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "8", // "length": 146364022, // "md5Checksum": "96f514a9929e410c6651697bded59aec", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "9", // "length": 141213431, // "md5Checksum": "3e273117f15e0a400f01055d9f393768", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "10", // "length": 135534747, // "md5Checksum": "988c28e000e84c26d552359af1ea2e1d", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "11", // "length": 135006516, // "md5Checksum": "98c59049a2df285c76ffb1c6db8f8b96", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "12", // "length": 133851895, // "md5Checksum": "51851ac0e1a115847ad36449b0015864", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "13", // "length": 115169878, // "md5Checksum": "283f8d7892baa81b510a015719ca7b0b", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "14", // "length": 107349540, // "md5Checksum": "98f3cae32b2a2e9524bc19813927542e", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "15", // "length": 102531392, // "md5Checksum": "e5645a794a8238215b2cd77acb95a078", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "16", // "length": 90354753, // "md5Checksum": "fc9b1a7b42b97a864f56b348b06095e6", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "17", // "length": 81195210, // "md5Checksum": "351f64d4f4f9ddd45b35336ad97aa6de", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "18", // "length": 78077248, // "md5Checksum": "b15d4b2d29dde9d3e4f93d1d0f2cbc9c", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "19", // "length": 59128983, // "md5Checksum": "1aacd71f30db8e561810913e0b72636d", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "20", // "length": 63025520, // "md5Checksum": "0dec9660ec1efaaf33281c0d5ea2560f", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "21", // "length": 48129895, // "md5Checksum": "2979a6085bfe28e3ad6f552f361ed74d", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "22", // "length": 51304566, // "md5Checksum": "a718acaa6135fdca8357d5bfe94211dd", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "X", // "length": 155270560, // "md5Checksum": "7e0e2e580297b7764e31dbc80c2540dd", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "Y", // "length": 59373566, // "md5Checksum": "1fa3474750af0948bdf97d5a0ee52e51", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "MT", // "length": 16569, // "md5Checksum": "c68f52674c9fb33aef52dcf399755519", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000207.1", // "length": 4262, // "md5Checksum": "f3814841f1939d3ca19072d9e89f3fd7", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000226.1", // "length": 15008, // "md5Checksum": "1c1b2cd1fccbc0a99b6a447fa24d1504", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000229.1", // "length": 19913, // "md5Checksum": "d0f40ec87de311d8e715b52e4c7062e1", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000231.1", // "length": 27386, // "md5Checksum": "ba8882ce3a1efa2080e5d29b956568a4", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000210.1", // "length": 27682, // "md5Checksum": "851106a74238044126131ce2a8e5847c", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000239.1", // "length": 33824, // "md5Checksum": "99795f15702caec4fa1c4e15f8a29c07", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000235.1", // "length": 34474, // "md5Checksum": "118a25ca210cfbcdfb6c2ebb249f9680", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000201.1", // "length": 36148, // "md5Checksum": "dfb7e7ec60ffdcb85cb359ea28454ee9", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000247.1", // "length": 36422, // "md5Checksum": "7de00226bb7df1c57276ca6baabafd15", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000245.1", // "length": 36651, // "md5Checksum": "89bc61960f37d94abf0df2d481ada0ec", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000197.1", // "length": 37175, // "md5Checksum": "6f5efdd36643a9b8c8ccad6f2f1edc7b", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000203.1", // "length": 37498, // "md5Checksum": "96358c325fe0e70bee73436e8bb14dbd", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000246.1", // "length": 38154, // "md5Checksum": "e4afcd31912af9d9c2546acf1cb23af2", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000249.1", // "length": 38502, // "md5Checksum": "1d78abec37c15fe29a275eb08d5af236", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000196.1", // "length": 38914, // "md5Checksum": "d92206d1bb4c3b4019c43c0875c06dc0", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000248.1", // "length": 39786, // "md5Checksum": "5a8e43bec9be36c7b49c84d585107776", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000244.1", // "length": 39929, // "md5Checksum": "0996b4475f353ca98bacb756ac479140", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000238.1", // "length": 39939, // "md5Checksum": "131b1efc3270cc838686b54e7c34b17b", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000202.1", // "length": 40103, // "md5Checksum": "06cbf126247d89664a4faebad130fe9c", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000234.1", // "length": 40531, // "md5Checksum": "93f998536b61a56fd0ff47322a911d4b", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000232.1", // "length": 40652, // "md5Checksum": "3e06b6741061ad93a8587531307057d8", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000206.1", // "length": 41001, // "md5Checksum": "43f69e423533e948bfae5ce1d45bd3f1", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000240.1", // "length": 41933, // "md5Checksum": "445a86173da9f237d7bcf41c6cb8cc62", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000236.1", // "length": 41934, // "md5Checksum": "fdcd739913efa1fdc64b6c0cd7016779", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000241.1", // "length": 42152, // "md5Checksum": "ef4258cdc5a45c206cea8fc3e1d858cf", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000243.1", // "length": 43341, // "md5Checksum": "cc34279a7e353136741c9fce79bc4396", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000242.1", // "length": 43523, // "md5Checksum": "2f8694fc47576bc81b5fe9e7de0ba49e", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000230.1", // "length": 43691, // "md5Checksum": "b4eb71ee878d3706246b7c1dbef69299", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000237.1", // "length": 45867, // "md5Checksum": "e0c82e7751df73f4f6d0ed30cdc853c0", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000233.1", // "length": 45941, // "md5Checksum": "7fed60298a8d62ff808b74b6ce820001", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000204.1", // "length": 81310, // "md5Checksum": "efc49c871536fa8d79cb0a06fa739722", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000198.1", // "length": 90085, // "md5Checksum": "868e7784040da90d900d2d1b667a1383", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000208.1", // "length": 92689, // "md5Checksum": "aa81be49bf3fe63a79bdc6a6f279abf6", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000191.1", // "length": 106433, // "md5Checksum": "d75b436f50a8214ee9c2a51d30b2c2cc", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000227.1", // "length": 128374, // "md5Checksum": "a4aead23f8053f2655e468bcc6ecdceb", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000228.1", // "length": 129120, // "md5Checksum": "c5a17c97e2c1a0b6a9cc5a6b064b714f", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000214.1", // "length": 137718, // "md5Checksum": "46c2032c37f2ed899eb41c0473319a69", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000221.1", // "length": 155397, // "md5Checksum": "3238fb74ea87ae857f9c7508d315babb", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000209.1", // "length": 159169, // "md5Checksum": "f40598e2a5a6b26e84a3775e0d1e2c81", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000218.1", // "length": 161147, // "md5Checksum": "1d708b54644c26c7e01c2dad5426d38c", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000220.1", // "length": 161802, // "md5Checksum": "fc35de963c57bf7648429e6454f1c9db", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000213.1", // "length": 164239, // "md5Checksum": "9d424fdcc98866650b58f004080a992a", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000211.1", // "length": 166566, // "md5Checksum": "7daaa45c66b288847b9b32b964e623d3", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000199.1", // "length": 169874, // "md5Checksum": "569af3b73522fab4b40995ae4944e78e", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000217.1", // "length": 172149, // "md5Checksum": "6d243e18dea1945fb7f2517615b8f52e", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000216.1", // "length": 172294, // "md5Checksum": "642a232d91c486ac339263820aef7fe0", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000215.1", // "length": 172545, // "md5Checksum": "5eb3b418480ae67a997957c909375a73", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000205.1", // "length": 174588, // "md5Checksum": "d22441398d99caf673e9afb9a1908ec5", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000219.1", // "length": 179198, // "md5Checksum": "f977edd13bac459cb2ed4a5457dba1b3", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000224.1", // "length": 179693, // "md5Checksum": "d5b2fc04f6b41b212a4198a07f450e20", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000223.1", // "length": 180455, // "md5Checksum": "399dfa03bf32022ab52a846f7ca35b30", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000195.1", // "length": 182896, // "md5Checksum": "5d9ec007868d517e73543b005ba48535", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000212.1", // "length": 186858, // "md5Checksum": "563531689f3dbd691331fd6c5730a88b", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000222.1", // "length": 186861, // "md5Checksum": "6fe9abac455169f50470f5a6b01d0f59", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000200.1", // "length": 187035, // "md5Checksum": "75e4c8d17cd4addf3917d1703cacaf25", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000193.1", // "length": 189789, // "md5Checksum": "dbb6e8ece0b5de29da56601613007c2a", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000194.1", // "length": 191469, // "md5Checksum": "6ac8f815bf8e845bb3031b73f812c012", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000225.1", // "length": 211173, // "md5Checksum": "63945c3e6962f28ffd469719a747e73c", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "GL000192.1", // "length": 547496, // "md5Checksum": "325ba9e808f669dfeee210fdd7b470ac", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "NC_007605", // "length": 171823, // "md5Checksum": "6743bd63b3ff2b5b8985d8933c53290a", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // }, // { // "name": "hs37d5", // "length": 35477943, // "md5Checksum": "5b6a4b3a81a2d3c134b7d14bf6ad39f1", // "uri": "ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human" // } // ], // "readGroups": [ // { // "id": "SRR068145", // "sequencingCenterName": "BI", // "description": "SRP001523", // "library": "Solexa-41478", // "predictedInsertSize": 500, // "sequencingTechnology": "ILLUMINA", // "sample": "HG01440" // } // ], // "programs": [ // { // "id": "bwa_index", // "name": "bwa", // "commandLine": "bwa index -a bwtsw $reference_fasta", // "version": "0.5.9-r16" // }, // { // "id": "bwa_aln_fastq", // "name": "bwa", // "commandLine": "bwa aln -q 15 -f $sai_file $reference_fasta $fastq_file", // "prevProgramId": "bwa_index", // "version": "0.5.9-r16" // }, // { // "id": "bwa_sam", // "name": "bwa", // "commandLine": "bwa sampe -a 1500 -r $rg_line -f $sam_file $reference_fasta $sai_file(s) $fastq_file(s)", // "prevProgramId": "bwa_aln_fastq", // "version": "0.5.9-r16" // }, // { // "id": "sam_to_fixed_bam", // "name": "samtools", // "commandLine": "samtools view -bSu $sam_file | samtools sort -n -o - samtools_nsort_tmp | samtools fixmate /dev/stdin /dev/stdout | samtools sort -o - samtools_csort_tmp | samtools fillmd -u - $reference_fasta > $fixed_bam_file", // "prevProgramId": "bwa_sam", // "version": "0.1.17 (r973:277)" // }, // { // "id": "gatk_target_interval_creator", // "name": "GenomeAnalysisTK", // "commandLine": "java $jvm_args -jar GenomeAnalysisTK.jar -T RealignerTargetCreator -R $reference_fasta -o $intervals_file -known $known_indels_file(s) ", // "prevProgramId": "sam_to_fixed_bam", // "version": "1.2-29-g0acaf2d" // }, // { // "id": "bam_realignment_around_known_indels", // "name": "GenomeAnalysisTK", // "commandLine": "java $jvm_args -jar GenomeAnalysisTK.jar -T IndelRealigner -R $reference_fasta -I $bam_file -o $realigned_bam_file -targetIntervals $intervals_file -known $known_indels_file(s) -LOD 0.4 -model KNOWNS_ONLY -compress 0 --disable_bam_indexing", // "prevProgramId": "gatk_target_interval_creator", // "version": "1.2-29-g0acaf2d" // }, // { // "id": "bam_count_covariates", // "name": "GenomeAnalysisTK", // "commandLine": "java $jvm_args -jar GenomeAnalysisTK.jar -T CountCovariates -R $reference_fasta -I $bam_file -recalFile $bam_file.recal_data.csv -knownSites $known_sites_file(s) -l INFO -L '1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;X;Y;MT' -cov ReadGroupCovariate -cov QualityScoreCovariate -cov CycleCovariate -cov DinucCovariate", // "prevProgramId": "bam_realignment_around_known_indels", // "version": "1.2-29-g0acaf2d" // }, // { // "id": "bam_recalibrate_quality_scores", // "name": "GenomeAnalysisTK", // "commandLine": "java $jvm_args -jar GenomeAnalysisTK.jar -T TableRecalibration -R $reference_fasta -recalFile $bam_file.recal_data.csv -I $bam_file -o $recalibrated_bam_file -l INFO -compress 0 --disable_bam_indexing", // "prevProgramId": "bam_count_covariates", // "version": "1.2-29-g0acaf2d" // }, // { // "id": "bam_calculate_bq", // "name": "samtools", // "commandLine": "samtools calmd -Erb $bam_file $reference_fasta > $bq_bam_file", // "prevProgramId": "bam_recalibrate_quality_scores", // "version": "0.1.17 (r973:277)" // }, // { // "id": "bam_merge", // "name": "picard", // "commandLine": "java $jvm_args -jar MergeSamFiles.jar INPUT=$bam_file(s) OUTPUT=$merged_bam VALIDATION_STRINGENCY=SILENT", // "prevProgramId": "bam_calculate_bq", // "version": "1.53" // }, // { // "id": "bam_mark_duplicates", // "name": "picard", // "commandLine": "java $jvm_args -jar MarkDuplicates.jar INPUT=$bam_file OUTPUT=$markdup_bam_file ASSUME_SORTED=TRUE METRICS_FILE=/dev/null VALIDATION_STRINGENCY=SILENT", // "prevProgramId": "bam_merge", // "version": "1.53" // }, // { // "id": "bam_merge.1", // "name": "picard", // "commandLine": "java $jvm_args -jar MergeSamFiles.jar INPUT=$bam_file(s) OUTPUT=$merged_bam VALIDATION_STRINGENCY=SILENT", // "prevProgramId": "bam_mark_duplicates", // "version": "1.53" // } // ], // "comments": [ // "$known_indels_file(s) = ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_mapping_resources/ALL.wgs.indels_mills_devine_hg19_leftAligned_collapsed_double_hit.indels.sites.vcf.gz", // "$known_indels_file(s) .= ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_mapping_resources/ALL.wgs.low_coverage_vqsr.20101123.indels.sites.vcf.gz", // "$known_sites_file(s) = ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_mapping_resources/ALL.wgs.dbsnp.build135.snps.sites.vcf.gz" // ] // } // ] // }; // // var sequenceNames = igv.decodeGa4ghReadset(sampleJson); // ok(sequenceNames); // // ok(sequenceNames.indexOf("MT") > 0); // // // equal(101, alignment.lengthOnRef); // // equal(true, alignment.strand); // // //}); }
'use strict'; //Setting up route angular.module('dashboards').config(['$stateProvider', function($stateProvider) { // Dashboards state routing $stateProvider. state('listDashboards', { url: '/dashboards', templateUrl: 'modules/dashboards/views/list-dashboards.client.view.html' }). state('createDashboard', { url: '/dashboards/create', templateUrl: 'modules/dashboards/views/create-dashboard.client.view.html' }). state('viewDashboard', { url: '/dashboards/:dashboardId', templateUrl: 'modules/dashboards/views/view-dashboard.client.view.html' }). state('editDashboard', { url: '/dashboards/:dashboardId/edit', templateUrl: 'modules/dashboards/views/edit-dashboard.client.view.html' }); } ]);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TreeTableHeader = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); var _DomHandler = _interopRequireDefault(require("../utils/DomHandler")); var _InputText = require("../inputtext/InputText"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var TreeTableHeader = /*#__PURE__*/ function (_Component) { _inherits(TreeTableHeader, _Component); function TreeTableHeader(props) { var _this; _classCallCheck(this, TreeTableHeader); _this = _possibleConstructorReturn(this, _getPrototypeOf(TreeTableHeader).call(this, props)); _this.onHeaderMouseDown = _this.onHeaderMouseDown.bind(_assertThisInitialized(_this)); _this.onFilterInput = _this.onFilterInput.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTableHeader, [{ key: "onHeaderClick", value: function onHeaderClick(event, column) { if (column.props.sortable) { var targetNode = event.target; if (_DomHandler.default.hasClass(targetNode, 'p-sortable-column') || _DomHandler.default.hasClass(targetNode, 'p-column-title') || _DomHandler.default.hasClass(targetNode, 'p-sortable-column-icon') || _DomHandler.default.hasClass(targetNode.parentElement, 'p-sortable-column-icon')) { this.props.onSort({ originalEvent: event, sortField: column.props.field, sortFunction: column.props.sortFunction, sortable: column.props.sortable }); _DomHandler.default.clearSelection(); } } } }, { key: "onHeaderMouseDown", value: function onHeaderMouseDown(event) { if (this.props.reorderableColumns) { if (event.target.nodeName !== 'INPUT') event.currentTarget.draggable = true;else if (event.target.nodeName === 'INPUT') event.currentTarget.draggable = false; } } }, { key: "onHeaderKeyDown", value: function onHeaderKeyDown(event, column) { if (event.key === 'Enter') { this.onHeaderClick(event, column); event.preventDefault(); } } }, { key: "getMultiSortMetaData", value: function getMultiSortMetaData(column) { if (this.props.multiSortMeta) { for (var i = 0; i < this.props.multiSortMeta.length; i++) { if (this.props.multiSortMeta[i].field === column.props.field) { return this.props.multiSortMeta[i]; } } } return null; } }, { key: "onResizerMouseDown", value: function onResizerMouseDown(event, column) { if (this.props.resizableColumns && this.props.onResizeStart) { this.props.onResizeStart({ originalEvent: event, columnEl: event.target.parentElement, column: column }); } } }, { key: "onFilterInput", value: function onFilterInput(e, column) { var _this2 = this; if (column.props.filter && this.props.onFilter) { if (this.filterTimeout) { clearTimeout(this.filterTimeout); } var filterValue = e.target.value; this.filterTimeout = setTimeout(function () { _this2.props.onFilter({ value: filterValue, field: column.props.field, matchMode: column.props.filterMatchMode }); _this2.filterTimeout = null; }, this.filterDelay); } } }, { key: "renderSortIcon", value: function renderSortIcon(column, sorted, sortOrder) { if (column.props.sortable) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-down' : 'pi-sort-up' : 'pi-sort'; var sortIconClassName = (0, _classnames.default)('p-sortable-column-icon', 'pi pi-fw', sortIcon); return _react.default.createElement("span", { className: sortIconClassName }); } else { return null; } } }, { key: "renderResizer", value: function renderResizer(column) { var _this3 = this; if (this.props.resizableColumns) { return _react.default.createElement("span", { className: "p-column-resizer p-clickable", onMouseDown: function onMouseDown(e) { return _this3.onResizerMouseDown(e, column); } }); } else { return null; } } }, { key: "renderHeaderCell", value: function renderHeaderCell(column, index) { var _this4 = this; var multiSortMetaData = this.getMultiSortMetaData(column); var singleSorted = column.props.field === this.props.sortField; var multipleSorted = multiSortMetaData !== null; var sorted = column.props.sortable && (singleSorted || multipleSorted); var sortOrder = 0; var filterElement; if (singleSorted) sortOrder = this.props.sortOrder;else if (multipleSorted) sortOrder = multiSortMetaData.order; var sortIconElement = this.renderSortIcon(column, sorted, sortOrder); var className = (0, _classnames.default)(column.props.headerClassName || column.props.className, { 'p-sortable-column': column.props.sortable, 'p-highlight': sorted, 'p-resizable-column': this.props.resizableColumns }); if (column.props.filter) { filterElement = column.props.filterElement || _react.default.createElement(_InputText.InputText, { onInput: function onInput(e) { return _this4.onFilterInput(e, column); }, type: this.props.filterType, defaultValue: this.props.filters && this.props.filters[this.props.field] ? this.props.filters[this.props.field].value : null, className: "p-column-filter", placeholder: column.props.filterPlaceholder, maxLength: column.props.filterMaxLength }); } var resizer = this.renderResizer(column); return _react.default.createElement("th", { key: column.field || index, className: className, style: column.props.headerStyle || column.props.style, tabIndex: column.props.sortable ? this.props.tabIndex : null, onClick: function onClick(e) { return _this4.onHeaderClick(e, column); }, onMouseDown: this.onHeaderMouseDown, onKeyDown: function onKeyDown(e) { return _this4.onHeaderKeyDown(e, column); }, rowSpan: column.props.rowSpan, colSpan: column.props.colSpan, onDragStart: this.props.onDragStart, onDragOver: this.props.onDragOver, onDragLeave: this.props.onDragLeave, onDrop: this.props.onDrop }, resizer, _react.default.createElement("span", { className: "p-column-title" }, column.props.header), sortIconElement, filterElement); } }, { key: "renderHeaderRow", value: function renderHeaderRow(row, index) { var _this5 = this; var rowColumns = _react.default.Children.toArray(row.props.children); var rowHeaderCells = rowColumns.map(function (col, index) { return _this5.renderHeaderCell(col, index); }); return _react.default.createElement("tr", { key: index }, rowHeaderCells); } }, { key: "renderColumnGroup", value: function renderColumnGroup() { var _this6 = this; var rows = _react.default.Children.toArray(this.props.columnGroup.props.children); return rows.map(function (row, i) { return _this6.renderHeaderRow(row, i); }); } }, { key: "renderColumns", value: function renderColumns(columns) { var _this7 = this; if (columns) { var headerCells = columns.map(function (col, index) { return _this7.renderHeaderCell(col, index); }); return _react.default.createElement("tr", null, headerCells); } else { return null; } } }, { key: "render", value: function render() { var content = this.props.columnGroup ? this.renderColumnGroup() : this.renderColumns(this.props.columns); return _react.default.createElement("thead", { className: "p-treetable-thead" }, content); } }]); return TreeTableHeader; }(_react.Component); exports.TreeTableHeader = TreeTableHeader; _defineProperty(TreeTableHeader, "defaultProps", { columns: null, columnGroup: null, sortField: null, sortOrder: null, multiSortMeta: null, resizableColumns: false, reorderableColumns: false, onSort: null, onResizeStart: null, onDragStart: null, onDragOver: null, onDragLeave: null, onDrop: null, onFilter: null }); _defineProperty(TreeTableHeader, "propTypes", { columns: _propTypes.default.array, columnGroup: _propTypes.default.any, sortField: _propTypes.default.string, sortOrder: _propTypes.default.number, multiSortMeta: _propTypes.default.array, resizableColumns: _propTypes.default.bool, reorderableColumns: _propTypes.default.bool, onSort: _propTypes.default.func, onResizeStart: _propTypes.default.func, onDragStart: _propTypes.default.func, onDragOver: _propTypes.default.func, onDragLeave: _propTypes.default.func, onDrop: _propTypes.default.func, onFilter: _propTypes.default.func });
tinyMCE.addI18n('zh-cn.simple',{cleanup_desc:"\u6e05\u9664\u65e0\u7528\u4ee3\u7801",redo_desc:"\u6062\u590d(Ctrl Y)",undo_desc:"\u64a4\u9500(Ctrl Z)",numlist_desc:"\u7f16\u53f7\u5217\u8868",bullist_desc:"\u9879\u76ee\u5217\u8868",striketrough_desc:"\u5220\u9664\u7ebf",underline_desc:"\u4e0b\u5212\u7ebf(Ctrl U)",italic_desc:"\u659c\u4f53(Ctrl I)",bold_desc:"\u7c97\u4f53(Ctrl B)"});
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("popper.js")); else if(typeof define === 'function' && define.amd) define(["popper.js"], factory); else if(typeof exports === 'object') exports["cytoscapePopper"] = factory(require("popper.js")); else root["cytoscapePopper"] = factory(root["Popper"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_8__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 7); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Simple, internal Object.assign() polyfill for options objects etc. module.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) { for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { srcs[_key - 1] = arguments[_key]; } srcs.forEach(function (src) { if (src !== null && src !== undefined) { Object.keys(src).forEach(function (k) { return tgt[k] = src[k]; }); } }); return tgt; }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _require = __webpack_require__(5), getBoundingBox = _require.getBoundingBox; // Create a popper reference object // https://popper.js.org/popper-documentation.html#referenceObject function getRef(target, opts) { var renderedDimensions = opts.renderedDimensions; //Define popper reference object and cy reference object var refObject = { getBoundingClientRect: function getBoundingClientRect() { return getBoundingBox(target, opts); }, get clientWidth() { return renderedDimensions(target).w; }, get clientHeight() { return renderedDimensions(target).h; } }; return refObject; } module.exports = { getRef: getRef }; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assign = __webpack_require__(0); var _require = __webpack_require__(1), getRef = _require.getRef; var _require2 = __webpack_require__(6), getContent = _require2.getContent; var popperDefaults = {}; //Fix Popper.js webpack import conflict (Use .default if using webpack) var Popper = __webpack_require__(8); var EsmWebpackPopper = Popper.default; if (EsmWebpackPopper != null && EsmWebpackPopper.Defaults != null) { Popper = Popper.default; } // Create a new popper object for a core or element target function getPopper(target, opts) { var refObject = getRef(target, opts); var content = getContent(target, opts.content); var popperOpts = assign({}, popperDefaults, opts.popper); return new Popper(refObject, content, popperOpts); } module.exports = { getPopper: getPopper }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assign = __webpack_require__(0); var _require = __webpack_require__(2), getPopper = _require.getPopper; var _require2 = __webpack_require__(1), getRef = _require2.getRef; function popper(opts) { checkForWarning(this); return getPopper(this[0], createOptionsObject(this[0], opts)); } function popperRef(opts) { checkForWarning(this); return getRef(this[0], createOptionsObject(this[0], opts)); } function createOptionsObject(target, opts) { var renderedDimensions = function renderedDimensions(el) { return el.isNode() ? { w: el.renderedWidth(), h: el.renderedHeight() } : { w: 3, h: 3 }; }; var renderedPosition = function renderedPosition(el) { return el.isNode() ? getRenderedCenter(el, renderedDimensions) : getRenderedMidpoint(el); }; var popper = {}; var cy = target.cy(); var defaults = { renderedDimensions: renderedDimensions, renderedPosition: renderedPosition, popper: popper, cy: cy }; return assign({}, defaults, opts); } //Get the rendered center function getRenderedCenter(target, renderedDimensions) { var pos = target.renderedPosition(); var dimensions = renderedDimensions(target); var offsetX = dimensions.w / 2; var offsetY = dimensions.h / 2; return { x: pos.x - offsetX, y: pos.y - offsetY }; } //Get the rendered position of the midpoint function getRenderedMidpoint(target) { var p = target.midpoint(); var pan = target.cy().pan(); var zoom = target.cy().zoom(); return { x: p.x * zoom + pan.x, y: p.y * zoom + pan.y }; } //Warn user about misuse of the plugin function checkForWarning(elements) { /* eslint-disable no-console */ //Popper.js Should only be used on 1 element if (elements.length > 1) { console.warn("Popper.js Extension should only be used on one element."); console.warn("Ignoring all subsequent elements"); } /* eslint-enable */ } module.exports = { popper: popper, popperRef: popperRef }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assign = __webpack_require__(0); var _require = __webpack_require__(2), getPopper = _require.getPopper; var _require2 = __webpack_require__(1), getRef = _require2.getRef; function popper(opts) { return getPopper(this, createOptionsObject(this, opts)); } function popperRef(opts) { return getRef(this, createOptionsObject(this, opts)); } //Create a options object with required default values function createOptionsObject(target, opts) { var defaults = { boundingBox: { top: 0, left: 0, right: 0, bottom: 0, w: 3, h: 3 }, renderedDimensions: function renderedDimensions() { return { w: 3, h: 3 }; }, redneredPosition: function redneredPosition() { return { x: 0, y: 0 }; }, popper: {}, cy: target }; return assign({}, defaults, opts); } module.exports = { popper: popper, popperRef: popperRef }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function getBoundingBox(target, opts) { var renderedPosition = opts.renderedPosition, cy = opts.cy, renderedDimensions = opts.renderedDimensions; var offset = cy.container().getBoundingClientRect(); var dims = renderedDimensions(target); var pos = renderedPosition(target); return { top: pos.y + offset.top, left: pos.x + offset.left, right: pos.x + dims.w + offset.left, bottom: pos.y + dims.h + offset.top, width: dims.w, height: dims.h }; } module.exports = { getBoundingBox: getBoundingBox }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function getContent(target, content) { var contentObject = null; if (typeof content === "function") { //Execute function if user opted for a dyanamic target contentObject = content(target); } else if (content instanceof HTMLElement) { //Target option is an HTML element return content; } else { throw new Error("Can not create popper from 'target' with unknown type"); } // Check validity of parsed target if (contentObject === null) { throw new Error("No 'target' specified to create popper"); } else { return contentObject; } } module.exports = { getContent: getContent }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* global cytoscape */ var coreImpl = __webpack_require__(4); var collectionImpl = __webpack_require__(3); // registers the extension on a cytoscape lib ref var register = function register(cytoscape) { if (!cytoscape) { return; } // can't register if cytoscape unspecified // register with cytoscape.js cytoscape('core', 'popper', coreImpl.popper); //Cytoscape Core cytoscape('collection', 'popper', collectionImpl.popper); //Cytoscape Collections cytoscape('core', 'popperRef', coreImpl.popperRef); //Cytoscape Core for References cytoscape('collection', 'popperRef', collectionImpl.popperRef); //Cytoscape Collections for References }; if (typeof cytoscape !== 'undefined') { // expose to global cytoscape (i.e. window.cytoscape) register(cytoscape); } module.exports = register; /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_8__; /***/ }) /******/ ]); });
/* * xpath.js * * An XPath 1.0 library for JavaScript. * * Cameron McCormack <cam (at) mcc.id.au> * * This work is licensed under the Creative Commons Attribution-ShareAlike * License. To view a copy of this license, visit * * http://creativecommons.org/licenses/by-sa/2.0/ * * or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, * California 94305, USA. * * Revision 20: April 26, 2011 * Fixed a typo resulting in FIRST_ORDERED_NODE_TYPE results being wrong, * thanks to <shi_a009 (at) hotmail.com>. * * Revision 19: November 29, 2005 * Nodesets now store their nodes in a height balanced tree, increasing * performance for the common case of selecting nodes in document order, * thanks to S閎astien Cramatte <contact (at) zeninteractif.com>. * AVL tree code adapted from Raimund Neumann <rnova (at) gmx.net>. * * Revision 18: October 27, 2005 * DOM 3 XPath support. Caveats: * - namespace prefixes aren't resolved in XPathEvaluator.createExpression, * but in XPathExpression.evaluate. * - XPathResult.invalidIteratorState is not implemented. * * Revision 17: October 25, 2005 * Some core XPath function fixes and a patch to avoid crashing certain * versions of MSXML in PathExpr.prototype.getOwnerElement, thanks to * S閎astien Cramatte <contact (at) zeninteractif.com>. * * Revision 16: September 22, 2005 * Workarounds for some IE 5.5 deficiencies. * Fixed problem with prefix node tests on attribute nodes. * * Revision 15: May 21, 2005 * Fixed problem with QName node tests on elements with an xmlns="...". * * Revision 14: May 19, 2005 * Fixed QName node tests on attribute node regression. * * Revision 13: May 3, 2005 * Node tests are case insensitive now if working in an HTML DOM. * * Revision 12: April 26, 2005 * Updated licence. Slight code changes to enable use of Dean * Edwards' script compression, http://dean.edwards.name/packer/ . * * Revision 11: April 23, 2005 * Fixed bug with 'and' and 'or' operators, fix thanks to * Sandy McArthur <sandy (at) mcarthur.org>. * * Revision 10: April 15, 2005 * Added support for a virtual root node, supposedly helpful for * implementing XForms. Fixed problem with QName node tests and * the parent axis. * * Revision 9: March 17, 2005 * Namespace resolver tweaked so using the document node as the context * for namespace lookups is equivalent to using the document element. * * Revision 8: February 13, 2005 * Handle implicit declaration of 'xmlns' namespace prefix. * Fixed bug when comparing nodesets. * Instance data can now be associated with a FunctionResolver, and * workaround for MSXML not supporting 'localName' and 'getElementById', * thanks to Grant Gongaware. * Fix a few problems when the context node is the root node. * * Revision 7: February 11, 2005 * Default namespace resolver fix from Grant Gongaware * <grant (at) gongaware.com>. * * Revision 6: February 10, 2005 * Fixed bug in 'number' function. * * Revision 5: February 9, 2005 * Fixed bug where text nodes not getting converted to string values. * * Revision 4: January 21, 2005 * Bug in 'name' function, fix thanks to Bill Edney. * Fixed incorrect processing of namespace nodes. * Fixed NamespaceResolver to resolve 'xml' namespace. * Implemented union '|' operator. * * Revision 3: January 14, 2005 * Fixed bug with nodeset comparisons, bug lexing < and >. * * Revision 2: October 26, 2004 * QName node test namespace handling fixed. Few other bug fixes. * * Revision 1: August 13, 2004 * Bug fixes from William J. Edney <bedney (at) technicalpursuit.com>. * Added minimal licence. * * Initial version: June 14, 2004 */ // XPathParser /////////////////////////////////////////////////////////////// XPathParser.prototype = new Object(); XPathParser.prototype.constructor = XPathParser; XPathParser.superclass = Object.prototype; function XPathParser() { this.init(); } XPathParser.prototype.init = function() { this.reduceActions = []; this.reduceActions[3] = function(rhs) { return new OrOperation(rhs[0], rhs[2]); }; this.reduceActions[5] = function(rhs) { return new AndOperation(rhs[0], rhs[2]); }; this.reduceActions[7] = function(rhs) { return new EqualsOperation(rhs[0], rhs[2]); }; this.reduceActions[8] = function(rhs) { return new NotEqualOperation(rhs[0], rhs[2]); }; this.reduceActions[10] = function(rhs) { return new LessThanOperation(rhs[0], rhs[2]); }; this.reduceActions[11] = function(rhs) { return new GreaterThanOperation(rhs[0], rhs[2]); }; this.reduceActions[12] = function(rhs) { return new LessThanOrEqualOperation(rhs[0], rhs[2]); }; this.reduceActions[13] = function(rhs) { return new GreaterThanOrEqualOperation(rhs[0], rhs[2]); }; this.reduceActions[15] = function(rhs) { return new PlusOperation(rhs[0], rhs[2]); }; this.reduceActions[16] = function(rhs) { return new MinusOperation(rhs[0], rhs[2]); }; this.reduceActions[18] = function(rhs) { return new MultiplyOperation(rhs[0], rhs[2]); }; this.reduceActions[19] = function(rhs) { return new DivOperation(rhs[0], rhs[2]); }; this.reduceActions[20] = function(rhs) { return new ModOperation(rhs[0], rhs[2]); }; this.reduceActions[22] = function(rhs) { return new UnaryMinusOperation(rhs[1]); }; this.reduceActions[24] = function(rhs) { return new BarOperation(rhs[0], rhs[2]); }; this.reduceActions[25] = function(rhs) { return new PathExpr(undefined, undefined, rhs[0]); }; this.reduceActions[27] = function(rhs) { rhs[0].locationPath = rhs[2]; return rhs[0]; }; this.reduceActions[28] = function(rhs) { rhs[0].locationPath = rhs[2]; rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), [])); return rhs[0]; }; this.reduceActions[29] = function(rhs) { return new PathExpr(rhs[0], [], undefined); }; this.reduceActions[30] = function(rhs) { if (Utilities.instance_of(rhs[0], PathExpr)) { if (rhs[0].filterPredicates == undefined) { rhs[0].filterPredicates = []; } rhs[0].filterPredicates.push(rhs[1]); return rhs[0]; } else { return new PathExpr(rhs[0], [rhs[1]], undefined); } }; this.reduceActions[32] = function(rhs) { return rhs[1]; }; this.reduceActions[33] = function(rhs) { return new XString(rhs[0]); }; this.reduceActions[34] = function(rhs) { return new XNumber(rhs[0]); }; this.reduceActions[36] = function(rhs) { return new FunctionCall(rhs[0], []); }; this.reduceActions[37] = function(rhs) { return new FunctionCall(rhs[0], rhs[2]); }; this.reduceActions[38] = function(rhs) { return [ rhs[0] ]; }; this.reduceActions[39] = function(rhs) { rhs[2].unshift(rhs[0]); return rhs[2]; }; this.reduceActions[43] = function(rhs) { return new LocationPath(true, []); }; this.reduceActions[44] = function(rhs) { rhs[1].absolute = true; return rhs[1]; }; this.reduceActions[46] = function(rhs) { return new LocationPath(false, [ rhs[0] ]); }; this.reduceActions[47] = function(rhs) { rhs[0].steps.push(rhs[2]); return rhs[0]; }; this.reduceActions[49] = function(rhs) { return new Step(rhs[0], rhs[1], []); }; this.reduceActions[50] = function(rhs) { return new Step(Step.CHILD, rhs[0], []); }; this.reduceActions[51] = function(rhs) { return new Step(rhs[0], rhs[1], rhs[2]); }; this.reduceActions[52] = function(rhs) { return new Step(Step.CHILD, rhs[0], rhs[1]); }; this.reduceActions[54] = function(rhs) { return [ rhs[0] ]; }; this.reduceActions[55] = function(rhs) { rhs[1].unshift(rhs[0]); return rhs[1]; }; this.reduceActions[56] = function(rhs) { if (rhs[0] == "ancestor") { return Step.ANCESTOR; } else if (rhs[0] == "ancestor-or-self") { return Step.ANCESTORORSELF; } else if (rhs[0] == "attribute") { return Step.ATTRIBUTE; } else if (rhs[0] == "child") { return Step.CHILD; } else if (rhs[0] == "descendant") { return Step.DESCENDANT; } else if (rhs[0] == "descendant-or-self") { return Step.DESCENDANTORSELF; } else if (rhs[0] == "following") { return Step.FOLLOWING; } else if (rhs[0] == "following-sibling") { return Step.FOLLOWINGSIBLING; } else if (rhs[0] == "namespace") { return Step.NAMESPACE; } else if (rhs[0] == "parent") { return Step.PARENT; } else if (rhs[0] == "preceding") { return Step.PRECEDING; } else if (rhs[0] == "preceding-sibling") { return Step.PRECEDINGSIBLING; } else if (rhs[0] == "self") { return Step.SELF; } return -1; }; this.reduceActions[57] = function(rhs) { return Step.ATTRIBUTE; }; this.reduceActions[59] = function(rhs) { if (rhs[0] == "comment") { return new NodeTest(NodeTest.COMMENT, undefined); } else if (rhs[0] == "text") { return new NodeTest(NodeTest.TEXT, undefined); } else if (rhs[0] == "processing-instruction") { return new NodeTest(NodeTest.PI, undefined); } else if (rhs[0] == "node") { return new NodeTest(NodeTest.NODE, undefined); } return new NodeTest(-1, undefined); }; this.reduceActions[60] = function(rhs) { return new NodeTest(NodeTest.PI, rhs[2]); }; this.reduceActions[61] = function(rhs) { return rhs[1]; }; this.reduceActions[63] = function(rhs) { rhs[1].absolute = true; rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), [])); return rhs[1]; }; this.reduceActions[64] = function(rhs) { rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), [])); rhs[0].steps.push(rhs[2]); return rhs[0]; }; this.reduceActions[65] = function(rhs) { return new Step(Step.SELF, new NodeTest(NodeTest.NODE, undefined), []); }; this.reduceActions[66] = function(rhs) { return new Step(Step.PARENT, new NodeTest(NodeTest.NODE, undefined), []); }; this.reduceActions[67] = function(rhs) { return new VariableReference(rhs[1]); }; this.reduceActions[68] = function(rhs) { return new NodeTest(NodeTest.NAMETESTANY, undefined); }; this.reduceActions[69] = function(rhs) { var prefix = rhs[0].substring(0, rhs[0].indexOf(":")); return new NodeTest(NodeTest.NAMETESTPREFIXANY, prefix); }; this.reduceActions[70] = function(rhs) { return new NodeTest(NodeTest.NAMETESTQNAME, rhs[0]); }; }; XPathParser.actionTable = [ " s s sssssssss s ss s ss", " s ", "r rrrrrrrrr rrrrrrr rr r ", " rrrrr ", " s s sssssssss s ss s ss", "rs rrrrrrrr s sssssrrrrrr rrs rs ", " s s sssssssss s ss s ss", " s ", " s ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " s ", " s ", " s s sssss s s ", "r rrrrrrrrr rrrrrrr rr r ", "a ", "r s rr r ", "r sr rr r ", "r s rr s rr r ", "r rssrr rss rr r ", "r rrrrr rrrss rr r ", "r rrrrrsss rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrrs rr r ", "r rrrrrrrr rrrrrr rr r ", "r rrrrrrrr rrrrrr rr r ", "r srrrrrrrr rrrrrrs rr sr ", "r srrrrrrrr rrrrrrs rr r ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrr rrrrrr rr r ", "r rrrrrrrr rrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", " sssss ", "r rrrrrrrrr rrrrrrr rr sr ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " s ", "r srrrrrrrr rrrrrrs rr r ", "r rrrrrrrr rrrrr rr r ", " s ", " s ", " rrrrr ", " s s sssssssss s sss s ss", "r srrrrrrrr rrrrrrs rr r ", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss ss s ss", " s s sssssssss s ss s ss", " s s sssss s s ", " s s sssss s s ", "r rrrrrrrrr rrrrrrr rr rr ", " s s sssss s s ", " s s sssss s s ", "r rrrrrrrrr rrrrrrr rr sr ", "r rrrrrrrrr rrrrrrr rr sr ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr rr ", " s ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " rr ", " s ", " rs ", "r sr rr r ", "r s rr s rr r ", "r rssrr rss rr r ", "r rssrr rss rr r ", "r rrrrr rrrss rr r ", "r rrrrr rrrss rr r ", "r rrrrr rrrss rr r ", "r rrrrr rrrss rr r ", "r rrrrrsss rrrrr rr r ", "r rrrrrsss rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrrr rr r ", " r ", " s ", "r srrrrrrrr rrrrrrs rr r ", "r srrrrrrrr rrrrrrs rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " s s sssssssss s ss s ss", "r rrrrrrrrr rrrrrrr rr rr ", " r " ]; XPathParser.actionTableNumber = [ " 1 0 /.-,+*)(' & %$ # \"!", " J ", "a aaaaaaaaa aaaaaaa aa a ", " YYYYY ", " 1 0 /.-,+*)(' & %$ # \"!", "K1 KKKKKKKK . +*)('KKKKKK KK# K\" ", " 1 0 /.-,+*)(' & %$ # \"!", " N ", " O ", "e eeeeeeeee eeeeeee ee ee ", "f fffffffff fffffff ff ff ", "d ddddddddd ddddddd dd dd ", "B BBBBBBBBB BBBBBBB BB BB ", "A AAAAAAAAA AAAAAAA AA AA ", " P ", " Q ", " 1 . +*)(' # \" ", "b bbbbbbbbb bbbbbbb bb b ", " ", "! S !! ! ", "\" T\" \"\" \" ", "$ V $$ U $$ $ ", "& &ZY&& &XW && & ", ") ))))) )))\\[ )) ) ", ". ....._^] ..... .. . ", "1 11111111 11111 11 1 ", "5 55555555 55555` 55 5 ", "7 77777777 777777 77 7 ", "9 99999999 999999 99 9 ", ": c:::::::: ::::::b :: a: ", "I fIIIIIIII IIIIIIe II I ", "= ========= ======= == == ", "? ????????? ??????? ?? ?? ", "C CCCCCCCCC CCCCCCC CC CC ", "J JJJJJJJJ JJJJJJ JJ J ", "M MMMMMMMM MMMMMM MM M ", "N NNNNNNNNN NNNNNNN NN N ", "P PPPPPPPPP PPPPPPP PP P ", " +*)(' ", "R RRRRRRRRR RRRRRRR RR aR ", "U UUUUUUUUU UUUUUUU UU U ", "Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ", "c ccccccccc ccccccc cc cc ", " j ", "L fLLLLLLLL LLLLLLe LL L ", "6 66666666 66666 66 6 ", " k ", " l ", " XXXXX ", " 1 0 /.-,+*)(' & %$m # \"!", "_ f________ ______e __ _ ", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 . +*)(' # \" ", " 1 . +*)(' # \" ", "> >>>>>>>>> >>>>>>> >> >> ", " 1 . +*)(' # \" ", " 1 . +*)(' # \" ", "Q QQQQQQQQQ QQQQQQQ QQ aQ ", "V VVVVVVVVV VVVVVVV VV aV ", "T TTTTTTTTT TTTTTTT TT T ", "@ @@@@@@@@@ @@@@@@@ @@ @@ ", " \x87 ", "[ [[[[[[[[[ [[[[[[[ [[ [[ ", "D DDDDDDDDD DDDDDDD DD DD ", " HH ", " \x88 ", " F\x89 ", "# T# ## # ", "% V %% U %% % ", "' 'ZY'' 'XW '' ' ", "( (ZY(( (XW (( ( ", "+ +++++ +++\\[ ++ + ", "* ***** ***\\[ ** * ", "- ----- ---\\[ -- - ", ", ,,,,, ,,,\\[ ,, , ", "0 00000_^] 00000 00 0 ", "/ /////_^] ///// // / ", "2 22222222 22222 22 2 ", "3 33333333 33333 33 3 ", "4 44444444 44444 44 4 ", "8 88888888 888888 88 8 ", " ^ ", " \x8a ", "; f;;;;;;;; ;;;;;;e ;; ; ", "< f<<<<<<<< <<<<<<e << < ", "O OOOOOOOOO OOOOOOO OO O ", "` ````````` ``````` `` ` ", "S SSSSSSSSS SSSSSSS SS S ", "W WWWWWWWWW WWWWWWW WW W ", "\\ \\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\ \\\\ \\\\ ", "E EEEEEEEEE EEEEEEE EE EE ", " 1 0 /.-,+*)(' & %$ # \"!", "] ]]]]]]]]] ]]]]]]] ]] ]] ", " G " ]; XPathParser.gotoTable = [ "3456789:;<=>?@ AB CDEFGH IJ ", " ", " ", " ", "L456789:;<=>?@ AB CDEFGH IJ ", " M EFGH IJ ", " N;<=>?@ AB CDEFGH IJ ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " S EFGH IJ ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " e ", " ", " ", " ", " ", " ", " ", " ", " ", " h J ", " i j ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "o456789:;<=>?@ ABpqCDEFGH IJ ", " ", " r6789:;<=>?@ AB CDEFGH IJ ", " s789:;<=>?@ AB CDEFGH IJ ", " t89:;<=>?@ AB CDEFGH IJ ", " u89:;<=>?@ AB CDEFGH IJ ", " v9:;<=>?@ AB CDEFGH IJ ", " w9:;<=>?@ AB CDEFGH IJ ", " x9:;<=>?@ AB CDEFGH IJ ", " y9:;<=>?@ AB CDEFGH IJ ", " z:;<=>?@ AB CDEFGH IJ ", " {:;<=>?@ AB CDEFGH IJ ", " |;<=>?@ AB CDEFGH IJ ", " };<=>?@ AB CDEFGH IJ ", " ~;<=>?@ AB CDEFGH IJ ", " \x7f=>?@ AB CDEFGH IJ ", "\x80456789:;<=>?@ AB CDEFGH IJ\x81", " \x82 EFGH IJ ", " \x83 EFGH IJ ", " ", " \x84 GH IJ ", " \x85 GH IJ ", " i \x86 ", " i \x87 ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "o456789:;<=>?@ AB\x8cqCDEFGH IJ ", " ", " " ]; XPathParser.productions = [ [1, 1, 2], [2, 1, 3], [3, 1, 4], [3, 3, 3, -9, 4], [4, 1, 5], [4, 3, 4, -8, 5], [5, 1, 6], [5, 3, 5, -22, 6], [5, 3, 5, -5, 6], [6, 1, 7], [6, 3, 6, -23, 7], [6, 3, 6, -24, 7], [6, 3, 6, -6, 7], [6, 3, 6, -7, 7], [7, 1, 8], [7, 3, 7, -25, 8], [7, 3, 7, -26, 8], [8, 1, 9], [8, 3, 8, -12, 9], [8, 3, 8, -11, 9], [8, 3, 8, -10, 9], [9, 1, 10], [9, 2, -26, 9], [10, 1, 11], [10, 3, 10, -27, 11], [11, 1, 12], [11, 1, 13], [11, 3, 13, -28, 14], [11, 3, 13, -4, 14], [13, 1, 15], [13, 2, 13, 16], [15, 1, 17], [15, 3, -29, 2, -30], [15, 1, -15], [15, 1, -16], [15, 1, 18], [18, 3, -13, -29, -30], [18, 4, -13, -29, 19, -30], [19, 1, 20], [19, 3, 20, -31, 19], [20, 1, 2], [12, 1, 14], [12, 1, 21], [21, 1, -28], [21, 2, -28, 14], [21, 1, 22], [14, 1, 23], [14, 3, 14, -28, 23], [14, 1, 24], [23, 2, 25, 26], [23, 1, 26], [23, 3, 25, 26, 27], [23, 2, 26, 27], [23, 1, 28], [27, 1, 16], [27, 2, 16, 27], [25, 2, -14, -3], [25, 1, -32], [26, 1, 29], [26, 3, -20, -29, -30], [26, 4, -21, -29, -15, -30], [16, 3, -33, 30, -34], [30, 1, 2], [22, 2, -4, 14], [24, 3, 14, -4, 23], [28, 1, -35], [28, 1, -2], [17, 2, -36, -18], [29, 1, -17], [29, 1, -19], [29, 1, -18] ]; XPathParser.DOUBLEDOT = 2; XPathParser.DOUBLECOLON = 3; XPathParser.DOUBLESLASH = 4; XPathParser.NOTEQUAL = 5; XPathParser.LESSTHANOREQUAL = 6; XPathParser.GREATERTHANOREQUAL = 7; XPathParser.AND = 8; XPathParser.OR = 9; XPathParser.MOD = 10; XPathParser.DIV = 11; XPathParser.MULTIPLYOPERATOR = 12; XPathParser.FUNCTIONNAME = 13; XPathParser.AXISNAME = 14; XPathParser.LITERAL = 15; XPathParser.NUMBER = 16; XPathParser.ASTERISKNAMETEST = 17; XPathParser.QNAME = 18; XPathParser.NCNAMECOLONASTERISK = 19; XPathParser.NODETYPE = 20; XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21; XPathParser.EQUALS = 22; XPathParser.LESSTHAN = 23; XPathParser.GREATERTHAN = 24; XPathParser.PLUS = 25; XPathParser.MINUS = 26; XPathParser.BAR = 27; XPathParser.SLASH = 28; XPathParser.LEFTPARENTHESIS = 29; XPathParser.RIGHTPARENTHESIS = 30; XPathParser.COMMA = 31; XPathParser.AT = 32; XPathParser.LEFTBRACKET = 33; XPathParser.RIGHTBRACKET = 34; XPathParser.DOT = 35; XPathParser.DOLLAR = 36; XPathParser.prototype.tokenize = function(s1) { var types = []; var values = []; var s = s1 + '\0'; var pos = 0; var c = s.charAt(pos++); while (1) { while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { c = s.charAt(pos++); } if (c == '\0' || pos >= s.length) { break; } if (c == '(') { types.push(XPathParser.LEFTPARENTHESIS); values.push(c); c = s.charAt(pos++); continue; } if (c == ')') { types.push(XPathParser.RIGHTPARENTHESIS); values.push(c); c = s.charAt(pos++); continue; } if (c == '[') { types.push(XPathParser.LEFTBRACKET); values.push(c); c = s.charAt(pos++); continue; } if (c == ']') { types.push(XPathParser.RIGHTBRACKET); values.push(c); c = s.charAt(pos++); continue; } if (c == '@') { types.push(XPathParser.AT); values.push(c); c = s.charAt(pos++); continue; } if (c == ',') { types.push(XPathParser.COMMA); values.push(c); c = s.charAt(pos++); continue; } if (c == '|') { types.push(XPathParser.BAR); values.push(c); c = s.charAt(pos++); continue; } if (c == '+') { types.push(XPathParser.PLUS); values.push(c); c = s.charAt(pos++); continue; } if (c == '-') { types.push(XPathParser.MINUS); values.push(c); c = s.charAt(pos++); continue; } if (c == '=') { types.push(XPathParser.EQUALS); values.push(c); c = s.charAt(pos++); continue; } if (c == '$') { types.push(XPathParser.DOLLAR); values.push(c); c = s.charAt(pos++); continue; } if (c == '.') { c = s.charAt(pos++); if (c == '.') { types.push(XPathParser.DOUBLEDOT); values.push(".."); c = s.charAt(pos++); continue; } if (c >= '0' && c <= '9') { var number = "." + c; c = s.charAt(pos++); while (c >= '0' && c <= '9') { number += c; c = s.charAt(pos++); } types.push(XPathParser.NUMBER); values.push(number); continue; } types.push(XPathParser.DOT); values.push('.'); continue; } if (c == '\'' || c == '"') { var delimiter = c; var literal = ""; while ((c = s.charAt(pos++)) != delimiter) { literal += c; } types.push(XPathParser.LITERAL); values.push(literal); c = s.charAt(pos++); continue; } if (c >= '0' && c <= '9') { var number = c; c = s.charAt(pos++); while (c >= '0' && c <= '9') { number += c; c = s.charAt(pos++); } if (c == '.') { if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') { number += c; number += s.charAt(pos++); c = s.charAt(pos++); while (c >= '0' && c <= '9') { number += c; c = s.charAt(pos++); } } } types.push(XPathParser.NUMBER); values.push(number); continue; } if (c == '*') { if (types.length > 0) { var last = types[types.length - 1]; if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) { types.push(XPathParser.MULTIPLYOPERATOR); values.push(c); c = s.charAt(pos++); continue; } } types.push(XPathParser.ASTERISKNAMETEST); values.push(c); c = s.charAt(pos++); continue; } if (c == ':') { if (s.charAt(pos) == ':') { types.push(XPathParser.DOUBLECOLON); values.push("::"); pos++; c = s.charAt(pos++); continue; } } if (c == '/') { c = s.charAt(pos++); if (c == '/') { types.push(XPathParser.DOUBLESLASH); values.push("//"); c = s.charAt(pos++); continue; } types.push(XPathParser.SLASH); values.push('/'); continue; } if (c == '!') { if (s.charAt(pos) == '=') { types.push(XPathParser.NOTEQUAL); values.push("!="); pos++; c = s.charAt(pos++); continue; } } if (c == '<') { if (s.charAt(pos) == '=') { types.push(XPathParser.LESSTHANOREQUAL); values.push("<="); pos++; c = s.charAt(pos++); continue; } types.push(XPathParser.LESSTHAN); values.push('<'); c = s.charAt(pos++); continue; } if (c == '>') { if (s.charAt(pos) == '=') { types.push(XPathParser.GREATERTHANOREQUAL); values.push(">="); pos++; c = s.charAt(pos++); continue; } types.push(XPathParser.GREATERTHAN); values.push('>'); c = s.charAt(pos++); continue; } if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) { var name = c; c = s.charAt(pos++); while (Utilities.isNCNameChar(c.charCodeAt(0))) { name += c; c = s.charAt(pos++); } if (types.length > 0) { var last = types[types.length - 1]; if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) { if (name == "and") { types.push(XPathParser.AND); values.push(name); continue; } if (name == "or") { types.push(XPathParser.OR); values.push(name); continue; } if (name == "mod") { types.push(XPathParser.MOD); values.push(name); continue; } if (name == "div") { types.push(XPathParser.DIV); values.push(name); continue; } } } if (c == ':') { if (s.charAt(pos) == '*') { types.push(XPathParser.NCNAMECOLONASTERISK); values.push(name + ":*"); pos++; c = s.charAt(pos++); continue; } if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) { name += ':'; c = s.charAt(pos++); while (Utilities.isNCNameChar(c.charCodeAt(0))) { name += c; c = s.charAt(pos++); } if (c == '(') { types.push(XPathParser.FUNCTIONNAME); values.push(name); continue; } types.push(XPathParser.QNAME); values.push(name); continue; } if (s.charAt(pos) == ':') { types.push(XPathParser.AXISNAME); values.push(name); continue; } } if (c == '(') { if (name == "comment" || name == "text" || name == "node") { types.push(XPathParser.NODETYPE); values.push(name); continue; } if (name == "processing-instruction") { if (s.charAt(pos) == ')') { types.push(XPathParser.NODETYPE); } else { types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL); } values.push(name); continue; } types.push(XPathParser.FUNCTIONNAME); values.push(name); continue; } types.push(XPathParser.QNAME); values.push(name); continue; } throw new Error("Unexpected character " + c); } types.push(1); values.push("[EOF]"); return [types, values]; }; XPathParser.SHIFT = 's'; XPathParser.REDUCE = 'r'; XPathParser.ACCEPT = 'a'; XPathParser.prototype.parse = function(s) { var types; var values; var res = this.tokenize(s); if (res == undefined) { return undefined; } types = res[0]; values = res[1]; var tokenPos = 0; var state = []; var tokenType = []; var tokenValue = []; var s; var a; var t; state.push(0); tokenType.push(1); tokenValue.push("_S"); a = types[tokenPos]; t = values[tokenPos++]; while (1) { s = state[state.length - 1]; switch (XPathParser.actionTable[s].charAt(a - 1)) { case XPathParser.SHIFT: tokenType.push(-a); tokenValue.push(t); state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32); a = types[tokenPos]; t = values[tokenPos++]; break; case XPathParser.REDUCE: var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1]; var rhs = []; for (var i = 0; i < num; i++) { tokenType.pop(); rhs.unshift(tokenValue.pop()); state.pop(); } var s_ = state[state.length - 1]; tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]); if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) { tokenValue.push(rhs[0]); } else { tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs)); } state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33); break; case XPathParser.ACCEPT: return new XPath(tokenValue.pop()); default: throw new Error("XPath parse error"); } } }; // XPath ///////////////////////////////////////////////////////////////////// XPath.prototype = new Object(); XPath.prototype.constructor = XPath; XPath.superclass = Object.prototype; function XPath(e) { this.expression = e; } XPath.prototype.toString = function() { return this.expression.toString(); }; XPath.prototype.evaluate = function(c) { c.contextNode = c.expressionContextNode; c.contextSize = 1; c.contextPosition = 1; c.caseInsensitive = false; if (c.contextNode != null) { var doc = c.contextNode; if (doc.nodeType != 9 /*Node.DOCUMENT_NODE*/) { doc = doc.ownerDocument; } try { c.caseInsensitive = doc.implementation.hasFeature("HTML", "2.0"); } catch (e) { c.caseInsensitive = true; } } return this.expression.evaluate(c); }; XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/"; // Expression //////////////////////////////////////////////////////////////// Expression.prototype = new Object(); Expression.prototype.constructor = Expression; Expression.superclass = Object.prototype; function Expression() { } Expression.prototype.init = function() { }; Expression.prototype.toString = function() { return "<Expression>"; }; Expression.prototype.evaluate = function(c) { throw new Error("Could not evaluate expression."); }; // UnaryOperation //////////////////////////////////////////////////////////// UnaryOperation.prototype = new Expression(); UnaryOperation.prototype.constructor = UnaryOperation; UnaryOperation.superclass = Expression.prototype; function UnaryOperation(rhs) { if (arguments.length > 0) { this.init(rhs); } } UnaryOperation.prototype.init = function(rhs) { this.rhs = rhs; }; // UnaryMinusOperation /////////////////////////////////////////////////////// UnaryMinusOperation.prototype = new UnaryOperation(); UnaryMinusOperation.prototype.constructor = UnaryMinusOperation; UnaryMinusOperation.superclass = UnaryOperation.prototype; function UnaryMinusOperation(rhs) { if (arguments.length > 0) { this.init(rhs); } } UnaryMinusOperation.prototype.init = function(rhs) { UnaryMinusOperation.superclass.init.call(this, rhs); }; UnaryMinusOperation.prototype.evaluate = function(c) { return this.rhs.evaluate(c).number().negate(); }; UnaryMinusOperation.prototype.toString = function() { return "-" + this.rhs.toString(); }; // BinaryOperation /////////////////////////////////////////////////////////// BinaryOperation.prototype = new Expression(); BinaryOperation.prototype.constructor = BinaryOperation; BinaryOperation.superclass = Expression.prototype; function BinaryOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } BinaryOperation.prototype.init = function(lhs, rhs) { this.lhs = lhs; this.rhs = rhs; }; // OrOperation /////////////////////////////////////////////////////////////// OrOperation.prototype = new BinaryOperation(); OrOperation.prototype.constructor = OrOperation; OrOperation.superclass = BinaryOperation.prototype; function OrOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } OrOperation.prototype.init = function(lhs, rhs) { OrOperation.superclass.init.call(this, lhs, rhs); }; OrOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")"; }; OrOperation.prototype.evaluate = function(c) { var b = this.lhs.evaluate(c).bool(); if (b.booleanValue()) { return b; } return this.rhs.evaluate(c).bool(); }; // AndOperation ////////////////////////////////////////////////////////////// AndOperation.prototype = new BinaryOperation(); AndOperation.prototype.constructor = AndOperation; AndOperation.superclass = BinaryOperation.prototype; function AndOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } AndOperation.prototype.init = function(lhs, rhs) { AndOperation.superclass.init.call(this, lhs, rhs); }; AndOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")"; }; AndOperation.prototype.evaluate = function(c) { var b = this.lhs.evaluate(c).bool(); if (!b.booleanValue()) { return b; } return this.rhs.evaluate(c).bool(); }; // EqualsOperation /////////////////////////////////////////////////////////// EqualsOperation.prototype = new BinaryOperation(); EqualsOperation.prototype.constructor = EqualsOperation; EqualsOperation.superclass = BinaryOperation.prototype; function EqualsOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } EqualsOperation.prototype.init = function(lhs, rhs) { EqualsOperation.superclass.init.call(this, lhs, rhs); }; EqualsOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")"; }; EqualsOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).equals(this.rhs.evaluate(c)); }; // NotEqualOperation ///////////////////////////////////////////////////////// NotEqualOperation.prototype = new BinaryOperation(); NotEqualOperation.prototype.constructor = NotEqualOperation; NotEqualOperation.superclass = BinaryOperation.prototype; function NotEqualOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } NotEqualOperation.prototype.init = function(lhs, rhs) { NotEqualOperation.superclass.init.call(this, lhs, rhs); }; NotEqualOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")"; }; NotEqualOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c)); }; // LessThanOperation ///////////////////////////////////////////////////////// LessThanOperation.prototype = new BinaryOperation(); LessThanOperation.prototype.constructor = LessThanOperation; LessThanOperation.superclass = BinaryOperation.prototype; function LessThanOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } LessThanOperation.prototype.init = function(lhs, rhs) { LessThanOperation.superclass.init.call(this, lhs, rhs); }; LessThanOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c)); }; LessThanOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")"; }; // GreaterThanOperation ////////////////////////////////////////////////////// GreaterThanOperation.prototype = new BinaryOperation(); GreaterThanOperation.prototype.constructor = GreaterThanOperation; GreaterThanOperation.superclass = BinaryOperation.prototype; function GreaterThanOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } GreaterThanOperation.prototype.init = function(lhs, rhs) { GreaterThanOperation.superclass.init.call(this, lhs, rhs); }; GreaterThanOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c)); }; GreaterThanOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")"; }; // LessThanOrEqualOperation ////////////////////////////////////////////////// LessThanOrEqualOperation.prototype = new BinaryOperation(); LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation; LessThanOrEqualOperation.superclass = BinaryOperation.prototype; function LessThanOrEqualOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } LessThanOrEqualOperation.prototype.init = function(lhs, rhs) { LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs); }; LessThanOrEqualOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c)); }; LessThanOrEqualOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")"; }; // GreaterThanOrEqualOperation /////////////////////////////////////////////// GreaterThanOrEqualOperation.prototype = new BinaryOperation(); GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation; GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype; function GreaterThanOrEqualOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } GreaterThanOrEqualOperation.prototype.init = function(lhs, rhs) { GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs); }; GreaterThanOrEqualOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c)); }; GreaterThanOrEqualOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")"; }; // PlusOperation ///////////////////////////////////////////////////////////// PlusOperation.prototype = new BinaryOperation(); PlusOperation.prototype.constructor = PlusOperation; PlusOperation.superclass = BinaryOperation.prototype; function PlusOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } PlusOperation.prototype.init = function(lhs, rhs) { PlusOperation.superclass.init.call(this, lhs, rhs); }; PlusOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number()); }; PlusOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")"; }; // MinusOperation //////////////////////////////////////////////////////////// MinusOperation.prototype = new BinaryOperation(); MinusOperation.prototype.constructor = MinusOperation; MinusOperation.superclass = BinaryOperation.prototype; function MinusOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } MinusOperation.prototype.init = function(lhs, rhs) { MinusOperation.superclass.init.call(this, lhs, rhs); }; MinusOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number()); }; MinusOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")"; }; // MultiplyOperation ///////////////////////////////////////////////////////// MultiplyOperation.prototype = new BinaryOperation(); MultiplyOperation.prototype.constructor = MultiplyOperation; MultiplyOperation.superclass = BinaryOperation.prototype; function MultiplyOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } MultiplyOperation.prototype.init = function(lhs, rhs) { MultiplyOperation.superclass.init.call(this, lhs, rhs); }; MultiplyOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number()); }; MultiplyOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")"; }; // DivOperation ////////////////////////////////////////////////////////////// DivOperation.prototype = new BinaryOperation(); DivOperation.prototype.constructor = DivOperation; DivOperation.superclass = BinaryOperation.prototype; function DivOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } DivOperation.prototype.init = function(lhs, rhs) { DivOperation.superclass.init.call(this, lhs, rhs); }; DivOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number()); }; DivOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")"; }; // ModOperation ////////////////////////////////////////////////////////////// ModOperation.prototype = new BinaryOperation(); ModOperation.prototype.constructor = ModOperation; ModOperation.superclass = BinaryOperation.prototype; function ModOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } ModOperation.prototype.init = function(lhs, rhs) { ModOperation.superclass.init.call(this, lhs, rhs); }; ModOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number()); }; ModOperation.prototype.toString = function() { return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")"; }; // BarOperation ////////////////////////////////////////////////////////////// BarOperation.prototype = new BinaryOperation(); BarOperation.prototype.constructor = BarOperation; BarOperation.superclass = BinaryOperation.prototype; function BarOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } BarOperation.prototype.init = function(lhs, rhs) { BarOperation.superclass.init.call(this, lhs, rhs); }; BarOperation.prototype.evaluate = function(c) { return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset()); }; BarOperation.prototype.toString = function() { return this.lhs.toString() + " | " + this.rhs.toString(); }; // PathExpr ////////////////////////////////////////////////////////////////// PathExpr.prototype = new Expression(); PathExpr.prototype.constructor = PathExpr; PathExpr.superclass = Expression.prototype; function PathExpr(filter, filterPreds, locpath) { if (arguments.length > 0) { this.init(filter, filterPreds, locpath); } } PathExpr.prototype.init = function(filter, filterPreds, locpath) { PathExpr.superclass.init.call(this); this.filter = filter; this.filterPredicates = filterPreds; this.locationPath = locpath; }; PathExpr.prototype.evaluate = function(c) { var nodes; var xpc = new XPathContext(); xpc.variableResolver = c.variableResolver; xpc.functionResolver = c.functionResolver; xpc.namespaceResolver = c.namespaceResolver; xpc.expressionContextNode = c.expressionContextNode; xpc.virtualRoot = c.virtualRoot; xpc.caseInsensitive = c.caseInsensitive; if (this.filter == null) { nodes = [ c.contextNode ]; } else { var ns = this.filter.evaluate(c); if (!Utilities.instance_of(ns, XNodeSet)) { if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) { throw new Error("Path expression filter must evaluate to a nodset if predicates or location path are used"); } return ns; } nodes = ns.toArray(); if (this.filterPredicates != null) { // apply each of the predicates in turn for (var j = 0; j < this.filterPredicates.length; j++) { var pred = this.filterPredicates[j]; var newNodes = []; xpc.contextSize = nodes.length; for (xpc.contextPosition = 1; xpc.contextPosition <= xpc.contextSize; xpc.contextPosition++) { xpc.contextNode = nodes[xpc.contextPosition - 1]; if (this.predicateMatches(pred, xpc)) { newNodes.push(xpc.contextNode); } } nodes = newNodes; } } } if (this.locationPath != null) { if (this.locationPath.absolute) { if (nodes[0].nodeType != 9 /*Node.DOCUMENT_NODE*/) { if (xpc.virtualRoot != null) { nodes = [ xpc.virtualRoot ]; } else { if (nodes[0].ownerDocument == null) { // IE 5.5 doesn't have ownerDocument? var n = nodes[0]; while (n.parentNode != null) { n = n.parentNode; } nodes = [ n ]; } else { nodes = [ nodes[0].ownerDocument ]; } } } else { nodes = [ nodes[0] ]; } } for (var i = 0; i < this.locationPath.steps.length; i++) { var step = this.locationPath.steps[i]; var newNodes = []; for (var j = 0; j < nodes.length; j++) { xpc.contextNode = nodes[j]; switch (step.axis) { case Step.ANCESTOR: // look at all the ancestor nodes if (xpc.contextNode === xpc.virtualRoot) { break; } var m; if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { m = this.getOwnerElement(xpc.contextNode); } else { m = xpc.contextNode.parentNode; } while (m != null) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m === xpc.virtualRoot) { break; } m = m.parentNode; } break; case Step.ANCESTORORSELF: // look at all the ancestor nodes and the current node for (var m = xpc.contextNode; m != null; m = m.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ ? this.getOwnerElement(m) : m.parentNode) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m === xpc.virtualRoot) { break; } } break; case Step.ATTRIBUTE: // look at the attributes var nnm = xpc.contextNode.attributes; if (nnm != null) { for (var k = 0; k < nnm.length; k++) { var m = nnm.item(k); if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } } break; case Step.CHILD: // look at all child elements for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } break; case Step.DESCENDANT: // look at all descendant nodes var st = [ xpc.contextNode.firstChild ]; while (st.length > 0) { for (var m = st.pop(); m != null; ) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } break; case Step.DESCENDANTORSELF: // look at self if (step.nodeTest.matches(xpc.contextNode, xpc)) { newNodes.push(xpc.contextNode); } // look at all descendant nodes var st = [ xpc.contextNode.firstChild ]; while (st.length > 0) { for (var m = st.pop(); m != null; ) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } break; case Step.FOLLOWING: if (xpc.contextNode === xpc.virtualRoot) { break; } var st = []; if (xpc.contextNode.firstChild != null) { st.unshift(xpc.contextNode.firstChild); } else { st.unshift(xpc.contextNode.nextSibling); } for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != 9 /*Node.DOCUMENT_NODE*/ && m !== xpc.virtualRoot; m = m.parentNode) { st.unshift(m.nextSibling); } do { for (var m = st.pop(); m != null; ) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } while (st.length > 0); break; case Step.FOLLOWINGSIBLING: if (xpc.contextNode === xpc.virtualRoot) { break; } for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } break; case Step.NAMESPACE: var n = {}; if (xpc.contextNode.nodeType == 1 /*Node.ELEMENT_NODE*/) { n["xml"] = XPath.XML_NAMESPACE_URI; n["xmlns"] = XPath.XMLNS_NAMESPACE_URI; for (var m = xpc.contextNode; m != null && m.nodeType == 1 /*Node.ELEMENT_NODE*/; m = m.parentNode) { for (var k = 0; k < m.attributes.length; k++) { var attr = m.attributes.item(k); var nm = String(attr.name); if (nm == "xmlns") { if (n[""] == undefined) { n[""] = attr.value; } } else if (nm.length > 6 && nm.substring(0, 6) == "xmlns:") { var pre = nm.substring(6, nm.length); if (n[pre] == undefined) { n[pre] = attr.value; } } } } for (var pre in n) { var nsn = new NamespaceNode(pre, n[pre], xpc.contextNode); if (step.nodeTest.matches(nsn, xpc)) { newNodes.push(nsn); } } } break; case Step.PARENT: m = null; if (xpc.contextNode !== xpc.virtualRoot) { if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { m = this.getOwnerElement(xpc.contextNode); } else { m = xpc.contextNode.parentNode; } } if (m != null && step.nodeTest.matches(m, xpc)) { newNodes.push(m); } break; case Step.PRECEDING: var st; if (xpc.virtualRoot != null) { st = [ xpc.virtualRoot ]; } else { st = xpc.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/ ? [ xpc.contextNode ] : [ xpc.contextNode.ownerDocument ]; } outer: while (st.length > 0) { for (var m = st.pop(); m != null; ) { if (m == xpc.contextNode) { break outer; } if (step.nodeTest.matches(m, xpc)) { newNodes.unshift(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } break; case Step.PRECEDINGSIBLING: if (xpc.contextNode === xpc.virtualRoot) { break; } for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } break; case Step.SELF: if (step.nodeTest.matches(xpc.contextNode, xpc)) { newNodes.push(xpc.contextNode); } break; default: } } nodes = newNodes; // apply each of the predicates in turn for (var j = 0; j < step.predicates.length; j++) { var pred = step.predicates[j]; var newNodes = []; xpc.contextSize = nodes.length; for (xpc.contextPosition = 1; xpc.contextPosition <= xpc.contextSize; xpc.contextPosition++) { xpc.contextNode = nodes[xpc.contextPosition - 1]; if (this.predicateMatches(pred, xpc)) { newNodes.push(xpc.contextNode); } else { } } nodes = newNodes; } } } var ns = new XNodeSet(); ns.addArray(nodes); return ns; }; PathExpr.prototype.predicateMatches = function(pred, c) { var res = pred.evaluate(c); if (Utilities.instance_of(res, XNumber)) { return c.contextPosition == res.numberValue(); } return res.booleanValue(); }; PathExpr.prototype.toString = function() { if (this.filter != undefined) { var s = this.filter.toString(); if (Utilities.instance_of(this.filter, XString)) { s = "'" + s + "'"; } if (this.filterPredicates != undefined) { for (var i = 0; i < this.filterPredicates.length; i++) { s = s + "[" + this.filterPredicates[i].toString() + "]"; } } if (this.locationPath != undefined) { if (!this.locationPath.absolute) { s += "/"; } s += this.locationPath.toString(); } return s; } return this.locationPath.toString(); }; PathExpr.prototype.getOwnerElement = function(n) { // DOM 2 has ownerElement if (n.ownerElement) { return n.ownerElement; } // DOM 1 Internet Explorer can use selectSingleNode (ironically) try { if (n.selectSingleNode) { return n.selectSingleNode(".."); } } catch (e) { } // Other DOM 1 implementations must use this egregious search var doc = n.nodeType == 9 /*Node.DOCUMENT_NODE*/ ? n : n.ownerDocument; var elts = doc.getElementsByTagName("*"); for (var i = 0; i < elts.length; i++) { var elt = elts.item(i); var nnm = elt.attributes; for (var j = 0; j < nnm.length; j++) { var an = nnm.item(j); if (an === n) { return elt; } } } return null; }; // LocationPath ////////////////////////////////////////////////////////////// LocationPath.prototype = new Object(); LocationPath.prototype.constructor = LocationPath; LocationPath.superclass = Object.prototype; function LocationPath(abs, steps) { if (arguments.length > 0) { this.init(abs, steps); } } LocationPath.prototype.init = function(abs, steps) { this.absolute = abs; this.steps = steps; }; LocationPath.prototype.toString = function() { var s; if (this.absolute) { s = "/"; } else { s = ""; } for (var i = 0; i < this.steps.length; i++) { if (i != 0) { s += "/"; } s += this.steps[i].toString(); } return s; }; // Step ////////////////////////////////////////////////////////////////////// Step.prototype = new Object(); Step.prototype.constructor = Step; Step.superclass = Object.prototype; function Step(axis, nodetest, preds) { if (arguments.length > 0) { this.init(axis, nodetest, preds); } } Step.prototype.init = function(axis, nodetest, preds) { this.axis = axis; this.nodeTest = nodetest; this.predicates = preds; }; Step.prototype.toString = function() { var s; switch (this.axis) { case Step.ANCESTOR: s = "ancestor"; break; case Step.ANCESTORORSELF: s = "ancestor-or-self"; break; case Step.ATTRIBUTE: s = "attribute"; break; case Step.CHILD: s = "child"; break; case Step.DESCENDANT: s = "descendant"; break; case Step.DESCENDANTORSELF: s = "descendant-or-self"; break; case Step.FOLLOWING: s = "following"; break; case Step.FOLLOWINGSIBLING: s = "following-sibling"; break; case Step.NAMESPACE: s = "namespace"; break; case Step.PARENT: s = "parent"; break; case Step.PRECEDING: s = "preceding"; break; case Step.PRECEDINGSIBLING: s = "preceding-sibling"; break; case Step.SELF: s = "self"; break; } s += "::"; s += this.nodeTest.toString(); for (var i = 0; i < this.predicates.length; i++) { s += "[" + this.predicates[i].toString() + "]"; } return s; }; Step.ANCESTOR = 0; Step.ANCESTORORSELF = 1; Step.ATTRIBUTE = 2; Step.CHILD = 3; Step.DESCENDANT = 4; Step.DESCENDANTORSELF = 5; Step.FOLLOWING = 6; Step.FOLLOWINGSIBLING = 7; Step.NAMESPACE = 8; Step.PARENT = 9; Step.PRECEDING = 10; Step.PRECEDINGSIBLING = 11; Step.SELF = 12; // NodeTest ////////////////////////////////////////////////////////////////// NodeTest.prototype = new Object(); NodeTest.prototype.constructor = NodeTest; NodeTest.superclass = Object.prototype; function NodeTest(type, value) { if (arguments.length > 0) { this.init(type, value); } } NodeTest.prototype.init = function(type, value) { this.type = type; this.value = value; }; NodeTest.prototype.toString = function() { switch (this.type) { case NodeTest.NAMETESTANY: return "*"; case NodeTest.NAMETESTPREFIXANY: return this.value + ":*"; case NodeTest.NAMETESTRESOLVEDANY: return "{" + this.value + "}*"; case NodeTest.NAMETESTQNAME: return this.value; case NodeTest.NAMETESTRESOLVEDNAME: return "{" + this.namespaceURI + "}" + this.value; case NodeTest.COMMENT: return "comment()"; case NodeTest.TEXT: return "text()"; case NodeTest.PI: if (this.value != undefined) { return "processing-instruction(\"" + this.value + "\")"; } return "processing-instruction()"; case NodeTest.NODE: return "node()"; } return "<unknown nodetest type>"; }; NodeTest.prototype.matches = function(n, xpc) { switch (this.type) { case NodeTest.NAMETESTANY: if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ || n.nodeType == 1 /*Node.ELEMENT_NODE*/ || n.nodeType == XPathNamespace.XPATH_NAMESPACE_NODE) { return true; } return false; case NodeTest.NAMETESTPREFIXANY: if ((n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ || n.nodeType == 1 /*Node.ELEMENT_NODE*/)) { var ns = xpc.namespaceResolver.getNamespace(this.value, xpc.expressionContextNode); if (ns == null) { throw new Error("Cannot resolve QName " + this.value); } return true; } return false; case NodeTest.NAMETESTQNAME: if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ || n.nodeType == 1 /*Node.ELEMENT_NODE*/ || n.nodeType == XPathNamespace.XPATH_NAMESPACE_NODE) { var test = Utilities.resolveQName(this.value, xpc.namespaceResolver, xpc.expressionContextNode, false); if (test[0] == null) { throw new Error("Cannot resolve QName " + this.value); } test[0] = String(test[0]); test[1] = String(test[1]); if (test[0] == "") { test[0] = null; } var node = Utilities.resolveQName(n.nodeName, xpc.namespaceResolver, n, n.nodeType == 1 /*Node.ELEMENT_NODE*/); node[0] = String(node[0]); node[1] = String(node[1]); if (node[0] == "") { node[0] = null; } if (xpc.caseInsensitive) { return test[0] == node[0] && String(test[1]).toLowerCase() == String(node[1]).toLowerCase(); } return test[0] == node[0] && test[1] == node[1]; } return false; case NodeTest.COMMENT: return n.nodeType == 8 /*Node.COMMENT_NODE*/; case NodeTest.TEXT: return n.nodeType == 3 /*Node.TEXT_NODE*/ || n.nodeType == 4 /*Node.CDATA_SECTION_NODE*/; case NodeTest.PI: return n.nodeType == 7 /*Node.PROCESSING_INSTRUCTION_NODE*/ && (this.value == null || n.nodeName == this.value); case NodeTest.NODE: return n.nodeType == 9 /*Node.DOCUMENT_NODE*/ || n.nodeType == 1 /*Node.ELEMENT_NODE*/ || n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ || n.nodeType == 3 /*Node.TEXT_NODE*/ || n.nodeType == 4 /*Node.CDATA_SECTION_NODE*/ || n.nodeType == 8 /*Node.COMMENT_NODE*/ || n.nodeType == 7 /*Node.PROCESSING_INSTRUCTION_NODE*/; } return false; }; NodeTest.NAMETESTANY = 0; NodeTest.NAMETESTPREFIXANY = 1; NodeTest.NAMETESTQNAME = 2; NodeTest.COMMENT = 3; NodeTest.TEXT = 4; NodeTest.PI = 5; NodeTest.NODE = 6; // VariableReference ///////////////////////////////////////////////////////// VariableReference.prototype = new Expression(); VariableReference.prototype.constructor = VariableReference; VariableReference.superclass = Expression.prototype; function VariableReference(v) { if (arguments.length > 0) { this.init(v); } } VariableReference.prototype.init = function(v) { this.variable = v; }; VariableReference.prototype.toString = function() { return "$" + this.variable; }; VariableReference.prototype.evaluate = function(c) { return c.variableResolver.getVariable(this.variable, c); }; // FunctionCall ////////////////////////////////////////////////////////////// FunctionCall.prototype = new Expression(); FunctionCall.prototype.constructor = FunctionCall; FunctionCall.superclass = Expression.prototype; function FunctionCall(fn, args) { if (arguments.length > 0) { this.init(fn, args); } } FunctionCall.prototype.init = function(fn, args) { this.functionName = fn; this.arguments = args; }; FunctionCall.prototype.toString = function() { var s = this.functionName + "("; for (var i = 0; i < this.arguments.length; i++) { if (i > 0) { s += ", "; } s += this.arguments[i].toString(); } return s + ")"; }; FunctionCall.prototype.evaluate = function(c) { var f = c.functionResolver.getFunction(this.functionName, c); if (f == undefined) { throw new Error("Unknown function " + this.functionName); } var a = [c].concat(this.arguments); return f.apply(c.functionResolver.thisArg, a); }; // XString /////////////////////////////////////////////////////////////////// XString.prototype = new Expression(); XString.prototype.constructor = XString; XString.superclass = Expression.prototype; function XString(s) { if (arguments.length > 0) { this.init(s); } } XString.prototype.init = function(s) { this.str = s; }; XString.prototype.toString = function() { return this.str; }; XString.prototype.evaluate = function(c) { return this; }; XString.prototype.string = function() { return this; }; XString.prototype.number = function() { return new XNumber(this.str); }; XString.prototype.bool = function() { return new XBoolean(this.str); }; XString.prototype.nodeset = function() { throw new Error("Cannot convert string to nodeset"); }; XString.prototype.stringValue = function() { return this.str; }; XString.prototype.numberValue = function() { return this.number().numberValue(); }; XString.prototype.booleanValue = function() { return this.bool().booleanValue(); }; XString.prototype.equals = function(r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().equals(r); } if (Utilities.instance_of(r, XNumber)) { return this.number().equals(r); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithString(this, Operators.equals); } return new XBoolean(this.str == r.str); }; XString.prototype.notequal = function(r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().notequal(r); } if (Utilities.instance_of(r, XNumber)) { return this.number().notequal(r); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithString(this, Operators.notequal); } return new XBoolean(this.str != r.str); }; XString.prototype.lessthan = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.greaterthanorequal); } return this.number().lessthan(r.number()); }; XString.prototype.greaterthan = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.lessthanorequal); } return this.number().greaterthan(r.number()); }; XString.prototype.lessthanorequal = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.greaterthan); } return this.number().lessthanorequal(r.number()); }; XString.prototype.greaterthanorequal = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.lessthan); } return this.number().greaterthanorequal(r.number()); }; // XNumber /////////////////////////////////////////////////////////////////// XNumber.prototype = new Expression(); XNumber.prototype.constructor = XNumber; XNumber.superclass = Expression.prototype; function XNumber(n) { if (arguments.length > 0) { this.init(n); } } XNumber.prototype.init = function(n) { this.num = Number(n); }; XNumber.prototype.toString = function() { return this.num; }; XNumber.prototype.evaluate = function(c) { return this; }; XNumber.prototype.string = function() { return new XString(this.num); }; XNumber.prototype.number = function() { return this; }; XNumber.prototype.bool = function() { return new XBoolean(this.num); }; XNumber.prototype.nodeset = function() { throw new Error("Cannot convert number to nodeset"); }; XNumber.prototype.stringValue = function() { return this.string().stringValue(); }; XNumber.prototype.numberValue = function() { return this.num; }; XNumber.prototype.booleanValue = function() { return this.bool().booleanValue(); }; XNumber.prototype.negate = function() { return new XNumber(-this.num); }; XNumber.prototype.equals = function(r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().equals(r); } if (Utilities.instance_of(r, XString)) { return this.equals(r.number()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.equals); } return new XBoolean(this.num == r.num); }; XNumber.prototype.notequal = function(r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().notequal(r); } if (Utilities.instance_of(r, XString)) { return this.notequal(r.number()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.notequal); } return new XBoolean(this.num != r.num); }; XNumber.prototype.lessthan = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.greaterthanorequal); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.lessthan(r.number()); } return new XBoolean(this.num < r.num); }; XNumber.prototype.greaterthan = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.lessthanorequal); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.greaterthan(r.number()); } return new XBoolean(this.num > r.num); }; XNumber.prototype.lessthanorequal = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.greaterthan); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.lessthanorequal(r.number()); } return new XBoolean(this.num <= r.num); }; XNumber.prototype.greaterthanorequal = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.lessthan); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.greaterthanorequal(r.number()); } return new XBoolean(this.num >= r.num); }; XNumber.prototype.plus = function(r) { return new XNumber(this.num + r.num); }; XNumber.prototype.minus = function(r) { return new XNumber(this.num - r.num); }; XNumber.prototype.multiply = function(r) { return new XNumber(this.num * r.num); }; XNumber.prototype.div = function(r) { return new XNumber(this.num / r.num); }; XNumber.prototype.mod = function(r) { return new XNumber(this.num % r.num); }; // XBoolean ////////////////////////////////////////////////////////////////// XBoolean.prototype = new Expression(); XBoolean.prototype.constructor = XBoolean; XBoolean.superclass = Expression.prototype; function XBoolean(b) { if (arguments.length > 0) { this.init(b); } } XBoolean.prototype.init = function(b) { this.b = Boolean(b); }; XBoolean.prototype.toString = function() { return this.b.toString(); }; XBoolean.prototype.evaluate = function(c) { return this; }; XBoolean.prototype.string = function() { return new XString(this.b); }; XBoolean.prototype.number = function() { return new XNumber(this.b); }; XBoolean.prototype.bool = function() { return this; }; XBoolean.prototype.nodeset = function() { throw new Error("Cannot convert boolean to nodeset"); }; XBoolean.prototype.stringValue = function() { return this.string().stringValue(); }; XBoolean.prototype.numberValue = function() { return this.num().numberValue(); }; XBoolean.prototype.booleanValue = function() { return this.b; }; XBoolean.prototype.not = function() { return new XBoolean(!this.b); }; XBoolean.prototype.equals = function(r) { if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { return this.equals(r.bool()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithBoolean(this, Operators.equals); } return new XBoolean(this.b == r.b); }; XBoolean.prototype.notequal = function(r) { if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { return this.notequal(r.bool()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithBoolean(this, Operators.notequal); } return new XBoolean(this.b != r.b); }; XBoolean.prototype.lessthan = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.greaterthanorequal); } return this.number().lessthan(r.number()); }; XBoolean.prototype.greaterthan = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.lessthanorequal); } return this.number().greaterthan(r.number()); }; XBoolean.prototype.lessthanorequal = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.greaterthan); } return this.number().lessthanorequal(r.number()); }; XBoolean.prototype.greaterthanorequal = function(r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this.number(), Operators.lessthan); } return this.number().greaterthanorequal(r.number()); }; // AVLTree /////////////////////////////////////////////////////////////////// AVLTree.prototype = new Object(); AVLTree.prototype.constructor = AVLTree; AVLTree.superclass = Object.prototype; function AVLTree(n) { this.init(n); } AVLTree.prototype.init = function(n) { this.left = null; this.right = null; this.node = n; this.depth = 1; }; AVLTree.prototype.balance = function() { var ldepth = this.left == null ? 0 : this.left.depth; var rdepth = this.right == null ? 0 : this.right.depth; if (ldepth > rdepth + 1) { // LR or LL rotation var lldepth = this.left.left == null ? 0 : this.left.left.depth; var lrdepth = this.left.right == null ? 0 : this.left.right.depth; if (lldepth < lrdepth) { // LR rotation consists of a RR rotation of the left child this.left.rotateRR(); // plus a LL rotation of this node, which happens anyway } this.rotateLL(); } else if (ldepth + 1 < rdepth) { // RR or RL rorarion var rrdepth = this.right.right == null ? 0 : this.right.right.depth; var rldepth = this.right.left == null ? 0 : this.right.left.depth; if (rldepth > rrdepth) { // RR rotation consists of a LL rotation of the right child this.right.rotateLL(); // plus a RR rotation of this node, which happens anyway } this.rotateRR(); } }; AVLTree.prototype.rotateLL = function() { // the left side is too long => rotate from the left (_not_ leftwards) var nodeBefore = this.node; var rightBefore = this.right; this.node = this.left.node; this.right = this.left; this.left = this.left.left; this.right.left = this.right.right; this.right.right = rightBefore; this.right.node = nodeBefore; this.right.updateInNewLocation(); this.updateInNewLocation(); }; AVLTree.prototype.rotateRR = function() { // the right side is too long => rotate from the right (_not_ rightwards) var nodeBefore = this.node; var leftBefore = this.left; this.node = this.right.node; this.left = this.right; this.right = this.right.right; this.left.right = this.left.left; this.left.left = leftBefore; this.left.node = nodeBefore; this.left.updateInNewLocation(); this.updateInNewLocation(); }; AVLTree.prototype.updateInNewLocation = function() { this.getDepthFromChildren(); }; AVLTree.prototype.getDepthFromChildren = function() { this.depth = this.node == null ? 0 : 1; if (this.left != null) { this.depth = this.left.depth + 1; } if (this.right != null && this.depth <= this.right.depth) { this.depth = this.right.depth + 1; } }; AVLTree.prototype.order = function(n1, n2) { if (n1 === n2) { return 0; } var d1 = 0; var d2 = 0; for (var m1 = n1; m1 != null; m1 = m1.parentNode) { d1++; } for (var m2 = n2; m2 != null; m2 = m2.parentNode) { d2++; } if (d1 > d2) { while (d1 > d2) { n1 = n1.parentNode; d1--; } if (n1 == n2) { return 1; } } else if (d2 > d1) { while (d2 > d1) { n2 = n2.parentNode; d2--; } if (n1 == n2) { return -1; } } while (n1.parentNode != n2.parentNode) { n1 = n1.parentNode; n2 = n2.parentNode; } while (n1.previousSibling != null && n2.previousSibling != null) { n1 = n1.previousSibling; n2 = n2.previousSibling; } if (n1.previousSibling == null) { return -1; } return 1; }; AVLTree.prototype.add = function(n) { if (n === this.node) { return false; } var o = this.order(n, this.node); var ret = false; if (o == -1) { if (this.left == null) { this.left = new AVLTree(n); ret = true; } else { ret = this.left.add(n); if (ret) { this.balance(); } } } else if (o == 1) { if (this.right == null) { this.right = new AVLTree(n); ret = true; } else { ret = this.right.add(n); if (ret) { this.balance(); } } } if (ret) { this.getDepthFromChildren(); } return ret; }; // XNodeSet ////////////////////////////////////////////////////////////////// XNodeSet.prototype = new Expression(); XNodeSet.prototype.constructor = XNodeSet; XNodeSet.superclass = Expression.prototype; function XNodeSet() { this.init(); } XNodeSet.prototype.init = function() { this.tree = null; this.size = 0; }; XNodeSet.prototype.toString = function() { var p = this.first(); if (p == null) { return ""; } return this.stringForNode(p); }; XNodeSet.prototype.evaluate = function(c) { return this; }; XNodeSet.prototype.string = function() { return new XString(this.toString()); }; XNodeSet.prototype.stringValue = function() { return this.toString(); }; XNodeSet.prototype.number = function() { return new XNumber(this.string()); }; XNodeSet.prototype.numberValue = function() { return Number(this.string()); }; XNodeSet.prototype.bool = function() { return new XBoolean(this.tree != null); }; XNodeSet.prototype.booleanValue = function() { return this.tree != null; }; XNodeSet.prototype.nodeset = function() { return this; }; XNodeSet.prototype.stringForNode = function(n) { if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) { n = n.documentElement; } if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) { return this.stringForNodeRec(n); } if (n.isNamespaceNode) { return n.namespace; } return n.nodeValue; }; XNodeSet.prototype.stringForNodeRec = function(n) { var s = ""; for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) { if (n2.nodeType == 3 /*Node.TEXT_NODE*/) { s += n2.nodeValue; } else if (n2.nodeType == 1 /*Node.ELEMENT_NODE*/) { s += this.stringForNodeRec(n2); } } return s; }; XNodeSet.prototype.first = function() { var p = this.tree; if (p == null) { return null; } while (p.left != null) { p = p.left; } return p.node; }; XNodeSet.prototype.add = function(n) { var added; if (this.tree == null) { this.tree = new AVLTree(n); added = true; } else { added = this.tree.add(n); } if (added) { this.size++; } }; XNodeSet.prototype.addArray = function(ns) { for (var i = 0; i < ns.length; i++) { this.add(ns[i]); } }; XNodeSet.prototype.toArray = function() { var a = []; this.toArrayRec(this.tree, a); return a; }; XNodeSet.prototype.toArrayRec = function(t, a) { if (t != null) { this.toArrayRec(t.left, a); a.push(t.node); this.toArrayRec(t.right, a); } }; XNodeSet.prototype.compareWithString = function(r, o) { var a = this.toArray(); for (var i = 0; i < a.length; i++) { var n = a[i]; var l = new XString(this.stringForNode(n)); var res = o(l, r); if (res.booleanValue()) { return res; } } return new XBoolean(false); }; XNodeSet.prototype.compareWithNumber = function(r, o) { var a = this.toArray(); for (var i = 0; i < a.length; i++) { var n = a[i]; var l = new XNumber(this.stringForNode(n)); var res = o(l, r); if (res.booleanValue()) { return res; } } return new XBoolean(false); }; XNodeSet.prototype.compareWithBoolean = function(r, o) { return o(this.bool(), r); }; XNodeSet.prototype.compareWithNodeSet = function(r, o) { var a = this.toArray(); for (var i = 0; i < a.length; i++) { var n = a[i]; var l = new XString(this.stringForNode(n)); var b = r.toArray(); for (var j = 0; j < b.length; j++) { var n2 = b[j]; var r = new XString(this.stringForNode(n2)); var res = o(l, r); if (res.booleanValue()) { return res; } } } return new XBoolean(false); }; XNodeSet.prototype.equals = function(r) { if (Utilities.instance_of(r, XString)) { return this.compareWithString(r, Operators.equals); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, Operators.equals); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, Operators.equals); } return this.compareWithNodeSet(r, Operators.equals); }; XNodeSet.prototype.notequal = function(r) { if (Utilities.instance_of(r, XString)) { return this.compareWithString(r, Operators.notequal); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, Operators.notequal); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, Operators.notequal); } return this.compareWithNodeSet(r, Operators.notequal); }; XNodeSet.prototype.lessthan = function(r) { if (Utilities.instance_of(r, XString)) { return this.compareWithNumber(r.number(), Operators.lessthan); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, Operators.lessthan); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, Operators.lessthan); } return this.compareWithNodeSet(r, Operators.lessthan); }; XNodeSet.prototype.greaterthan = function(r) { if (Utilities.instance_of(r, XString)) { return this.compareWithNumber(r.number(), Operators.greaterthan); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, Operators.greaterthan); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, Operators.greaterthan); } return this.compareWithNodeSet(r, Operators.greaterthan); }; XNodeSet.prototype.lessthanorequal = function(r) { if (Utilities.instance_of(r, XString)) { return this.compareWithNumber(r.number(), Operators.lessthanorequal); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, Operators.lessthanorequal); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, Operators.lessthanorequal); } return this.compareWithNodeSet(r, Operators.lessthanorequal); }; XNodeSet.prototype.greaterthanorequal = function(r) { if (Utilities.instance_of(r, XString)) { return this.compareWithNumber(r.number(), Operators.greaterthanorequal); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, Operators.greaterthanorequal); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, Operators.greaterthanorequal); } return this.compareWithNodeSet(r, Operators.greaterthanorequal); }; XNodeSet.prototype.union = function(r) { var ns = new XNodeSet(); ns.tree = this.tree; ns.size = this.size; ns.addArray(r.toArray()); return ns; }; // XPathNamespace //////////////////////////////////////////////////////////// XPathNamespace.prototype = new Object(); XPathNamespace.prototype.constructor = XPathNamespace; XPathNamespace.superclass = Object.prototype; function XPathNamespace(pre, ns, p) { this.isXPathNamespace = true; this.ownerDocument = p.ownerDocument; this.nodeName = "#namespace"; this.prefix = pre; this.localName = pre; this.namespaceURI = ns; this.nodeValue = ns; this.ownerElement = p; this.nodeType = XPathNamespace.XPATH_NAMESPACE_NODE; } XPathNamespace.prototype.toString = function() { return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }"; }; // Operators ///////////////////////////////////////////////////////////////// var Operators = new Object(); Operators.equals = function(l, r) { return l.equals(r); }; Operators.notequal = function(l, r) { return l.notequal(r); }; Operators.lessthan = function(l, r) { return l.lessthan(r); }; Operators.greaterthan = function(l, r) { return l.greaterthan(r); }; Operators.lessthanorequal = function(l, r) { return l.lessthanorequal(r); }; Operators.greaterthanorequal = function(l, r) { return l.greaterthanorequal(r); }; // XPathContext ////////////////////////////////////////////////////////////// XPathContext.prototype = new Object(); XPathContext.prototype.constructor = XPathContext; XPathContext.superclass = Object.prototype; function XPathContext(vr, nr, fr) { this.variableResolver = vr != null ? vr : new VariableResolver(); this.namespaceResolver = nr != null ? nr : new NamespaceResolver(); this.functionResolver = fr != null ? fr : new FunctionResolver(); } // VariableResolver ////////////////////////////////////////////////////////// VariableResolver.prototype = new Object(); VariableResolver.prototype.constructor = VariableResolver; VariableResolver.superclass = Object.prototype; function VariableResolver() { } VariableResolver.prototype.getVariable = function(vn, c) { var parts = Utilities.splitQName(vn); if (parts[0] != null) { parts[0] = c.namespaceResolver.getNamespace(parts[0], c.expressionContextNode); if (parts[0] == null) { throw new Error("Cannot resolve QName " + fn); } } return this.getVariableWithName(parts[0], parts[1], c.expressionContextNode); }; VariableResolver.prototype.getVariableWithName = function(ns, ln, c) { return null; }; // FunctionResolver ////////////////////////////////////////////////////////// FunctionResolver.prototype = new Object(); FunctionResolver.prototype.constructor = FunctionResolver; FunctionResolver.superclass = Object.prototype; function FunctionResolver(thisArg) { this.thisArg = thisArg != null ? thisArg : Functions; this.functions = new Object(); this.addStandardFunctions(); } FunctionResolver.prototype.addStandardFunctions = function() { this.functions["{}last"] = Functions.last; this.functions["{}position"] = Functions.position; this.functions["{}count"] = Functions.count; this.functions["{}id"] = Functions.id; this.functions["{}local-name"] = Functions.localName; this.functions["{}namespace-uri"] = Functions.namespaceURI; this.functions["{}name"] = Functions.name; this.functions["{}string"] = Functions.string; this.functions["{}concat"] = Functions.concat; this.functions["{}starts-with"] = Functions.startsWith; this.functions["{}contains"] = Functions.contains; this.functions["{}substring-before"] = Functions.substringBefore; this.functions["{}substring-after"] = Functions.substringAfter; this.functions["{}substring"] = Functions.substring; this.functions["{}string-length"] = Functions.stringLength; this.functions["{}normalize-space"] = Functions.normalizeSpace; this.functions["{}translate"] = Functions.translate; this.functions["{}boolean"] = Functions.boolean_; this.functions["{}not"] = Functions.not; this.functions["{}true"] = Functions.true_; this.functions["{}false"] = Functions.false_; this.functions["{}lang"] = Functions.lang; this.functions["{}number"] = Functions.number; this.functions["{}sum"] = Functions.sum; this.functions["{}floor"] = Functions.floor; this.functions["{}ceiling"] = Functions.ceiling; this.functions["{}round"] = Functions.round; }; FunctionResolver.prototype.addFunction = function(ns, ln, f) { this.functions["{" + ns + "}" + ln] = f; }; FunctionResolver.prototype.getFunction = function(fn, c) { var parts = Utilities.resolveQName(fn, c.namespaceResolver, c.contextNode, false); if (parts[0] == null) { throw new Error("Cannot resolve QName " + fn); } return this.getFunctionWithName(parts[0], parts[1], c.contextNode); }; FunctionResolver.prototype.getFunctionWithName = function(ns, ln, c) { return this.functions["{" + ns + "}" + ln]; }; // NamespaceResolver ///////////////////////////////////////////////////////// NamespaceResolver.prototype = new Object(); NamespaceResolver.prototype.constructor = NamespaceResolver; NamespaceResolver.superclass = Object.prototype; function NamespaceResolver() { } NamespaceResolver.prototype.getNamespace = function(prefix, n) { if (prefix == "xml") { return XPath.XML_NAMESPACE_URI; } else if (prefix == "xmlns") { return XPath.XMLNS_NAMESPACE_URI; } if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) { n = n.documentElement; } else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { n = PathExpr.prototype.getOwnerElement(n); } else if (n.nodeType != 1 /*Node.ELEMENT_NODE*/) { n = n.parentNode; } while (n != null && n.nodeType == 1 /*Node.ELEMENT_NODE*/) { var nnm = n.attributes; for (var i = 0; i < nnm.length; i++) { var a = nnm.item(i); var aname = a.nodeName; if (aname == "xmlns" && prefix == "" || aname == "xmlns:" + prefix) { return String(a.nodeValue); } } n = n.parentNode; } return null; }; // Functions ///////////////////////////////////////////////////////////////// Functions = new Object(); Functions.last = function() { var c = arguments[0]; if (arguments.length != 1) { throw new Error("Function last expects ()"); } return new XNumber(c.contextSize); }; Functions.position = function() { var c = arguments[0]; if (arguments.length != 1) { throw new Error("Function position expects ()"); } return new XNumber(c.contextPosition); }; Functions.count = function() { var c = arguments[0]; var ns; if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) { throw new Error("Function count expects (node-set)"); } return new XNumber(ns.size); }; Functions.id = function() { var c = arguments[0]; var id; if (arguments.length != 2) { throw new Error("Function id expects (object)"); } id = arguments[1].evaluate(c); if (Utilities.instance_of(id, XNodeSet)) { id = id.toArray().join(" "); } else { id = id.stringValue(); } var ids = id.split(/[\x0d\x0a\x09\x20]+/); var count = 0; var ns = new XNodeSet(); var doc = c.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/ ? c.contextNode : c.contextNode.ownerDocument; for (var i = 0; i < ids.length; i++) { var n; if (doc.getElementById) { n = doc.getElementById(ids[i]); } else { n = Utilities.getElementById(doc, ids[i]); } if (n != null) { ns.add(n); count++; } } return ns; }; Functions.localName = function() { var c = arguments[0]; var n; if (arguments.length == 1) { n = c.contextNode; } else if (arguments.length == 2) { n = arguments[1].evaluate(c).first(); } else { throw new Error("Function local-name expects (node-set?)"); } if (n == null) { return new XString(""); } return new XString(n.localName ? n.localName : n.baseName); }; Functions.namespaceURI = function() { var c = arguments[0]; var n; if (arguments.length == 1) { n = c.contextNode; } else if (arguments.length == 2) { n = arguments[1].evaluate(c).first(); } else { throw new Error("Function namespace-uri expects (node-set?)"); } if (n == null) { return new XString(""); } return new XString(n.namespaceURI); }; Functions.name = function() { var c = arguments[0]; var n; if (arguments.length == 1) { n = c.contextNode; } else if (arguments.length == 2) { n = arguments[1].evaluate(c).first(); } else { throw new Error("Function name expects (node-set?)"); } if (n == null) { return new XString(""); } if (n.nodeType == 1 /*Node.ELEMENT_NODE*/ || n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { return new XString(n.nodeName); } else if (n.localName == null) { return new XString(""); } else { return new XString(n.localName); } }; Functions.string = function() { var c = arguments[0]; if (arguments.length == 1) { return XNodeSet.prototype.stringForNode(c.contextNode); } else if (arguments.length == 2) { return arguments[1].evaluate(c).string(); } throw new Error("Function string expects (object?)"); }; Functions.concat = function() { var c = arguments[0]; if (arguments.length < 3) { throw new Error("Function concat expects (string, string, string*)"); } var s = ""; for (var i = 1; i < arguments.length; i++) { s += arguments[i].evaluate(c).stringValue(); } return new XString(s); }; Functions.startsWith = function() { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function startsWith expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); return new XBoolean(s1.substring(0, s2.length) == s2); }; Functions.contains = function() { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function contains expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); return new XBoolean(s1.indexOf(s2) != -1); }; Functions.substringBefore = function() { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function substring-before expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); return new XString(s1.substring(0, s1.indexOf(s2))); }; Functions.substringAfter = function() { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function substring-after expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); if (s2.length == 0) { return new XString(s1); } var i = s1.indexOf(s2); if (i == -1) { return new XString(""); } return new XString(s1.substring(s1.indexOf(s2) + 1)); }; Functions.substring = function() { var c = arguments[0]; if (!(arguments.length == 3 || arguments.length == 4)) { throw new Error("Function substring expects (string, number, number?)"); } var s = arguments[1].evaluate(c).stringValue(); var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1; var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined; return new XString(s.substring(n1, n2)); }; Functions.stringLength = function() { var c = arguments[0]; var s; if (arguments.length == 1) { s = XNodeSet.prototype.stringForNode(c.contextNode); } else if (arguments.length == 2) { s = arguments[1].evaluate(c).stringValue(); } else { throw new Error("Function string-length expects (string?)"); } return new XNumber(s.length); }; Functions.normalizeSpace = function() { var c = arguments[0]; var s; if (arguments.length == 1) { s = XNodeSet.prototype.stringForNode(c.contextNode); } else if (arguments.length == 2) { s = arguments[1].evaluate(c).stringValue(); } else { throw new Error("Function normalize-space expects (string?)"); } var i = 0; var j = s.length - 1; while (Utilities.isSpace(s.charCodeAt(j))) { j--; } var t = ""; while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { i++; } while (i <= j) { if (Utilities.isSpace(s.charCodeAt(i))) { t += " "; while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { i++; } } else { t += s.charAt(i); i++; } } return new XString(t); }; Functions.translate = function() { var c = arguments[0]; if (arguments.length != 4) { throw new Error("Function translate expects (string, string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); var s3 = arguments[3].evaluate(c).stringValue(); var map = []; for (var i = 0; i < s2.length; i++) { var j = s2.charCodeAt(i); if (map[j] == undefined) { var k = i > s3.length ? "" : s3.charAt(i); map[j] = k; } } var t = ""; for (var i = 0; i < s1.length; i++) { var c = s1.charCodeAt(i); var r = map[c]; if (r == undefined) { t += s1.charAt(i); } else { t += r; } } return new XString(t); }; Functions.boolean_ = function() { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function boolean expects (object)"); } return arguments[1].evaluate(c).bool(); }; Functions.not = function() { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function not expects (object)"); } return arguments[1].evaluate(c).bool().not(); }; Functions.true_ = function() { if (arguments.length != 1) { throw new Error("Function true expects ()"); } return new XBoolean(true); }; Functions.false_ = function() { if (arguments.length != 1) { throw new Error("Function false expects ()"); } return new XBoolean(false); }; Functions.lang = function() { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function lang expects (string)"); } var lang; for (var n = c.contextNode; n != null && n.nodeType != 9 /*Node.DOCUMENT_NODE*/; n = n.parentNode) { var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang"); if (a != null) { lang = String(a); break; } } if (lang == null) { return new XBoolean(false); } var s = arguments[1].evaluate(c).stringValue(); return new XBoolean(lang.substring(0, s.length) == s && (lang.length == s.length || lang.charAt(s.length) == '-')); }; Functions.number = function() { var c = arguments[0]; if (!(arguments.length == 1 || arguments.length == 2)) { throw new Error("Function number expects (object?)"); } if (arguments.length == 1) { return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode)); } return arguments[1].evaluate(c).number(); }; Functions.sum = function() { var c = arguments[0]; var ns; if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) { throw new Error("Function sum expects (node-set)"); } ns = ns.toArray(); var n = 0; for (var i = 0; i < ns.length; i++) { n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue(); } return new XNumber(n); }; Functions.floor = function() { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function floor expects (number)"); } return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue())); }; Functions.ceiling = function() { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function ceiling expects (number)"); } return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue())); }; Functions.round = function() { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function round expects (number)"); } return new XNumber(Math.round(arguments[1].evaluate(c).numberValue())); }; // Utilities ///////////////////////////////////////////////////////////////// Utilities = new Object(); Utilities.splitQName = function(qn) { var i = qn.indexOf(":"); if (i == -1) { return [ null, qn ]; } return [ qn.substring(0, i), qn.substring(i + 1) ]; }; Utilities.resolveQName = function(qn, nr, n, useDefault) { var parts = Utilities.splitQName(qn); if (parts[0] != null) { parts[0] = nr.getNamespace(parts[0], n); } else { if (useDefault) { parts[0] = nr.getNamespace("", n); if (parts[0] == null) { parts[0] = ""; } } else { parts[0] = ""; } } return parts; }; Utilities.isSpace = function(c) { return c == 0x9 || c == 0xd || c == 0xa || c == 0x20; }; Utilities.isLetter = function(c) { return c >= 0x0041 && c <= 0x005A || c >= 0x0061 && c <= 0x007A || c >= 0x00C0 && c <= 0x00D6 || c >= 0x00D8 && c <= 0x00F6 || c >= 0x00F8 && c <= 0x00FF || c >= 0x0100 && c <= 0x0131 || c >= 0x0134 && c <= 0x013E || c >= 0x0141 && c <= 0x0148 || c >= 0x014A && c <= 0x017E || c >= 0x0180 && c <= 0x01C3 || c >= 0x01CD && c <= 0x01F0 || c >= 0x01F4 && c <= 0x01F5 || c >= 0x01FA && c <= 0x0217 || c >= 0x0250 && c <= 0x02A8 || c >= 0x02BB && c <= 0x02C1 || c == 0x0386 || c >= 0x0388 && c <= 0x038A || c == 0x038C || c >= 0x038E && c <= 0x03A1 || c >= 0x03A3 && c <= 0x03CE || c >= 0x03D0 && c <= 0x03D6 || c == 0x03DA || c == 0x03DC || c == 0x03DE || c == 0x03E0 || c >= 0x03E2 && c <= 0x03F3 || c >= 0x0401 && c <= 0x040C || c >= 0x040E && c <= 0x044F || c >= 0x0451 && c <= 0x045C || c >= 0x045E && c <= 0x0481 || c >= 0x0490 && c <= 0x04C4 || c >= 0x04C7 && c <= 0x04C8 || c >= 0x04CB && c <= 0x04CC || c >= 0x04D0 && c <= 0x04EB || c >= 0x04EE && c <= 0x04F5 || c >= 0x04F8 && c <= 0x04F9 || c >= 0x0531 && c <= 0x0556 || c == 0x0559 || c >= 0x0561 && c <= 0x0586 || c >= 0x05D0 && c <= 0x05EA || c >= 0x05F0 && c <= 0x05F2 || c >= 0x0621 && c <= 0x063A || c >= 0x0641 && c <= 0x064A || c >= 0x0671 && c <= 0x06B7 || c >= 0x06BA && c <= 0x06BE || c >= 0x06C0 && c <= 0x06CE || c >= 0x06D0 && c <= 0x06D3 || c == 0x06D5 || c >= 0x06E5 && c <= 0x06E6 || c >= 0x0905 && c <= 0x0939 || c == 0x093D || c >= 0x0958 && c <= 0x0961 || c >= 0x0985 && c <= 0x098C || c >= 0x098F && c <= 0x0990 || c >= 0x0993 && c <= 0x09A8 || c >= 0x09AA && c <= 0x09B0 || c == 0x09B2 || c >= 0x09B6 && c <= 0x09B9 || c >= 0x09DC && c <= 0x09DD || c >= 0x09DF && c <= 0x09E1 || c >= 0x09F0 && c <= 0x09F1 || c >= 0x0A05 && c <= 0x0A0A || c >= 0x0A0F && c <= 0x0A10 || c >= 0x0A13 && c <= 0x0A28 || c >= 0x0A2A && c <= 0x0A30 || c >= 0x0A32 && c <= 0x0A33 || c >= 0x0A35 && c <= 0x0A36 || c >= 0x0A38 && c <= 0x0A39 || c >= 0x0A59 && c <= 0x0A5C || c == 0x0A5E || c >= 0x0A72 && c <= 0x0A74 || c >= 0x0A85 && c <= 0x0A8B || c == 0x0A8D || c >= 0x0A8F && c <= 0x0A91 || c >= 0x0A93 && c <= 0x0AA8 || c >= 0x0AAA && c <= 0x0AB0 || c >= 0x0AB2 && c <= 0x0AB3 || c >= 0x0AB5 && c <= 0x0AB9 || c == 0x0ABD || c == 0x0AE0 || c >= 0x0B05 && c <= 0x0B0C || c >= 0x0B0F && c <= 0x0B10 || c >= 0x0B13 && c <= 0x0B28 || c >= 0x0B2A && c <= 0x0B30 || c >= 0x0B32 && c <= 0x0B33 || c >= 0x0B36 && c <= 0x0B39 || c == 0x0B3D || c >= 0x0B5C && c <= 0x0B5D || c >= 0x0B5F && c <= 0x0B61 || c >= 0x0B85 && c <= 0x0B8A || c >= 0x0B8E && c <= 0x0B90 || c >= 0x0B92 && c <= 0x0B95 || c >= 0x0B99 && c <= 0x0B9A || c == 0x0B9C || c >= 0x0B9E && c <= 0x0B9F || c >= 0x0BA3 && c <= 0x0BA4 || c >= 0x0BA8 && c <= 0x0BAA || c >= 0x0BAE && c <= 0x0BB5 || c >= 0x0BB7 && c <= 0x0BB9 || c >= 0x0C05 && c <= 0x0C0C || c >= 0x0C0E && c <= 0x0C10 || c >= 0x0C12 && c <= 0x0C28 || c >= 0x0C2A && c <= 0x0C33 || c >= 0x0C35 && c <= 0x0C39 || c >= 0x0C60 && c <= 0x0C61 || c >= 0x0C85 && c <= 0x0C8C || c >= 0x0C8E && c <= 0x0C90 || c >= 0x0C92 && c <= 0x0CA8 || c >= 0x0CAA && c <= 0x0CB3 || c >= 0x0CB5 && c <= 0x0CB9 || c == 0x0CDE || c >= 0x0CE0 && c <= 0x0CE1 || c >= 0x0D05 && c <= 0x0D0C || c >= 0x0D0E && c <= 0x0D10 || c >= 0x0D12 && c <= 0x0D28 || c >= 0x0D2A && c <= 0x0D39 || c >= 0x0D60 && c <= 0x0D61 || c >= 0x0E01 && c <= 0x0E2E || c == 0x0E30 || c >= 0x0E32 && c <= 0x0E33 || c >= 0x0E40 && c <= 0x0E45 || c >= 0x0E81 && c <= 0x0E82 || c == 0x0E84 || c >= 0x0E87 && c <= 0x0E88 || c == 0x0E8A || c == 0x0E8D || c >= 0x0E94 && c <= 0x0E97 || c >= 0x0E99 && c <= 0x0E9F || c >= 0x0EA1 && c <= 0x0EA3 || c == 0x0EA5 || c == 0x0EA7 || c >= 0x0EAA && c <= 0x0EAB || c >= 0x0EAD && c <= 0x0EAE || c == 0x0EB0 || c >= 0x0EB2 && c <= 0x0EB3 || c == 0x0EBD || c >= 0x0EC0 && c <= 0x0EC4 || c >= 0x0F40 && c <= 0x0F47 || c >= 0x0F49 && c <= 0x0F69 || c >= 0x10A0 && c <= 0x10C5 || c >= 0x10D0 && c <= 0x10F6 || c == 0x1100 || c >= 0x1102 && c <= 0x1103 || c >= 0x1105 && c <= 0x1107 || c == 0x1109 || c >= 0x110B && c <= 0x110C || c >= 0x110E && c <= 0x1112 || c == 0x113C || c == 0x113E || c == 0x1140 || c == 0x114C || c == 0x114E || c == 0x1150 || c >= 0x1154 && c <= 0x1155 || c == 0x1159 || c >= 0x115F && c <= 0x1161 || c == 0x1163 || c == 0x1165 || c == 0x1167 || c == 0x1169 || c >= 0x116D && c <= 0x116E || c >= 0x1172 && c <= 0x1173 || c == 0x1175 || c == 0x119E || c == 0x11A8 || c == 0x11AB || c >= 0x11AE && c <= 0x11AF || c >= 0x11B7 && c <= 0x11B8 || c == 0x11BA || c >= 0x11BC && c <= 0x11C2 || c == 0x11EB || c == 0x11F0 || c == 0x11F9 || c >= 0x1E00 && c <= 0x1E9B || c >= 0x1EA0 && c <= 0x1EF9 || c >= 0x1F00 && c <= 0x1F15 || c >= 0x1F18 && c <= 0x1F1D || c >= 0x1F20 && c <= 0x1F45 || c >= 0x1F48 && c <= 0x1F4D || c >= 0x1F50 && c <= 0x1F57 || c == 0x1F59 || c == 0x1F5B || c == 0x1F5D || c >= 0x1F5F && c <= 0x1F7D || c >= 0x1F80 && c <= 0x1FB4 || c >= 0x1FB6 && c <= 0x1FBC || c == 0x1FBE || c >= 0x1FC2 && c <= 0x1FC4 || c >= 0x1FC6 && c <= 0x1FCC || c >= 0x1FD0 && c <= 0x1FD3 || c >= 0x1FD6 && c <= 0x1FDB || c >= 0x1FE0 && c <= 0x1FEC || c >= 0x1FF2 && c <= 0x1FF4 || c >= 0x1FF6 && c <= 0x1FFC || c == 0x2126 || c >= 0x212A && c <= 0x212B || c == 0x212E || c >= 0x2180 && c <= 0x2182 || c >= 0x3041 && c <= 0x3094 || c >= 0x30A1 && c <= 0x30FA || c >= 0x3105 && c <= 0x312C || c >= 0xAC00 && c <= 0xD7A3 || c >= 0x4E00 && c <= 0x9FA5 || c == 0x3007 || c >= 0x3021 && c <= 0x3029; }; Utilities.isNCNameChar = function(c) { return c >= 0x0030 && c <= 0x0039 || c >= 0x0660 && c <= 0x0669 || c >= 0x06F0 && c <= 0x06F9 || c >= 0x0966 && c <= 0x096F || c >= 0x09E6 && c <= 0x09EF || c >= 0x0A66 && c <= 0x0A6F || c >= 0x0AE6 && c <= 0x0AEF || c >= 0x0B66 && c <= 0x0B6F || c >= 0x0BE7 && c <= 0x0BEF || c >= 0x0C66 && c <= 0x0C6F || c >= 0x0CE6 && c <= 0x0CEF || c >= 0x0D66 && c <= 0x0D6F || c >= 0x0E50 && c <= 0x0E59 || c >= 0x0ED0 && c <= 0x0ED9 || c >= 0x0F20 && c <= 0x0F29 || c == 0x002E || c == 0x002D || c == 0x005F || Utilities.isLetter(c) || c >= 0x0300 && c <= 0x0345 || c >= 0x0360 && c <= 0x0361 || c >= 0x0483 && c <= 0x0486 || c >= 0x0591 && c <= 0x05A1 || c >= 0x05A3 && c <= 0x05B9 || c >= 0x05BB && c <= 0x05BD || c == 0x05BF || c >= 0x05C1 && c <= 0x05C2 || c == 0x05C4 || c >= 0x064B && c <= 0x0652 || c == 0x0670 || c >= 0x06D6 && c <= 0x06DC || c >= 0x06DD && c <= 0x06DF || c >= 0x06E0 && c <= 0x06E4 || c >= 0x06E7 && c <= 0x06E8 || c >= 0x06EA && c <= 0x06ED || c >= 0x0901 && c <= 0x0903 || c == 0x093C || c >= 0x093E && c <= 0x094C || c == 0x094D || c >= 0x0951 && c <= 0x0954 || c >= 0x0962 && c <= 0x0963 || c >= 0x0981 && c <= 0x0983 || c == 0x09BC || c == 0x09BE || c == 0x09BF || c >= 0x09C0 && c <= 0x09C4 || c >= 0x09C7 && c <= 0x09C8 || c >= 0x09CB && c <= 0x09CD || c == 0x09D7 || c >= 0x09E2 && c <= 0x09E3 || c == 0x0A02 || c == 0x0A3C || c == 0x0A3E || c == 0x0A3F || c >= 0x0A40 && c <= 0x0A42 || c >= 0x0A47 && c <= 0x0A48 || c >= 0x0A4B && c <= 0x0A4D || c >= 0x0A70 && c <= 0x0A71 || c >= 0x0A81 && c <= 0x0A83 || c == 0x0ABC || c >= 0x0ABE && c <= 0x0AC5 || c >= 0x0AC7 && c <= 0x0AC9 || c >= 0x0ACB && c <= 0x0ACD || c >= 0x0B01 && c <= 0x0B03 || c == 0x0B3C || c >= 0x0B3E && c <= 0x0B43 || c >= 0x0B47 && c <= 0x0B48 || c >= 0x0B4B && c <= 0x0B4D || c >= 0x0B56 && c <= 0x0B57 || c >= 0x0B82 && c <= 0x0B83 || c >= 0x0BBE && c <= 0x0BC2 || c >= 0x0BC6 && c <= 0x0BC8 || c >= 0x0BCA && c <= 0x0BCD || c == 0x0BD7 || c >= 0x0C01 && c <= 0x0C03 || c >= 0x0C3E && c <= 0x0C44 || c >= 0x0C46 && c <= 0x0C48 || c >= 0x0C4A && c <= 0x0C4D || c >= 0x0C55 && c <= 0x0C56 || c >= 0x0C82 && c <= 0x0C83 || c >= 0x0CBE && c <= 0x0CC4 || c >= 0x0CC6 && c <= 0x0CC8 || c >= 0x0CCA && c <= 0x0CCD || c >= 0x0CD5 && c <= 0x0CD6 || c >= 0x0D02 && c <= 0x0D03 || c >= 0x0D3E && c <= 0x0D43 || c >= 0x0D46 && c <= 0x0D48 || c >= 0x0D4A && c <= 0x0D4D || c == 0x0D57 || c == 0x0E31 || c >= 0x0E34 && c <= 0x0E3A || c >= 0x0E47 && c <= 0x0E4E || c == 0x0EB1 || c >= 0x0EB4 && c <= 0x0EB9 || c >= 0x0EBB && c <= 0x0EBC || c >= 0x0EC8 && c <= 0x0ECD || c >= 0x0F18 && c <= 0x0F19 || c == 0x0F35 || c == 0x0F37 || c == 0x0F39 || c == 0x0F3E || c == 0x0F3F || c >= 0x0F71 && c <= 0x0F84 || c >= 0x0F86 && c <= 0x0F8B || c >= 0x0F90 && c <= 0x0F95 || c == 0x0F97 || c >= 0x0F99 && c <= 0x0FAD || c >= 0x0FB1 && c <= 0x0FB7 || c == 0x0FB9 || c >= 0x20D0 && c <= 0x20DC || c == 0x20E1 || c >= 0x302A && c <= 0x302F || c == 0x3099 || c == 0x309A || c == 0x00B7 || c == 0x02D0 || c == 0x02D1 || c == 0x0387 || c == 0x0640 || c == 0x0E46 || c == 0x0EC6 || c == 0x3005 || c >= 0x3031 && c <= 0x3035 || c >= 0x309D && c <= 0x309E || c >= 0x30FC && c <= 0x30FE; }; Utilities.coalesceText = function(n) { for (var m = n.firstChild; m != null; m = m.nextSibling) { if (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) { var s = m.nodeValue; var first = m; m = m.nextSibling; while (m != null && (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/)) { s += m.nodeValue; var del = m; m = m.nextSibling; del.parentNode.removeChild(del); } if (first.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) { var p = first.parentNode; if (first.nextSibling == null) { p.removeChild(first); p.appendChild(p.ownerDocument.createTextNode(s)); } else { var next = first.nextSibling; p.removeChild(first); p.insertBefore(p.ownerDocument.createTextNode(s), next); } } else { first.nodeValue = s; } if (m == null) { break; } } else if (m.nodeType == 1 /*Node.ELEMENT_NODE*/) { Utilities.coalesceText(m); } } }; Utilities.instance_of = function(o, c) { while (o != null) { if (o.constructor === c) { return true; } if (o === Object) { return false; } o = o.constructor.superclass; } return false; }; Utilities.getElementById = function(n, id) { // Note that this does not check the DTD to check for actual // attributes of type ID, so this may be a bit wrong. if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) { if (n.getAttribute("id") == id || n.getAttributeNS(null, "id") == id) { return n; } } for (var m = n.firstChild; m != null; m = m.nextSibling) { var res = Utilities.getElementById(m, id); if (res != null) { return res; } } return null; }; // XPathException //////////////////////////////////////////////////////////// XPathException.prototype = {}; XPathException.prototype.constructor = XPathException; XPathException.superclass = Object.prototype; function XPathException(c, e) { this.code = c; this.exception = e; } XPathException.prototype.toString = function() { var msg = this.exception ? ": " + this.exception.toString() : ""; switch (this.code) { case XPathException.INVALID_EXPRESSION_ERR: return "Invalid expression" + msg; case XPathException.TYPE_ERR: return "Type error" + msg; } }; XPathException.INVALID_EXPRESSION_ERR = 51; XPathException.TYPE_ERR = 52; // XPathExpression /////////////////////////////////////////////////////////// XPathExpression.prototype = {}; XPathExpression.prototype.constructor = XPathExpression; XPathExpression.superclass = Object.prototype; function XPathExpression(e, r, p) { this.xpath = p.parse(e); this.context = new XPathContext(); this.context.namespaceResolver = new XPathNSResolverWrapper(r); } XPathExpression.prototype.evaluate = function(n, t, res) { this.context.expressionContextNode = n; var result = this.xpath.evaluate(this.context); return new XPathResult(result, t); } // XPathNSResolverWrapper //////////////////////////////////////////////////// XPathNSResolverWrapper.prototype = {}; XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper; XPathNSResolverWrapper.superclass = Object.prototype; function XPathNSResolverWrapper(r) { this.xpathNSResolver = r; } XPathNSResolverWrapper.prototype.getNamespace = function(prefix, n) { if (this.xpathNSResolver == null) { return null; } return this.xpathNSResolver.lookupNamespaceURI(prefix); }; // NodeXPathNSResolver /////////////////////////////////////////////////////// NodeXPathNSResolver.prototype = {}; NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver; NodeXPathNSResolver.superclass = Object.prototype; function NodeXPathNSResolver(n) { this.node = n; this.namespaceResolver = new NamespaceResolver(); } NodeXPathNSResolver.prototype.lookupNamespaceURI = function(prefix) { return this.namespaceResolver.getNamespace(prefix, this.node); }; // XPathResult /////////////////////////////////////////////////////////////// XPathResult.prototype = {}; XPathResult.prototype.constructor = XPathResult; XPathResult.superclass = Object.prototype; function XPathResult(v, t) { if (t == XPathResult.ANY_TYPE) { if (v.constructor === XString) { t = XPathResult.STRING_TYPE; } else if (v.constructor === XNumber) { t = XPathResult.NUMBER_TYPE; } else if (v.constructor === XBoolean) { t = XPathResult.BOOLEAN_TYPE; } else if (v.constructor === XNodeSet) { t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE; } } this.resultType = t; switch (t) { case XPathResult.NUMBER_TYPE: this.numberValue = v.numberValue(); return; case XPathResult.STRING_TYPE: this.stringValue = v.stringValue(); return; case XPathResult.BOOLEAN_TYPE: this.booleanValue = v.booleanValue(); return; case XPathResult.ANY_UNORDERED_NODE_TYPE: case XPathResult.FIRST_ORDERED_NODE_TYPE: if (v.constructor === XNodeSet) { this.singleNodeValue = v.first(); return; } break; case XPathResult.UNORDERED_NODE_ITERATOR_TYPE: case XPathResult.ORDERED_NODE_ITERATOR_TYPE: if (v.constructor === XNodeSet) { this.invalidIteratorState = false; this.nodes = v.toArray(); this.iteratorIndex = 0; return; } break; case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE: case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE: if (v.constructor === XNodeSet) { this.nodes = v.toArray(); this.snapshotLength = this.nodes.length; return; } break; } throw new XPathException(XPathException.TYPE_ERR); }; XPathResult.prototype.iterateNext = function() { if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE && this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) { throw new XPathException(XPathException.TYPE_ERR); } return this.nodes[this.iteratorIndex++]; }; XPathResult.prototype.snapshotItem = function(i) { if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE && this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) { throw new XPathException(XPathException.TYPE_ERR); } return this.nodes[i]; }; XPathResult.ANY_TYPE = 0; XPathResult.NUMBER_TYPE = 1; XPathResult.STRING_TYPE = 2; XPathResult.BOOLEAN_TYPE = 3; XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4; XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5; XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6; XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7; XPathResult.ANY_UNORDERED_NODE_TYPE = 8; XPathResult.FIRST_ORDERED_NODE_TYPE = 9; // DOM 3 XPath support /////////////////////////////////////////////////////// function installDOM3XPathSupport(doc, p) { doc.createExpression = function(e, r) { try { return new XPathExpression(e, r, p); } catch (e) { throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e); } }; doc.createNSResolver = function(n) { return new NodeXPathNSResolver(n); }; doc.evaluate = function(e, cn, r, t, res) { if (t < 0 || t > 9) { throw { code: 0, toString: function() { return "Request type not supported"; } }; } return doc.createExpression(e, r, p).evaluate(cn, t, res); }; }; // --------------------------------------------------------------------------- // Install DOM 3 XPath support for the current document. try { var shouldInstall = true; try { if (document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("XPath", null)) { shouldInstall = false; } } catch (e) { } if (shouldInstall) { installDOM3XPathSupport(document, new XPathParser()); } } catch (e) { } // --------------------------------------------------------------------------- // exports for node.js installDOM3XPathSupport(exports, new XPathParser()); exports.XPathResult = XPathResult; // helper exports.select = function(e, doc, single) { var expression = new XPathExpression(e, null, new XPathParser()); var type = XPathResult.ANY_TYPE; var result = expression.evaluate(doc, type, null); if (result.resultType == XPathResult.STRING_TYPE) { result = result.stringValue; } else if (result.resultType == XPathResult.NUMBER_TYPE) { result = result.numberValue; } else if (result.resultType == XPathResult.BOOLEAN_TYPE) { result = result.booleanValue; } else { result = result.nodes; if (single) { result = result[0]; } } return result; }; exports.select1 = function(e, doc) { return exports.select(e, doc, true); }; exports.attr = function(e, doc) { var result = exports.select1(e, doc); if (result) { return result.value; } };
/** * Output widget to vizualize DomainAnnotation object. * Pavel Novichkov <psnovichkov@lbl.gov> * @public */ (function($, undefined) { $.KBWidget({ name: 'kbaseDomainAnnotation', parent: 'kbaseAuthenticatedWidget', version: '1.0.1', options: { domainAnnotationID: null, workspaceID: null, domainAnnotationVer: null, kbCache: null, loadingImage: "assets/img/ajax-loader.gif", height: null, }, // Data for vizualization domainAnnotationData: null, genomeRef: null, genomeId: null, genomeName: null, domainModelSetRef: null, domainModelSetName: null, domainAccession2Description: {}, annotatedGenesCount: 0, annotatedDomainsCount: 0, init: function(options) { this._super(options); this.workspaceURL = kb.urls.workspace_url; this.landingPageURL = "#/dataview/"; // Create a message pain this.$messagePane = $("<div/>"); //.addClass("kbwidget-message-pane kbwidget-hide-message"); this.$elem.append(this.$messagePane); return this; }, loggedInCallback: function(event, auth) { // Cretae a new workspace client this.ws = new Workspace(this.workspaceURL, auth); // Let's go... this.render(); return this; }, loggedOutCallback: function(event, auth) { this.ws = null; this.isLoggedIn = false; return this; }, render: function(){ var self = this; self.pref = this.uuid(); self.loading(true); var container = this.$elem; var kbws = this.ws; //self.options.workspaceID + "/" + self.options.domainAnnotationID; //kbws.get_objects([{ref: domainAnnotationRef}], function(data) { var domainAnnotationRef = self.buildObjectIdentity(this.options.workspaceID, this.options.domainAnnotationID, this.options.domainAnnotationVer); kbws.get_objects([domainAnnotationRef], function(data) { self.domainAnnotationData = data[0].data; self.genomeRef = self.domainAnnotationData.genome_ref; self.domainModelSetRef = self.domainAnnotationData.used_dms_ref; // Job to get properties of AnnotationDomain object: name and id of the annotated genome var jobGetDomainAnnotationProperties = kbws.get_object_subset( [ { 'ref':self.genomeRef, 'included':['/id'] }, { 'ref':self.genomeRef, 'included':['/scientific_name'] } ], function(data){ self.genomeId = data[0].data.id; self.genomeName = data[1].data.scientific_name; }, function(error){ self.clientError(error); } ); var jobGetDomainModelSet = kbws.get_objects( [{ref: self.domainModelSetRef}], function(data) { self.domainSetName = data[0].data.set_name; self.domainAccession2Description = data[0].data.domain_accession_to_description; }, function(error){ self.clientError(error); } ); // Launch jobs and vizualize data once they are done $.when.apply($, [jobGetDomainAnnotationProperties, jobGetDomainModelSet]).done( function(){ self.loading(false); self.prepareVizData(); ///////////////////////////////////// Instantiating Tabs //////////////////////////////////////////// container.empty(); var tabPane = $('<div id="'+self.pref+'tab-content">'); container.append(tabPane); tabPane.kbaseTabs({canDelete : true, tabs : []}); ///////////////////////////////////// Overview table //////////////////////////////////////////// var tabOverview = $("<div/>"); tabPane.kbaseTabs('addTab', {tab: 'Overview', content: tabOverview, canDelete : false, show: true}); var tableOver = $('<table class="table table-striped table-bordered" '+ 'style="width: 100%; margin-left: 0px; margin-right: 0px;" id="'+self.pref+'overview-table"/>'); tabOverview.append(tableOver); tableOver .append( self.makeRow( 'Annotated genome', $('<span />').append(self.genomeName).css('font-style', 'italic') .append("<br /><a href='" + self.landingPageURL + self.genomeRef + "' target='_blank'>" + self.genomeRef + "</a>") ) ) .append( self.makeRow( 'Domain models set', self.domainSetName ) ) .append( self.makeRow( 'Annotated genes', self.annotatedGenesCount ) ) .append( self.makeRow( 'Annotated domains', self.annotatedDomainsCount) ); ///////////////////////////////////// Domains table //////////////////////////////////////////// var tabDomains = $("<div/>"); tabPane.kbaseTabs('addTab', {tab: 'Domains', content: tabDomains, canDelete : false, show: false}); var tableDomains = $('<table class="table table-striped table-bordered" '+ 'style="width: 100%; margin-left: 0px; margin-right: 0px;" id="'+self.pref+'domain-table"/>'); tabDomains.append(tableDomains); var domainTableSettings = { "sPaginationType": "full_numbers", "iDisplayLength": 10, "aaData": [], "aaSorting": [[ 2, "asc" ], [0, "asc"]], "aoColumns": [ { "sTitle": "Domain", 'mData': 'id'}, { "sTitle": "Description", 'mData': 'description'}, { "sTitle": "#Genes", 'mData': 'geneCount'}, { "sTitle": "Genes", 'mData': 'geneRefs'}, ], "oLanguage": { "sEmptyTable": "No domains found!", "sSearch": "Search: " }, 'fnDrawCallback': events }; var domainsTableData = []; var domains = self.domains; for(var domainId in domains){ var domain = domains[domainId]; // Build concatenated list of gene references var geneRefs = ""; for(var i = 0; i < domain.genes.length; i++){ gene = domain.genes[i]; if( i > 0 ) { geneRefs += '<br />'; } geneRefs += '<a class="show-gene' + self.pref + '"' + ' data-id="' + gene['geneId'] + '"' + ' data-contigId="' + gene['contigId'] + '"' + ' data-geneIndex="' + gene['geneIndex'] + '"' + '>' + gene['geneId'] + '</a>'; } // add table data row domainsTableData.push( { //id: '<a class="' + self.pref + 'gene-click" data-domainid="' + domainId + '">' + domainId + '</a>', id: domainId, description: domain.description, geneCount: domain.genes.length, geneRefs: geneRefs } ); }; domainTableSettings.aaData = domainsTableData; tableDomains.dataTable(domainTableSettings); ///////////////////////////////////// Events //////////////////////////////////////////// function events() { $('.show-gene'+self.pref).unbind('click'); $('.show-gene'+self.pref).click(function() { var id = $(this).attr('data-id'); var contigId = $(this).attr('data-contigId'); var geneIndex = $(this).attr('data-geneIndex'); if (tabPane.kbaseTabs('hasTab', id)) { tabPane.kbaseTabs('showTab', id); return; } ////////////////////////////// Build Gene Domains table ////////////////////////////// var tabContent = $("<div/>"); var tableGeneDomains = $('<table class="table table-striped table-bordered" '+ 'style="width: 100%; margin-left: 0px; margin-right: 0px;" id="' + self.pref + id + '-table"/>'); tabContent.append(tableGeneDomains); var geneDomainTableSettings = { "sPaginationType": "full_numbers", "iDisplayLength": 10, "aaData": [], "aaSorting": [[ 3, "asc" ], [5, "desc"]], "aoColumns": [ {sTitle: "Domain", mData: "domainId"}, {sTitle: "Description", mData: "domainDescription", sWidth:"30%"}, {sTitle: "Location", mData: "image"}, {sTitle: "Start", mData: "domainStart"}, {sTitle: "End", mData: "domainEnd"}, {sTitle: "eValue", mData: "eValue"}, ], "oLanguage": { "sEmptyTable": "No domains found!", "sSearch": "Search: " } }; var geneDomainsTableData = []; var gene = self.domainAnnotationData.data[contigId][geneIndex]; var geneId = gene[0]; var geneStart = gene[1]; var geneEnd = gene[2]; var domainsInfo = gene[4]; for(var domainId in domainsInfo){ var domainsArray = domainsInfo[domainId]; for(var i = 0 ; i < domainsArray.length; i++){ var domainStart = domainsArray[i][0]; var domainEnd = domainsArray[i][1]; var eValue = domainsArray[i][2]; var geneLength = (geneEnd - geneStart + 1)/3; var domainImgWidth = (domainEnd - domainStart)*100/geneLength; var domainImgleftShift = (domainStart)*100/geneLength; geneDomainsTableData.push({ 'contigId' : contigId, 'geneId' : geneId, 'geneStart' : geneStart, 'geneEnd' : geneEnd, 'domainId' : domainId, 'domainDescription' : self.domainAccession2Description[domainId], 'domainStart': domainStart, 'domainEnd' : domainEnd, 'eValue' : eValue, 'image' : '<div style="widht: 100%; height:100%; vertical-align: middle; margin-top: 1em; margin-bottom: 1em;">' + '<div style="position:relative; border: 1px solid gray; width:100%; height:2px;">' + '<div style="position:relative; left: ' + domainImgleftShift +'%;' + ' width:' + domainImgWidth + '%;' + ' top: -5px; height:10px; background-color:red;"/></div>' + '</div>' }); } } geneDomainTableSettings.aaData = geneDomainsTableData; tableGeneDomains.dataTable(geneDomainTableSettings); tabPane.kbaseTabs('addTab', {tab: id, content: tabContent, canDelete : true, show: true}); }); }; }); }); }, prepareVizData: function(){ var self = this; var dad = self.domainAnnotationData; var domains = {}; var domainsCount = 0; var genesCount = 0; for(var contigId in dad.data){ var genesArray = dad.data[contigId]; for(var i = 0 ; i < genesArray.length; i++){ var geneId = genesArray[i][0]; // var geneStart = genesArray[i][1]; // var geneEnd = genesArray[i][2]; var domainsInfo = genesArray[i][4]; if( $.isEmptyObject(domainsInfo)) continue; // If we have somthing in domainsIno, then the gene was anntoated genesCount ++; for(var domainId in domainsInfo){ var domainData = domains[domainId]; if(typeof domainData === 'undefined'){ domainData = { id: domainId, description: self.domainAccession2Description[domainId], genes: [] }; domains[domainId] = domainData; domainsCount++; } domainData.genes.push( { geneId: geneId, contigId: contigId, geneIndex: i } ); } } self.domains = domains; self.annotatedDomainsCount = domainsCount; self.annotatedGenesCount = genesCount; } }, makeRow: function(name, value) { var $row = $("<tr/>") .append($("<th />").css('width','20%').append(name)) .append($("<td />").append(value)); return $row; }, getData: function() { return { type: 'DomainAnnotation', id: this.options.domainAnnotationID, workspace: this.options.workspaceID, title: 'Domain Annotation' }; }, loading: function(isLoading) { if (isLoading) this.showMessage("<img src='" + this.options.loadingImage + "'/>"); else this.hideMessage(); }, showMessage: function(message) { var span = $("<span>").append(message); this.$messagePane.append(span); this.$messagePane.show(); }, hideMessage: function() { this.$messagePane.hide(); this.$messagePane.empty(); }, 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); }); }, buildObjectIdentity: function(workspaceID, objectID, objectVer, wsRef) { var obj = {}; if (wsRef) { obj['ref'] = wsRef; } else { if (/^\d+$/.exec(workspaceID)) obj['wsid'] = workspaceID; else obj['workspace'] = workspaceID; // same for the id if (/^\d+$/.exec(objectID)) obj['objid'] = objectID; else obj['name'] = objectID; if (objectVer) obj['ver'] = objectVer; } return obj; }, clientError: function(error){ this.loading(false); this.showMessage(error.error.error); } }); })( jQuery );
{ _template:"leavemealone", setObject:[ { object:"mapmeta", property:"stage1", value:{nextLevel:"stage2"} }, { object:"mapobjects", property:"stage1", value:{ items:[ {objecttype:"player", x:40, y:180, side:1}, {objecttype:"squid", x:80, y:40, side:1}, {objecttype:"squid", x:140, y:40, side:1}, {objecttype:"squid", x:220, y:40, side:1} ] } }, { object:"tilemaps", property:"stage1", value:help.finalizeTilemap({ tileset:"tiles", map:[ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,null,null,null,null,null,null,0,0,null,null,null,null,null,null,0], [0,null,null,0,0,0,null,null,null,null,0,0,0,null,null,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,0,null,null,null,null,null,null,null,null,null,null,null,null,0,0], [0,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ] }) } ] }
module.exports = function LoadProjectActions(actions) { actions.load( require('./routes/generate'), { id: 'routes/generate', uri: require.resolve('./routes/generate') } ) }
'use strict'; var fs = require('fs'); var broccoli = require('broccoli'); var assert = require('assert'); var templateCompilerFilter = require('../index'); var builder; describe('templateCompilerFilter', function(){ var sourcePath = 'test/fixtures'; afterEach(function() { if (builder) { builder.cleanup(); } }); var htmlbarsOptions, htmlbarsPrecompile; beforeEach(function() { htmlbarsOptions = { isHTMLBars: true, templateCompiler: require('../bower_components/ember/ember-template-compiler') }; htmlbarsPrecompile = htmlbarsOptions.templateCompiler.precompile; }); it('precompiles templates into htmlbars', function(){ var tree = templateCompilerFilter(sourcePath, htmlbarsOptions); builder = new broccoli.Builder(tree); return builder.build().then(function(results) { var actual = fs.readFileSync(results.directory + '/template.js', { encoding: 'utf8'}); var source = fs.readFileSync(sourcePath + '/template.hbs', { encoding: 'utf8' }); var expected = 'export default Ember.HTMLBars.template(' + htmlbarsPrecompile(source, { moduleName: 'template.hbs' }) + ');'; assert.equal(actual,expected,'They dont match!'); }); }); it('ignores utf-8 byte order marks', function(){ var tree = templateCompilerFilter(sourcePath, htmlbarsOptions); builder = new broccoli.Builder(tree); return builder.build().then(function(results) { var actual = fs.readFileSync(results.directory + '/template-with-bom.js', { encoding: 'utf8'}); var source = fs.readFileSync(sourcePath + '/template.hbs', { encoding: 'utf8' }); var expected = 'export default Ember.HTMLBars.template(' + htmlbarsPrecompile(source, { moduleName: 'template-with-bom.hbs' }) + ');'; assert.equal(actual,expected,'They dont match!'); }); }); it('passes FEATURES to compiler when provided as `FEATURES` [DEPRECATED]', function(){ htmlbarsOptions.FEATURES = { 'ember-htmlbars-component-generation': true }; var tree = templateCompilerFilter(sourcePath, htmlbarsOptions); builder = new broccoli.Builder(tree); return builder.build().then(function(results) { var actual = fs.readFileSync(results.directory + '/web-component-template.js', { encoding: 'utf8'}); var source = fs.readFileSync(sourcePath + '/web-component-template.hbs', { encoding: 'utf8' }); var expected = 'export default Ember.HTMLBars.template(' + htmlbarsPrecompile(source, { moduleName: 'web-component-template.hbs' }) + ');'; assert.equal(actual,expected,'They dont match!'); }); }); it('passes FEATURES to compiler when provided as `EmberENV.FEATURES`', function(){ htmlbarsOptions.EmberENV = { FEATURES: { 'ember-htmlbars-component-generation': true } }; var tree = templateCompilerFilter(sourcePath, htmlbarsOptions); builder = new broccoli.Builder(tree); return builder.build().then(function(results) { var actual = fs.readFileSync(results.directory + '/web-component-template.js', { encoding: 'utf8'}); var source = fs.readFileSync(sourcePath + '/web-component-template.hbs', { encoding: 'utf8' }); var expected = 'export default Ember.HTMLBars.template(' + htmlbarsPrecompile(source, { moduleName: 'web-component-template.hbs' }) + ');'; assert.equal(actual,expected,'They dont match!'); }); }); });
/* Longclick Event Copyright (c) 2010 Petr Vostrel (http://petr.vostrel.cz/) Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses. Version: 0.3.2 Updated: 2010-06-22 */ (function(a){function n(b){a.each("touchstart touchmove touchend touchcancel".split(/ /),function(d,e){b.addEventListener(e,function(){a(b).trigger(e)},false)});return a(b)}function j(b){function d(){a(e).data(h,true);b.type=f;jQuery.event.handle.apply(e,o)}if(!a(this).data(g)){var e=this,o=arguments;a(this).data(h,false).data(g,setTimeout(d,a(this).data(i)||a.longclick.duration))}}function k(){a(this).data(g,clearTimeout(a(this).data(g))||null)}function l(b){if(a(this).data(h))return b.stopImmediatePropagation()|| false}var p=a.fn.click;a.fn.click=function(b,d){if(!d)return p.apply(this,arguments);return a(this).data(i,b||null).bind(f,d)};a.fn.longclick=function(){var b=[].splice.call(arguments,0),d=b.pop();b=b.pop();var e=a(this).data(i,b||null);return d?e.click(b,d):e.trigger(f)};a.longclick={duration:500};a.event.special.longclick={setup:function(){/iphone|ipad|ipod/i.test(navigator.userAgent)?n(this).bind(q,j).bind([r,s,t].join(" "),k).bind(m,l).css({WebkitUserSelect:"none"}):a(this).bind(u,j).bind([v, w,x,y].join(" "),k).bind(m,l)},teardown:function(){a(this).unbind(c)}};var f="longclick",c="."+f,u="mousedown"+c,m="click"+c,v="mousemove"+c,w="mouseup"+c,x="mouseout"+c,y="contextmenu"+c,q="touchstart"+c,r="touchend"+c,s="touchmove"+c,t="touchcancel"+c,i="duration"+c,g="timer"+c,h="fired"+c})(jQuery);
import HelloWorld from '../components/hello-world' export default function Home() { return ( <div className="app"> <HelloWorld /> </div> ) }
/** * @fileoverview Tests for options. * @author George Zahariev */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const assert = require("chai").assert, options = require("../../lib/options"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ /* * This is testing the interface of the options object. */ describe("options", () => { describe("--help", () => { it("should return true for .help when passed", () => { const currentOptions = options.parse("--help"); assert.isTrue(currentOptions.help); }); }); describe("-h", () => { it("should return true for .help when passed", () => { const currentOptions = options.parse("-h"); assert.isTrue(currentOptions.help); }); }); describe("--config", () => { it("should return a string for .config when passed a string", () => { const currentOptions = options.parse("--config file"); assert.isString(currentOptions.config); assert.strictEqual(currentOptions.config, "file"); }); }); describe("-c", () => { it("should return a string for .config when passed a string", () => { const currentOptions = options.parse("-c file"); assert.isString(currentOptions.config); assert.strictEqual(currentOptions.config, "file"); }); }); describe("--ext", () => { it("should return an array with one item when passed .jsx", () => { const currentOptions = options.parse("--ext .jsx"); assert.isArray(currentOptions.ext); assert.strictEqual(currentOptions.ext[0], ".jsx"); }); it("should return an array with two items when passed .js and .jsx", () => { const currentOptions = options.parse("--ext .jsx --ext .js"); assert.isArray(currentOptions.ext); assert.strictEqual(currentOptions.ext[0], ".jsx"); assert.strictEqual(currentOptions.ext[1], ".js"); }); it("should return an array with two items when passed .jsx,.js", () => { const currentOptions = options.parse("--ext .jsx,.js"); assert.isArray(currentOptions.ext); assert.strictEqual(currentOptions.ext[0], ".jsx"); assert.strictEqual(currentOptions.ext[1], ".js"); }); it("should not exist when not passed", () => { const currentOptions = options.parse(""); assert.notProperty(currentOptions, "ext"); }); }); describe("--rulesdir", () => { it("should return a string for .rulesdir when passed a string", () => { const currentOptions = options.parse("--rulesdir /morerules"); assert.isArray(currentOptions.rulesdir); assert.deepStrictEqual(currentOptions.rulesdir, ["/morerules"]); }); }); describe("--format", () => { it("should return a string for .format when passed a string", () => { const currentOptions = options.parse("--format compact"); assert.isString(currentOptions.format); assert.strictEqual(currentOptions.format, "compact"); }); it("should return stylish for .format when not passed", () => { const currentOptions = options.parse(""); assert.isString(currentOptions.format); assert.strictEqual(currentOptions.format, "stylish"); }); }); describe("-f", () => { it("should return a string for .format when passed a string", () => { const currentOptions = options.parse("-f compact"); assert.isString(currentOptions.format); assert.strictEqual(currentOptions.format, "compact"); }); }); describe("--version", () => { it("should return true for .version when passed", () => { const currentOptions = options.parse("--version"); assert.isTrue(currentOptions.version); }); }); describe("-v", () => { it("should return true for .version when passed", () => { const currentOptions = options.parse("-v"); assert.isTrue(currentOptions.version); }); }); describe("when asking for help", () => { it("should return string of help text when called", () => { const helpText = options.generateHelp(); assert.isString(helpText); }); }); describe("--no-ignore", () => { it("should return false for .ignore when passed", () => { const currentOptions = options.parse("--no-ignore"); assert.isFalse(currentOptions.ignore); }); }); describe("--ignore-path", () => { it("should return a string for .ignorePath when passed", () => { const currentOptions = options.parse("--ignore-path .gitignore"); assert.strictEqual(currentOptions.ignorePath, ".gitignore"); }); }); describe("--ignore-pattern", () => { it("should return a string array for .ignorePattern when passed", () => { const currentOptions = options.parse("--ignore-pattern *.js"); assert.ok(currentOptions.ignorePattern); assert.strictEqual(currentOptions.ignorePattern.length, 1); assert.strictEqual(currentOptions.ignorePattern[0], "*.js"); }); it("should return a string array for multiple values", () => { const currentOptions = options.parse("--ignore-pattern *.js --ignore-pattern *.ts"); assert.ok(currentOptions.ignorePattern); assert.strictEqual(currentOptions.ignorePattern.length, 2); assert.strictEqual(currentOptions.ignorePattern[0], "*.js"); assert.strictEqual(currentOptions.ignorePattern[1], "*.ts"); }); it("should return a string array of properly parsed values, when those values include commas", () => { const currentOptions = options.parse("--ignore-pattern *.js --ignore-pattern foo-{bar,baz}.js"); assert.ok(currentOptions.ignorePattern); assert.strictEqual(currentOptions.ignorePattern.length, 2); assert.strictEqual(currentOptions.ignorePattern[0], "*.js"); assert.strictEqual(currentOptions.ignorePattern[1], "foo-{bar,baz}.js"); }); }); describe("--color", () => { it("should return true for .color when passed --color", () => { const currentOptions = options.parse("--color"); assert.isTrue(currentOptions.color); }); it("should return false for .color when passed --no-color", () => { const currentOptions = options.parse("--no-color"); assert.isFalse(currentOptions.color); }); }); describe("--stdin", () => { it("should return true for .stdin when passed", () => { const currentOptions = options.parse("--stdin"); assert.isTrue(currentOptions.stdin); }); }); describe("--stdin-filename", () => { it("should return a string for .stdinFilename when passed", () => { const currentOptions = options.parse("--stdin-filename test.js"); assert.strictEqual(currentOptions.stdinFilename, "test.js"); }); }); describe("--global", () => { it("should return an array for a single occurrence", () => { const currentOptions = options.parse("--global foo"); assert.isArray(currentOptions.global); assert.strictEqual(currentOptions.global.length, 1); assert.strictEqual(currentOptions.global[0], "foo"); }); it("should split variable names using commas", () => { const currentOptions = options.parse("--global foo,bar"); assert.isArray(currentOptions.global); assert.strictEqual(currentOptions.global.length, 2); assert.strictEqual(currentOptions.global[0], "foo"); assert.strictEqual(currentOptions.global[1], "bar"); }); it("should not split on colons", () => { const currentOptions = options.parse("--global foo:false,bar:true"); assert.isArray(currentOptions.global); assert.strictEqual(currentOptions.global.length, 2); assert.strictEqual(currentOptions.global[0], "foo:false"); assert.strictEqual(currentOptions.global[1], "bar:true"); }); it("should concatenate successive occurrences", () => { const currentOptions = options.parse("--global foo:true --global bar:false"); assert.isArray(currentOptions.global); assert.strictEqual(currentOptions.global.length, 2); assert.strictEqual(currentOptions.global[0], "foo:true"); assert.strictEqual(currentOptions.global[1], "bar:false"); }); }); describe("--plugin", () => { it("should return an array when passed a single occurrence", () => { const currentOptions = options.parse("--plugin single"); assert.isArray(currentOptions.plugin); assert.strictEqual(currentOptions.plugin.length, 1); assert.strictEqual(currentOptions.plugin[0], "single"); }); it("should return an array when passed a comma-delimited string", () => { const currentOptions = options.parse("--plugin foo,bar"); assert.isArray(currentOptions.plugin); assert.strictEqual(currentOptions.plugin.length, 2); assert.strictEqual(currentOptions.plugin[0], "foo"); assert.strictEqual(currentOptions.plugin[1], "bar"); }); it("should return an array when passed multiple times", () => { const currentOptions = options.parse("--plugin foo --plugin bar"); assert.isArray(currentOptions.plugin); assert.strictEqual(currentOptions.plugin.length, 2); assert.strictEqual(currentOptions.plugin[0], "foo"); assert.strictEqual(currentOptions.plugin[1], "bar"); }); }); describe("--quiet", () => { it("should return true for .quiet when passed", () => { const currentOptions = options.parse("--quiet"); assert.isTrue(currentOptions.quiet); }); }); describe("--max-warnings", () => { it("should return correct value for .maxWarnings when passed", () => { const currentOptions = options.parse("--max-warnings 10"); assert.strictEqual(currentOptions.maxWarnings, 10); }); it("should return -1 for .maxWarnings when not passed", () => { const currentOptions = options.parse(""); assert.strictEqual(currentOptions.maxWarnings, -1); }); it("should throw an error when supplied with a non-integer", () => { assert.throws(() => { options.parse("--max-warnings 10.2"); }, /Invalid value for option 'max-warnings' - expected type Int/u); }); }); describe("--init", () => { it("should return true for --init when passed", () => { const currentOptions = options.parse("--init"); assert.isTrue(currentOptions.init); }); }); describe("--fix", () => { it("should return true for --fix when passed", () => { const currentOptions = options.parse("--fix"); assert.isTrue(currentOptions.fix); }); }); describe("--fix-type", () => { it("should return one value with --fix-type is passed", () => { const currentOptions = options.parse("--fix-type problem"); assert.strictEqual(currentOptions.fixType.length, 1); assert.strictEqual(currentOptions.fixType[0], "problem"); }); it("should return two values when --fix-type is passed twice", () => { const currentOptions = options.parse("--fix-type problem --fix-type suggestion"); assert.strictEqual(currentOptions.fixType.length, 2); assert.strictEqual(currentOptions.fixType[0], "problem"); assert.strictEqual(currentOptions.fixType[1], "suggestion"); }); it("should return two values when --fix-type is passed a comma-separated value", () => { const currentOptions = options.parse("--fix-type problem,suggestion"); assert.strictEqual(currentOptions.fixType.length, 2); assert.strictEqual(currentOptions.fixType[0], "problem"); assert.strictEqual(currentOptions.fixType[1], "suggestion"); }); }); describe("--debug", () => { it("should return true for --debug when passed", () => { const currentOptions = options.parse("--debug"); assert.isTrue(currentOptions.debug); }); }); describe("--inline-config", () => { it("should return false when passed --no-inline-config", () => { const currentOptions = options.parse("--no-inline-config"); assert.isFalse(currentOptions.inlineConfig); }); it("should return true for --inline-config when empty", () => { const currentOptions = options.parse(""); assert.isTrue(currentOptions.inlineConfig); }); }); describe("--parser", () => { it("should return a string for --parser when passed", () => { const currentOptions = options.parse("--parser test"); assert.strictEqual(currentOptions.parser, "test"); }); }); describe("--print-config", () => { it("should return file path when passed --print-config", () => { const currentOptions = options.parse("--print-config file.js"); assert.strictEqual(currentOptions.printConfig, "file.js"); }); }); });
module.exports={A:{A:{"2":"H D G E A B fB"},B:{"2":"1 C p J L N I"},C:{"2":"1 3 dB FB F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m bB VB","194":"0 2 5 6 7 8 9 n o M q r s t u v w x y z BB CB DB"},D:{"1":"KB IB gB LB MB NB","2":"0 1 3 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z","322":"2 5 6 7 8 9 BB CB DB GB PB"},E:{"2":"F K H D G E A B C OB HB QB RB SB TB UB c WB"},F:{"2":"3 E B C J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n XB YB ZB aB c EB cB AB","322":"0 o M q r s t u v w x y z"},G:{"2":"4 G HB eB JB hB iB jB kB lB mB nB oB pB qB"},H:{"2":"rB"},I:{"1":"GB","2":"4 FB F sB tB uB vB wB xB"},J:{"2":"D A"},K:{"2":"A B C M c EB AB"},L:{"1":"IB"},M:{"194":"2"},N:{"2":"A B"},O:{"2":"yB"},P:{"2":"F K zB 0B"},Q:{"2":"1B"},R:{"2":"2B"}},B:1,C:"OffscreenCanvas"};
/* 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.string.BidiComplex"]){ dojo._hasResource["dojox.string.BidiComplex"]=true; dojo.provide("dojox.string.BidiComplex"); dojo.experimental("dojox.string.BidiComplex"); (function(){ var _1=[]; dojox.string.BidiComplex.attachInput=function(_2,_3){ _2.alt=_3; dojo.connect(_2,"onkeydown",this,"_ceKeyDown"); dojo.connect(_2,"onkeyup",this,"_ceKeyUp"); dojo.connect(_2,"oncut",this,"_ceCutText"); dojo.connect(_2,"oncopy",this,"_ceCopyText"); _2.value=dojox.string.BidiComplex.createDisplayString(_2.value,_2.alt); }; dojox.string.BidiComplex.createDisplayString=function(_4,_5){ _4=dojox.string.BidiComplex.stripSpecialCharacters(_4); var _6=dojox.string.BidiComplex._parse(_4,_5); var _7="‪"+_4; var _8=1; dojo.forEach(_6,function(n){ if(n!=null){ var _9=_7.substring(0,n+_8); var _a=_7.substring(n+_8,_7.length); _7=_9+"‎"+_a; _8++; } }); return _7; }; dojox.string.BidiComplex.stripSpecialCharacters=function(_b){ return _b.replace(/[\u200E\u200F\u202A-\u202E]/g,""); }; dojox.string.BidiComplex._ceKeyDown=function(_c){ var _d=dojo.isIE?_c.srcElement:_c.target; _1=_d.value; }; dojox.string.BidiComplex._ceKeyUp=function(_e){ var _f="‎"; var _10=dojo.isIE?_e.srcElement:_e.target; var _11=_10.value; var _12=_e.keyCode; if((_12==dojo.keys.HOME)||(_12==dojo.keys.END)||(_12==dojo.keys.SHIFT)){ return; } var _13,_14; var _15=dojox.string.BidiComplex._getCaretPos(_e,_10); if(_15){ _13=_15[0]; _14=_15[1]; } if(dojo.isIE){ var _16=_13,_17=_14; if(_12==dojo.keys.LEFT_ARROW){ if((_11.charAt(_14-1)==_f)&&(_13==_14)){ dojox.string.BidiComplex._setSelectedRange(_10,_13-1,_14-1); } return; } if(_12==dojo.keys.RIGHT_ARROW){ if(_11.charAt(_14-1)==_f){ _17=_14+1; if(_13==_14){ _16=_13+1; } } dojox.string.BidiComplex._setSelectedRange(_10,_16,_17); return; } }else{ if(_12==dojo.keys.LEFT_ARROW){ if(_11.charAt(_14-1)==_f){ dojox.string.BidiComplex._setSelectedRange(_10,_13-1,_14-1); } return; } if(_12==dojo.keys.RIGHT_ARROW){ if(_11.charAt(_14-1)==_f){ dojox.string.BidiComplex._setSelectedRange(_10,_13+1,_14+1); } return; } } var _18=dojox.string.BidiComplex.createDisplayString(_11,_10.alt); if(_11!=_18){ window.status=_11+" c="+_14; _10.value=_18; if((_12==dojo.keys.DELETE)&&(_18.charAt(_14)==_f)){ _10.value=_18.substring(0,_14)+_18.substring(_14+2,_18.length); } if(_12==dojo.keys.DELETE){ dojox.string.BidiComplex._setSelectedRange(_10,_13,_14); }else{ if(_12==dojo.keys.BACKSPACE){ if((_1.length>=_14)&&(_1.charAt(_14-1)==_f)){ dojox.string.BidiComplex._setSelectedRange(_10,_13-1,_14-1); }else{ dojox.string.BidiComplex._setSelectedRange(_10,_13,_14); } }else{ if(_10.value.charAt(_14)!=_f){ dojox.string.BidiComplex._setSelectedRange(_10,_13+1,_14+1); } } } } }; dojox.string.BidiComplex._processCopy=function(_19,_1a,_1b){ if(_1a==null){ if(dojo.isIE){ var _1c=document.selection.createRange(); _1a=_1c.text; }else{ _1a=_19.value.substring(_19.selectionStart,_19.selectionEnd); } } var _1d=dojox.string.BidiComplex.stripSpecialCharacters(_1a); if(dojo.isIE){ window.clipboardData.setData("Text",_1d); } return true; }; dojox.string.BidiComplex._ceCopyText=function(_1e){ if(dojo.isIE){ _1e.returnValue=false; } return dojox.string.BidiComplex._processCopy(_1e,null,false); }; dojox.string.BidiComplex._ceCutText=function(_1f){ var ret=dojox.string.BidiComplex._processCopy(_1f,null,false); if(!ret){ return false; } if(dojo.isIE){ document.selection.clear(); }else{ var _20=_1f.selectionStart; _1f.value=_1f.value.substring(0,_20)+_1f.value.substring(_1f.selectionEnd); _1f.setSelectionRange(_20,_20); } return true; }; dojox.string.BidiComplex._getCaretPos=function(_21,_22){ if(dojo.isIE){ var _23=0,_24=document.selection.createRange().duplicate(),_25=_24.duplicate(),_26=_24.text.length; if(_22.type=="textarea"){ _25.moveToElementText(_22); }else{ _25.expand("textedit"); } while(_24.compareEndPoints("StartToStart",_25)>0){ _24.moveStart("character",-1); ++_23; } return [_23,_23+_26]; } return [_21.target.selectionStart,_21.target.selectionEnd]; }; dojox.string.BidiComplex._setSelectedRange=function(_27,_28,_29){ if(dojo.isIE){ var _2a=_27.createTextRange(); if(_2a){ if(_27.type=="textarea"){ _2a.moveToElementText(_27); }else{ _2a.expand("textedit"); } _2a.collapse(); _2a.moveEnd("character",_29); _2a.moveStart("character",_28); _2a.select(); } }else{ _27.selectionStart=_28; _27.selectionEnd=_29; } }; var _2b=function(c){ return (c>="0"&&c<="9")||(c>"ÿ"); }; var _2c=function(c){ return (c>="A"&&c<="Z")||(c>="a"&&c<="z"); }; var _2d=function(_2e,i,_2f){ while(i>0){ if(i==_2f){ return false; } i--; if(_2b(_2e.charAt(i))){ return true; } if(_2c(_2e.charAt(i))){ return false; } } return false; }; dojox.string.BidiComplex._parse=function(str,_30){ var _31=-1,_32=[]; var _33={FILE_PATH:"/\\:.",URL:"/:.?=&#",XPATH:"/\\:.<>=[]",EMAIL:"<>@.,;"}[_30]; switch(_30){ case "FILE_PATH": case "URL": case "XPATH": dojo.forEach(str,function(ch,i){ if(_33.indexOf(ch)>=0&&_2d(str,i,_31)){ _31=i; _32.push(i); } }); break; case "EMAIL": var _34=false; dojo.forEach(str,function(ch,i){ if(ch=="\""){ if(_2d(str,i,_31)){ _31=i; _32.push(i); } i++; var i1=str.indexOf("\"",i); if(i1>=i){ i=i1; } if(_2d(str,i,_31)){ _31=i; _32.push(i); } } if(_33.indexOf(ch)>=0&&_2d(str,i,_31)){ _31=i; _32.push(i); } }); } return _32; }; })(); }
var lexi = require('../'); var test = require('tape'); test('small numbers', function (t) { var prev = lexi.pack(0); for (var n = 1; n < 256*256*16; n ++) { var cur = lexi.pack(n, 'hex'); if (cur <= prev) t.fail('cur <= prev'); prev = cur; } t.end(); });
"use strict"; var _getIterator = require("babel-runtime/core-js/get-iterator")["default"]; var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"]; var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"]; exports.__esModule = true; var _helpersMemoiseDecorators = require("../../helpers/memoise-decorators"); var _helpersMemoiseDecorators2 = _interopRequireDefault(_helpersMemoiseDecorators); var _helpersDefineMap = require("../../helpers/define-map"); var defineMap = _interopRequireWildcard(_helpersDefineMap); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); var metadata = { stage: 1 }; exports.metadata = metadata; var visitor = { ObjectExpression: function ObjectExpression(_ref3, file) { var node = _ref3.node; var scope = _ref3.scope; var hasDecorators = false; for (var _iterator = (node.properties /*: Array*/), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var prop = _ref; if (prop.decorators) { hasDecorators = true; break; } } if (!hasDecorators) return; var mutatorMap = {}; for (var _iterator2 = (node.properties /*: Array*/), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _getIterator(_iterator2);;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var prop = _ref2; if (prop.decorators) _helpersMemoiseDecorators2["default"](prop.decorators, scope); if (prop.kind === "init" && !prop.method) { prop.kind = ""; prop.value = t.functionExpression(null, [], t.blockStatement([t.returnStatement(prop.value)])); } defineMap.push(mutatorMap, prop, "initializer", file); } var obj = defineMap.toClassObject(mutatorMap); obj = defineMap.toComputedObjectFromClass(obj); return t.callExpression(file.addHelper("create-decorated-object"), [obj]); } }; exports.visitor = visitor;
Object.defineProperty(exports, "__esModule", { value: true }); var file_system_1 = require("../file-system"); exports.debug = true; var applicationRootPath; function ensureAppRootPath() { if (!applicationRootPath) { applicationRootPath = file_system_1.knownFolders.currentApp().path; applicationRootPath = applicationRootPath.substr(0, applicationRootPath.length - "app/".length); } } var Source = (function () { function Source(uri, line, column) { ensureAppRootPath(); if (uri.length > applicationRootPath.length && uri.substr(0, applicationRootPath.length) === applicationRootPath) { this._uri = "file://" + uri.substr(applicationRootPath.length); } else { this._uri = uri; } this._line = line; this._column = column; } Object.defineProperty(Source.prototype, "uri", { get: function () { return this._uri; }, enumerable: true, configurable: true }); Object.defineProperty(Source.prototype, "line", { get: function () { return this._line; }, enumerable: true, configurable: true }); Object.defineProperty(Source.prototype, "column", { get: function () { return this._column; }, enumerable: true, configurable: true }); Source.prototype.toString = function () { return this._uri + ":" + this._line + ":" + this._column; }; Source.get = function (object) { return object[Source._source]; }; Source.set = function (object, src) { object[Source._source] = src; }; return Source; }()); Source._source = Symbol("source"); exports.Source = Source; //# sourceMappingURL=debug-common.js.map
'use strict'; module.exports = function (app) { class Bar111 extends app.Service { constructor(ctx) { super(ctx); } * get(name) { return { bar: 'bar111', }; } } return Bar111; };
var app = require('express')(), wizard = require('hmpo-form-wizard'), steps = require('./steps'), fields = require('./fields'); app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' })); app.use(wizard(steps, fields, { templatePath: 'prototype_oix_171004/throttle' })); module.exports = app;
'use strict'; /** * Starts the test runner which in turn loads test frameworks, * assertion libraries and then executes tests. * * Example Usage: * gulp test * gulp test --watch */ var gulp = require('gulp'), chalk = require('chalk'), args = require('yargs').argv, common = require('./_common'); // Attempt to load test suite package to see if it is present or not. var testSuiteWrapper = false; try { testSuiteWrapper = require('rehab-fe-skeleton-testsuite'); } catch(e) {} gulp.task('test', function(done) { if (!testSuiteWrapper) { console.log(chalk.bgRed.white(' FE Skeleton: Missing `rehab-fe-skeleton-testsuite` package. Please install in `devDependencies`.')); console.log(chalk.bgRed.white(' You can do so via `npm install rehab-fe-skeleton-testsuite --save-dev`.')); done(1); return; } var karmaSettings = { configFile: common.configPath }; if (args.watch) { karmaSettings.autoWatch = true; karmaSettings.singleRun = false; } testSuiteWrapper.runTests(karmaSettings, done); });
console.log("Test"); x_a(); function x_a() { // used before defined }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var protractor_1 = require("protractor"); describe('QuickStart E2E Tests', function () { var expectedMsg = 'Hello Angular'; beforeEach(function () { protractor_1.browser.get(''); }); it('should display: ' + expectedMsg, function () { expect(protractor_1.element(protractor_1.by.css('h1')).getText()).toEqual(expectedMsg); }); }); //# sourceMappingURL=app.e2e-spec.js.map
module.exports={A:{A:{"2":"H D G E A B fB"},B:{"2":"1 C p J L N I"},C:{"1":"0 1 2 3 5 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z BB CB DB","16":"dB FB bB VB"},D:{"1":"0 2 5 6 7 8 9 u v w x y z BB CB DB GB PB KB IB gB LB MB NB","16":"1 F K H D G E A B C p","132":"3 J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t"},E:{"1":"B C UB c WB","16":"F K OB HB","132":"H D G E A QB RB SB TB"},F:{"1":"0 h i j k l m n o M q r s t u v w x y z","16":"E B XB YB ZB aB c EB","132":"3 J L N I O P Q R S T U V W X Y Z a b d e f g","260":"C cB AB"},G:{"1":"nB oB pB qB","16":"4 HB eB JB hB","132":"G iB jB kB lB mB"},H:{"260":"rB"},I:{"1":"GB","16":"FB sB tB uB","132":"4 F vB wB xB"},J:{"16":"D","132":"A"},K:{"1":"M","16":"A B C c EB","260":"AB"},L:{"1":"IB"},M:{"1":"2"},N:{"2":"A B"},O:{"132":"yB"},P:{"1":"K zB 0B","132":"F"},Q:{"1":"1B"},R:{"2":"2B"}},B:7,C:":default CSS pseudo-class"};
var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); var testCase = require('../../deps/nodeunit').testCase, mongoO = require('../../lib/mongodb').pure(), debug = require('util').debug, inspect = require('util').inspect, Buffer = require('buffer').Buffer, gleak = require('../../tools/gleak'), fs = require('fs'), BSON = mongoO.BSON, Code = mongoO.Code, Binary = mongoO.Binary, Timestamp = mongoO.Timestamp, Long = mongoO.Long, MongoReply = mongoO.MongoReply, ObjectID = mongoO.ObjectID, Symbol = mongoO.Symbol, DBRef = mongoO.DBRef, Double = mongoO.Double, MinKey = mongoO.MinKey, MaxKey = mongoO.MaxKey, BinaryParser = mongoO.BinaryParser; var BSONSE = mongodb, BSONDE = mongodb; // for tests BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0; BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1; BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; BSONDE.BSON_BINARY_SUBTYPE_UUID = 3; BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4; BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0; BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1; BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; BSONSE.BSON_BINARY_SUBTYPE_UUID = 3; BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4; BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; var hexStringToBinary = exports.hexStringToBinary = function(string) { var numberofValues = string.length / 2; var array = ""; for(var i = 0; i < numberofValues; i++) { array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16)); } return array; } var assertBuffersEqual = function(test, buffer1, buffer2) { if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); for(var i = 0; i < buffer1.length; i++) { test.equal(buffer1[i], buffer2[i]); } } /** * Module for parsing an ISO 8601 formatted string into a Date object. */ var ISODate = function (string) { var match; if (typeof string.getTime === "function") return string; else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { var date = new Date(); date.setUTCFullYear(Number(match[1])); date.setUTCMonth(Number(match[3]) - 1 || 0); date.setUTCDate(Number(match[5]) || 0); date.setUTCHours(Number(match[7]) || 0); date.setUTCMinutes(Number(match[8]) || 0); date.setUTCSeconds(Number(match[10]) || 0); date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); if (match[13] && match[13] !== "Z") { var h = Number(match[16]) || 0, m = Number(match[17]) || 0; h *= 3600000; m *= 60000; var offset = h + m; if (match[15] == "+") offset = -offset; date = new Date(date.valueOf() + offset); } return date; } else throw new Error("Invalid ISO 8601 date given.", __filename); }; var tests = testCase({ setUp: function(callback) { callback(); }, tearDown: function(callback) { callback(); }, 'Should Correctly get BSON types from require' : function(test) { var _mongodb = require('../../lib/mongodb'); test.ok(_mongodb.ObjectID === ObjectID); test.ok(_mongodb.Binary === Binary); test.ok(_mongodb.Long === Long); test.ok(_mongodb.Timestamp === Timestamp); test.ok(_mongodb.Code === Code); test.ok(_mongodb.DBRef === DBRef); test.ok(_mongodb.Symbol === Symbol); test.ok(_mongodb.MinKey === MinKey); test.ok(_mongodb.MaxKey === MaxKey); test.ok(_mongodb.Double === Double); test.done(); }, 'Should Correctly Deserialize object' : function(test) { var bytes = [95,0,0,0,2,110,115,0,42,0,0,0,105,110,116,101,103,114,97,116,105,111,110,95,116,101,115,116,115,95,46,116,101,115,116,95,105,110,100,101,120,95,105,110,102,111,114,109,97,116,105,111,110,0,8,117,110,105,113,117,101,0,0,3,107,101,121,0,12,0,0,0,16,97,0,1,0,0,0,0,2,110,97,109,101,0,4,0,0,0,97,95,49,0,0]; var serialized_data = ''; // Convert to chars for(var i = 0; i < bytes.length; i++) { serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]); } var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(new Buffer(serialized_data, 'binary')); test.equal("a_1", object.name); test.equal(false, object.unique); test.equal(1, object.key.a); test.done(); }, 'Should Correctly Deserialize object with all types' : function(test) { var bytes = [26,1,0,0,7,95,105,100,0,161,190,98,75,118,169,3,0,0,3,0,0,4,97,114,114,97,121,0,26,0,0,0,16,48,0,1,0,0,0,16,49,0,2,0,0,0,16,50,0,3,0,0,0,0,2,115,116,114,105,110,103,0,6,0,0,0,104,101,108,108,111,0,3,104,97,115,104,0,19,0,0,0,16,97,0,1,0,0,0,16,98,0,2,0,0,0,0,9,100,97,116,101,0,161,190,98,75,0,0,0,0,7,111,105,100,0,161,190,98,75,90,217,18,0,0,1,0,0,5,98,105,110,97,114,121,0,7,0,0,0,2,3,0,0,0,49,50,51,16,105,110,116,0,42,0,0,0,1,102,108,111,97,116,0,223,224,11,147,169,170,64,64,11,114,101,103,101,120,112,0,102,111,111,98,97,114,0,105,0,8,98,111,111,108,101,97,110,0,1,15,119,104,101,114,101,0,25,0,0,0,12,0,0,0,116,104,105,115,46,120,32,61,61,32,51,0,5,0,0,0,0,3,100,98,114,101,102,0,37,0,0,0,2,36,114,101,102,0,5,0,0,0,116,101,115,116,0,7,36,105,100,0,161,190,98,75,2,180,1,0,0,2,0,0,0,10,110,117,108,108,0,0]; var serialized_data = ''; // Convert to chars for(var i = 0; i < bytes.length; i++) { serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]); } var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(new Buffer(serialized_data, 'binary'));//, false, true); // Perform tests test.equal("hello", object.string); test.deepEqual([1,2,3], object.array); test.equal(1, object.hash.a); test.equal(2, object.hash.b); test.ok(object.date != null); test.ok(object.oid != null); test.ok(object.binary != null); test.equal(42, object.int); test.equal(33.3333, object.float); test.ok(object.regexp != null); test.equal(true, object.boolean); test.ok(object.where != null); test.ok(object.dbref != null); test.ok(object[null] == null); test.done(); }, 'Should Serialize and Deserialize String' : function(test) { var test_string = {hello: 'world'}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_string, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_string)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_string, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_string, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); test.done(); }, 'Should Serialize and Deserialize Empty String' : function(test) { var test_string = {hello: ''}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_string, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_string)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_string, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_string, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); test.done(); }, 'Should Correctly Serialize and Deserialize Integer' : function(test) { var test_number = {doc: 5}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_number, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_number)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_number, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data2)); test.done(); }, 'Should Correctly Serialize and Deserialize null value' : function(test) { var test_null = {doc:null}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_null, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_null)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_null, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.equal(null, object.doc); test.done(); }, 'Should Correctly Serialize and Deserialize Number' : function(test) { var test_number = {doc: 5.5}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_number, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_number)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_number, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); test.done(); }, 'Should Correctly Serialize and Deserialize Integer' : function(test) { var test_int = {doc: 42}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); test_int = {doc: -5600}; serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); test_int = {doc: 2147483647}; serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); test_int = {doc: -2147483648}; serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); test.done(); }, 'Should Correctly Serialize and Deserialize Object' : function(test) { var doc = {doc: {age: 42, name: 'Spongebob', shoe_size: 9.5}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(doc.doc.age, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.age); test.deepEqual(doc.doc.name, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.name); test.deepEqual(doc.doc.shoe_size, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.shoe_size); test.done(); }, 'Should Correctly Serialize and Deserialize Array' : function(test) { var doc = {doc: [1, 2, 'a', 'b']}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.equal(doc.doc[0], deserialized.doc[0]) test.equal(doc.doc[1], deserialized.doc[1]) test.equal(doc.doc[2], deserialized.doc[2]) test.equal(doc.doc[3], deserialized.doc[3]) test.done(); }, 'Should Correctly Serialize and Deserialize Array with added on functions' : function(test) { Array.prototype.toXml = function() {}; var doc = {doc: [1, 2, 'a', 'b']}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.equal(doc.doc[0], deserialized.doc[0]) test.equal(doc.doc[1], deserialized.doc[1]) test.equal(doc.doc[2], deserialized.doc[2]) test.equal(doc.doc[3], deserialized.doc[3]) test.done(); }, 'Should correctly deserialize a nested object' : function(test) { var doc = {doc: {doc:1}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(doc.doc.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.doc); test.done(); }, 'Should Correctly Serialize and Deserialize A Boolean' : function(test) { var doc = {doc: true}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.equal(doc.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); test.done(); }, 'Should Correctly Serialize and Deserialize a Date' : function(test) { var date = new Date(); //(2009, 11, 12, 12, 00, 30) date.setUTCDate(12); date.setUTCFullYear(2009); date.setUTCMonth(11 - 1); date.setUTCHours(12); date.setUTCMinutes(0); date.setUTCSeconds(30); var doc = {doc: date}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.equal(doc.date, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.date); test.done(); }, 'Should Correctly Serialize nested doc' : function(test) { var doc = { string: "Strings are great", decimal: 3.14159265, bool: true, integer: 5, subObject: { moreText: "Bacon ipsum dolor.", longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly." }, subArray: [1,2,3,4,5,6,7,8,9,10], anotherString: "another string" } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.done(); }, 'Should Correctly Serialize and Deserialize Oid' : function(test) { var doc = {doc: new ObjectID()}; var doc2 = {doc: ObjectID.createFromHexString(doc.doc.toHexString())}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); delete doc.doc.__id; test.deepEqual(doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); test.done(); }, 'Should Correctly encode Empty Hash' : function(test) { var doc = {}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); test.deepEqual(doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); test.done(); }, 'Should Correctly Serialize and Deserialize Ordered Hash' : function(test) { var doc = {doc: {b:1, a:2, c:3, d:4}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var decoded_hash = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc; var keys = []; for(var name in decoded_hash) keys.push(name); test.deepEqual(['b', 'a', 'c', 'd'], keys); test.done(); }, 'Should Correctly Serialize and Deserialize Regular Expression' : function(test) { // Serialize the regular expression var doc = {doc: /foobar/mi}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc.toString(), doc2.doc.toString()); test.done(); }, 'Should Correctly Serialize and Deserialize a Binary object' : function(test) { var bin = new Binary(); var string = 'binstring'; for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)); } var doc = {doc: bin}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); test.done(); }, 'Should Correctly Serialize and Deserialize a big Binary object' : function(test) { var data = fs.readFileSync("test/gridstore/test_gs_weird_bug.png", 'binary'); var bin = new Binary(); bin.write(data); var doc = {doc: bin}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); test.done(); }, "Should Correctly Serialize and Deserialize DBRef" : function(test) { var oid = new ObjectID(); var doc = {dbref: new DBRef('namespace', oid, null)}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.equal("namespace", doc2.dbref.namespace); test.deepEqual(doc2.dbref.oid.toHexString(), oid.toHexString()); test.done(); }, 'Should Correctly Serialize and Deserialize partial DBRef' : function(test) { var id = new ObjectID(); var doc = {'name':'something', 'user':{'$ref':'username', '$id': id}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.equal('something', doc2.name); test.equal('username', doc2.user.namespace); test.equal(id.toString(), doc2.user.oid.toString()); test.done(); }, 'Should Correctly Serialize and Deserialize simple Int' : function(test) { var doc = {doc:2147483648}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc, doc2.doc) test.done(); }, 'Should Correctly Serialize and Deserialize Long Integer' : function(test) { var doc = {doc: Long.fromNumber(9223372036854775807)}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc, deserialized_data.doc); doc = {doc: Long.fromNumber(-9223372036854775)}; serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc, deserialized_data.doc); doc = {doc: Long.fromNumber(-9223372036854775809)}; serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc, deserialized_data.doc); test.done(); }, 'Should Deserialize Large Integers as Number not Long' : function(test) { function roundTrip(val) { var doc = {doc: val}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc, deserialized_data.doc); }; roundTrip(Math.pow(2,52)); roundTrip(Math.pow(2,53) - 1); roundTrip(Math.pow(2,53)); roundTrip(-Math.pow(2,52)); roundTrip(-Math.pow(2,53) + 1); roundTrip(-Math.pow(2,53)); roundTrip(Math.pow(2,65)); // Too big for Long. roundTrip(-Math.pow(2,65)); roundTrip(9223372036854775807); roundTrip(1234567890123456800); // Bigger than 2^53, stays a double. roundTrip(-1234567890123456800); test.done(); }, 'Should Correctly Serialize and Deserialize Long Integer and Timestamp as different types' : function(test) { var long = Long.fromNumber(9223372036854775807); var timestamp = Timestamp.fromNumber(9223372036854775807); test.ok(long instanceof Long); test.ok(!(long instanceof Timestamp)); test.ok(timestamp instanceof Timestamp); test.ok(!(timestamp instanceof Long)); var test_int = {doc: long, doc2: timestamp}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(test_int.doc, deserialized_data.doc); test.done(); }, 'Should Always put the id as the first item in a hash' : function(test) { var hash = {doc: {not_id:1, '_id':2}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(hash, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(hash)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(hash, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); var keys = []; for(var name in deserialized_data.doc) { keys.push(name); } test.deepEqual(['not_id', '_id'], keys); test.done(); }, 'Should Correctly Serialize and Deserialize a User defined Binary object' : function(test) { var bin = new Binary(); bin.sub_type = BSON.BSON_BINARY_SUBTYPE_USER_DEFINED; var string = 'binstring'; for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)); } var doc = {doc: bin}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(deserialized_data.doc.sub_type, BSON.BSON_BINARY_SUBTYPE_USER_DEFINED); test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); test.done(); }, 'Should Correclty Serialize and Deserialize a Code object' : function(test) { var doc = {'doc': {'doc2': new Code('this.a > i', {i:1})}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.doc.doc2.code, deserialized_data.doc.doc2.code); test.deepEqual(doc.doc.doc2.scope.i, deserialized_data.doc.doc2.scope.i); test.done(); }, 'Should Correctly serialize and deserialize and embedded array' : function(test) { var doc = {'a':0, 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] }; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.a, deserialized_data.a); test.deepEqual(doc.b, deserialized_data.b); test.done(); }, 'Should Correctly Serialize and Deserialize UTF8' : function(test) { // Serialize utf8 var doc = { "name" : "本荘由利地域に洪水警報", "name1" : "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "name2" : "abcdedede"}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, deserialized_data); test.done(); }, 'Should Correctly Serialize and Deserialize query object' : function(test) { var doc = { count: 'remove_with_no_callback_bug_test', query: {}, fields: null}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, deserialized_data); test.done(); }, 'Should Correctly Serialize and Deserialize empty query object' : function(test) { var doc = {}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, deserialized_data); test.done(); }, 'Should Correctly Serialize and Deserialize array based doc' : function(test) { var doc = { b: [ 1, 2, 3 ], _id: new ObjectID() }; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.b, deserialized_data.b) test.deepEqual(doc, deserialized_data); test.done(); }, 'Should Correctly Serialize and Deserialize Symbol' : function(test) { if(Symbol != null) { var doc = { b: [ new Symbol('test') ]}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc.b, deserialized_data.b) test.deepEqual(doc, deserialized_data); test.ok(deserialized_data.b[0] instanceof Symbol); } test.done(); }, 'Should handle Deeply nested document' : function(test) { var doc = {a:{b:{c:{d:2}}}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, deserialized_data); test.done(); }, 'Should handle complicated all typed object' : function(test) { // First doc var date = new Date(); var oid = new ObjectID(); var string = 'binstring' var bin = new Binary() for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)) } var doc = { 'string': 'hello', 'array': [1,2,3], 'hash': {'a':1, 'b':2}, 'date': date, 'oid': oid, 'binary': bin, 'int': 42, 'float': 33.3333, 'regexp': /regexp/, 'boolean': true, 'long': date.getTime(), 'where': new Code('this.a > i', {i:1}), 'dbref': new DBRef('namespace', oid, 'integration_tests_') } // Second doc var oid = new ObjectID.createFromHexString(oid.toHexString()); var string = 'binstring' var bin = new Binary() for(var index = 0; index < string.length; index++) { bin.put(string.charAt(index)) } var doc2 = { 'string': 'hello', 'array': [1,2,3], 'hash': {'a':1, 'b':2}, 'date': date, 'oid': oid, 'binary': bin, 'int': 42, 'float': 33.3333, 'regexp': /regexp/, 'boolean': true, 'long': date.getTime(), 'where': new Code('this.a > i', {i:1}), 'dbref': new DBRef('namespace', oid, 'integration_tests_') } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); for(var i = 0; i < serialized_data2.length; i++) { require('assert').equal(serialized_data2[i], serialized_data[i]) } test.done(); }, 'Should Correctly Serialize Complex Nested Object' : function(test) { var doc = { email: 'email@email.com', encrypted_password: 'password', friends: [ '4db96b973d01205364000006', '4dc77b24c5ba38be14000002' ], location: [ 72.4930088, 23.0431957 ], name: 'Amit Kumar', password_salt: 'salty', profile_fields: [], username: 'amit', _id: new ObjectID() } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = doc; doc2._id = ObjectID.createFromHexString(doc2._id.toHexString()); var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); for(var i = 0; i < serialized_data2.length; i++) { require('assert').equal(serialized_data2[i], serialized_data[i]) } test.done(); }, 'Should correctly massive doc' : function(test) { var oid1 = new ObjectID(); var oid2 = new ObjectID(); // JS doc var doc = { dbref2: new DBRef('namespace', oid1, 'integration_tests_'), _id: oid2 }; var doc2 = { dbref2: new DBRef('namespace', ObjectID.createFromHexString(oid1.toHexString()), 'integration_tests_'), _id: new ObjectID.createFromHexString(oid2.toHexString()) }; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); test.done(); }, 'Should Correctly Serialize/Deserialize regexp object' : function(test) { var doc = {'b':/foobaré/}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); for(var i = 0; i < serialized_data2.length; i++) { require('assert').equal(serialized_data2[i], serialized_data[i]) } test.done(); }, 'Should Correctly Serialize/Deserialize complicated object' : function(test) { var doc = {a:{b:{c:[new ObjectID(), new ObjectID()]}}, d:{f:1332.3323}}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, doc2) test.done(); }, 'Should Correctly Serialize/Deserialize nested object' : function(test) { var doc = { "_id" : { "date" : new Date(), "gid" : "6f35f74d2bea814e21000000" }, "value" : { "b" : { "countries" : { "--" : 386 }, "total" : 1599 }, "bc" : { "countries" : { "--" : 3 }, "total" : 10 }, "gp" : { "countries" : { "--" : 2 }, "total" : 13 }, "mgc" : { "countries" : { "--" : 2 }, "total" : 14 } } } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, doc2) test.done(); }, 'Should Correctly Serialize/Deserialize nested object with even more nesting' : function(test) { var doc = { "_id" : { "date" : {a:1, b:2, c:new Date()}, "gid" : "6f35f74d2bea814e21000000" }, "value" : { "b" : { "countries" : { "--" : 386 }, "total" : 1599 }, "bc" : { "countries" : { "--" : 3 }, "total" : 10 }, "gp" : { "countries" : { "--" : 2 }, "total" : 13 }, "mgc" : { "countries" : { "--" : 2 }, "total" : 14 } } } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, doc2) test.done(); }, 'Should Correctly Serialize empty name object': function(test) { var doc = {'':'test', 'bbbb':1}; var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.equal(doc2[''], 'test'); test.equal(doc2['bbbb'], 1); test.done(); }, 'Should Correctly handle Forced Doubles to ensure we allocate enough space for cap collections' : function(test) { if(Double != null) { var doubleValue = new Double(100); var doc = {value:doubleValue}; // Serialize var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual({value:100}, doc2); } test.done(); }, 'Should Correctly deserialize a message' : function(test) { var data = "24000000be00de4428000000010000000800000000000000000000000000000000000000"; var parent = {bson_deserializer:{"Long":Long, "BSON":BSONSE.BSON}} var binaryData = new Buffer(hexStringToBinary(data)); var doc2 = new MongoReply(parent, binaryData); test.deepEqual([], doc2.documents); test.done(); }, 'Should deserialize correctly' : function(test) { var doc = { "_id" : new ObjectID("4e886e687ff7ef5e00000162"), "str" : "foreign", "type" : 2, "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), "links" : [ "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" ] } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, doc2) test.done(); }, 'Should correctly serialize and deserialize MinKey and MaxKey values' : function(test) { var doc = { _id : new ObjectID("4e886e687ff7ef5e00000162"), minKey : new MinKey(), maxKey : new MaxKey() } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.deepEqual(doc, doc2) test.ok(doc2.minKey instanceof MinKey); test.ok(doc2.maxKey instanceof MaxKey); test.done(); }, 'Should correctly serialize Double value' : function(test) { var doc = { value : new Double(34343.2222) } var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); assertBuffersEqual(test, serialized_data, serialized_data2, 0); var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); test.ok(doc.value.valueOf(), doc2.value); test.ok(doc.value.value, doc2.value); test.done(); }, 'ObjectID should correctly create objects' : function(test) { try { var object1 = ObjectID.createFromHexString('000000000000000000000001') var object2 = ObjectID.createFromHexString('00000000000000000000001') test.ok(false); } catch(err) { test.ok(err != null); } test.done(); }, 'ObjectID should correctly retrieve timestamp' : function(test) { var testDate = new Date(); var object1 = new ObjectID(); test.equal(Math.floor(testDate.getTime()/1000), Math.floor(object1.getTimestamp().getTime()/1000)); test.done(); }, // 'Should Correctly Function' : function(test) { // var doc = {b:1, func:function() { // this.b = 2; // }}; // // var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); // // debug("----------------------------------------------------------------------") // debug(inspect(serialized_data)) // // // var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); // // new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); // // assertBuffersEqual(test, serialized_data, serialized_data2, 0); // var COUNT = 100000; // // // var b = null; // // eval("b = function(x) { return x+x; }"); // // var b = new Function("x", "return x+x;"); // // console.log(COUNT + "x (objectBSON = BSON.serialize(object))") // start = new Date // // for (i=COUNT; --i>=0; ) { // var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); // } // // end = new Date // console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") // // // debug(inspect(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).functionCache)) // // // // var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); // // // test.deepEqual(doc, doc2) // // // // // debug(inspect(doc2)) // // doc2.func() // // debug(inspect(doc2)) // // // // var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); // // var doc3 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); // // // // debug("-----------------------------------------------") // // debug(inspect(doc3)) // // // var key = "0" // // for(var i = 1; i < 10000; i++) { // // key = key + " " + i // // } // // test.done(); // // // // var car = { // // model : "Volvo", // // country : "Sweden", // // // // isSwedish : function() { // // return this.country == "Sweden"; // // } // // } // // }, noGlobalsLeaked : function(test) { var leaks = gleak.detectNew(); test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); test.done(); } }); // Assign out tests module.exports = tests;
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentUnarchive = (props) => ( <SvgIcon {...props}> <path d="M20.55 5.22l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.15.55L3.46 5.22C3.17 5.57 3 6.01 3 6.5V19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.49-.17-.93-.45-1.28zM12 9.5l5.5 5.5H14v2h-4v-2H6.5L12 9.5zM5.12 5l.82-1h12l.93 1H5.12z"/> </SvgIcon> ); ContentUnarchive = pure(ContentUnarchive); ContentUnarchive.displayName = 'ContentUnarchive'; export default ContentUnarchive;
var gulp = require('gulp'); // TODO: clean-generated was breaking TeamCity. You need to make sure deployment/PostDeploy.ps1 and *.nuspec are not removed during the clean -AP gulp.task('build', function (cb) { require('run-sequence')( ['$clean-generated'], ['$sass', '$ng-templates', '$ng-config'], '$usemin', '$clean-temp', cb ); }); gulp.task('deploy', ['build']);// , 'test']); // TODO: Include tests. Removed to get building in TeamCity gulp.task('build-and-test', function () { require('run-sequence')('test', 'build'); });
/*! * jQuery JavaScript Library v3.4.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2019-05-01T21:04Z */ ( function( global, factory ) { "use strict"; 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 have a `window` with a `document` // (such as Node.js), expose a 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 ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var document = window.document; var getProto = Object.getPrototypeOf; 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 fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; var isFunction = function isFunction( obj ) { // Support: Chrome <=57, Firefox <=52 // In some browsers, typeof returns "function" for HTML <object> elements // (i.e., `typeof document.createElement( "object" ) === "function"`). // We don't want to classify *any* DOM node as a function. return typeof obj === "function" && typeof obj.nodeType !== "number"; }; var isWindow = function isWindow( obj ) { return obj != null && obj === obj.window; }; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval( code, node, doc ) { doc = doc || document; var i, val, script = doc.createElement( "script" ); script.text = code; if ( node ) { for ( i in preservedScriptAttributes ) { // Support: Firefox 64+, Edge 18+ // Some browsers don't support the "nonce" property on scripts. // On the other hand, just using `getAttribute` is not enough as // the `nonce` attribute is reset to an empty string whenever it // becomes browsing-context connected. // See https://github.com/whatwg/html/issues/2369 // See https://html.spec.whatwg.org/#nonce-attributes // The `node.getAttribute` check was added for the sake of // `jQuery.globalEval` so that it can fake a nonce-containing node // via an object. val = node[ i ] || node.getAttribute && node.getAttribute( i ); if ( val ) { script.setAttribute( i, val ); } } } doc.head.appendChild( script ).parentNode.removeChild( script ); } function toType( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.4.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-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.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // 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 all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : 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; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, 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(); }, // 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" && !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 ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // 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() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a global context globalEval: function( code, options ) { DOMEval( code, { nonce: options && options.nonce } ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android <=4.0 only 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 ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit 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 length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; 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, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.4 * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: 2019-04-08 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[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 // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "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" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // 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<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // 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 m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) && // Support: IE 8 only // Exclude object elements (nodeType !== 1 || context.nodeName.toLowerCase() !== "object") ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && rdescend.test( selector ) ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { 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 element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = 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 = arr.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 && a.sourceIndex - b.sourceIndex; // 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 :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * 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]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = (elem.ownerDocument || elem).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * 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 hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too 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 !== "undefined" && 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 https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // 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 // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // 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 ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + 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 ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.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 ? 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 = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( 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 document; }; 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 ); } if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !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) { nonnativeSelectorCache( expr, true ); } } 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 ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; 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 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; 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 while ( (node = elem[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 (jQuery #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[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[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // 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 !== "undefined" && 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.replace( rwhitespace, " " ) + " " ).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, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; 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 // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && 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 ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // 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 ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ 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( 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 ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || 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": createDisabledPseudo( false ), "disabled": createDisabledPseudo( 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 negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { 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; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // 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 > length ? 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(); tokenize = Sizzle.tokenize = function( 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, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "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 ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator 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 ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } return false; }; } 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 multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } 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( 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( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; 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 ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // 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 ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. 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, match /* 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 ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && 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; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } 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 ) && testContext( 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 if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // 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( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( el ) { el.innerHTML = "<a href='#'></a>"; return el.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( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.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( el ) { return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var 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; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, 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; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : 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 <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // 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; // Option to run 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 ( 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 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).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[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } 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.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 = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.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.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set 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.uniqueSort( 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 dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( typeof elem.contentDocument !== "undefined" ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return 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.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], 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" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes 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.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } 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; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, isFunction( onRejected ) ? onRejected : Thrower ) ); } ).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 = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // rejected_handlers.disable // fulfilled_handlers.disable tuples[ 3 - i ][ 3 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock, // progress_handlers.lock tuples[ 0 ][ 3 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith 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( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); 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, // 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 ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !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 ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; // Matches dashed string for camelizing var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g; // Used by camelCase as callback to replace() function fcamelCase( all, letter ) { return letter.toUpperCase(); } // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 15 // Microsoft forgot to hump their assets prefix (#9572) function camelCase( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { // 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 ) ) { return this.get( owner, 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, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( camelCase ); } else { key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = 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 getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } 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, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.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 = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // 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 // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.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 public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.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 = dataPriv.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 rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var documentElement = document.documentElement; var isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ); }, composed = { composed: true }; // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only // Check attachment across shadow DOM boundaries when possible (gh-3504) // Support: iOS 10.0-10.2 only // Early iOS 10 versions support `attachShadow` but not `getRootNode`, // leading to errors. We need to check for `getRootNode`. if ( documentElement.getRootNode ) { isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ) || elem.getRootNode( composed ) === elem.ownerDocument; }; } var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. isAttached( elem ) && jQuery.css( elem, "display" ) === "none"; }; var 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; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = elem.nodeType && ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Support: Firefox <=54 // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) initial = initial / 2; // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; while ( maxIterations-- ) { // Evaluate and update our best guess (doubling guesses that zero out). // Finish if the scale equals or crosses 1 (making the old*new product non-positive). jQuery.style( elem, prop, initialInUnit + unit ); if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { maxIterations = 0; } initialInUnit = initialInUnit / scale; } initialInUnit = initialInUnit * 2; jQuery.style( elem, prop, initialInUnit + unit ); // Make sure we update the tween properties later on valueParts = valueParts || []; } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { 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 ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "<select multiple='multiple'>", "</select>" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. 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 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, attached, 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 ( toType( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit 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 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } attached = isAttached( elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( attached ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 - 11+ // focus() and blur() are asynchronous, except when they are no-op. // So expect focus to be synchronous when the element is already active, // and blur to be synchronous when the element is not already active. // (focus and blur are always synchronous in other supported browsers, // this just defines when we can count on it). function expectSync( elem, type ) { return ( elem === safeActiveElement() ) === ( type === "focus" ); } // Support: IE <=9 only // Accessing document.activeElement can throw unexpectedly // https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, 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 ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } 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 elem; } 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 elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * 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 = dataPriv.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; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, 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 !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; 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 ); } } } 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 = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; 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 data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.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; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } 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() ) { // If the event is namespaced, then each handler is only invoked if it is // specially universal or its namespaces are a superset of the event's. if ( !event.rnamespace || handleObj.namespace === false || event.rnamespace.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, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG <use> instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // Utilize native event to ensure correct state for checkable inputs setup: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }, trigger: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Force setup before triggering a click if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { leverageNative( el, "click" ); } // Return non-false to allow normal event-path propagation return true; }, // For cross-browser consistency, suppress native .click() on links // Also prevent it if we're currently inside a leveraged native-event stack _default: function( event ) { var target = event.target; return rcheckableType.test( target.type ) && target.click && nodeName( target, "input" ) && dataPriv.get( target, "click" ) || nodeName( 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; } } } } }; // Ensure the presence of an event listener that handles manually-triggered // synthetic events by interrupting progress until reinvoked in response to // *native* events that it fires directly, ensuring that state changes have // already occurred before other listeners are invoked. function leverageNative( el, type, expectSync ) { // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add if ( !expectSync ) { if ( dataPriv.get( el, type ) === undefined ) { jQuery.event.add( el, type, returnTrue ); } return; } // Register the controller as a special universal handler for all event namespaces dataPriv.set( el, type, false ); jQuery.event.add( el, type, { namespace: false, handler: function( event ) { var notAsync, result, saved = dataPriv.get( this, type ); if ( ( event.isTrigger & 1 ) && this[ type ] ) { // Interrupt processing of the outer synthetic .trigger()ed event // Saved data should be false in such cases, but might be a leftover capture object // from an async native handler (gh-4350) if ( !saved.length ) { // Store arguments for use when handling the inner native event // There will always be at least one argument (an event object), so this array // will not be confused with a leftover capture object. saved = slice.call( arguments ); dataPriv.set( this, type, saved ); // Trigger the native event and capture its result // Support: IE <=9 - 11+ // focus() and blur() are asynchronous notAsync = expectSync( this, type ); this[ type ](); result = dataPriv.get( this, type ); if ( saved !== result || notAsync ) { dataPriv.set( this, type, false ); } else { result = {}; } if ( saved !== result ) { // Cancel the outer synthetic event event.stopImmediatePropagation(); event.preventDefault(); return result.value; } // If this is an inner synthetic event for an event with a bubbling surrogate // (focus or blur), assume that the surrogate already propagated from triggering the // native event and prevent that from happening again here. // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the // bubbling surrogate propagates *after* the non-bubbling base), but that seems // less bad than duplication. } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { event.stopPropagation(); } // If this is a native event triggered above, everything is now in order // Fire an inner synthetic event with the original arguments } else if ( saved.length ) { // ...and capture the result dataPriv.set( this, type, { value: jQuery.event.trigger( // Support: IE <=9 - 11+ // Extend with the prototype to reset the above stopImmediatePropagation() jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), saved.slice( 1 ), this ) } ); // Abort handling of the native event event.stopImmediatePropagation(); } } } ); } jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // 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 || Date.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, code: true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { jQuery.event.special[ type ] = { // Utilize native event if possible so blur/focus sequence is correct setup: function() { // Claim the first handler // dataPriv.set( this, "focus", ... ) // dataPriv.set( this, "blur", ... ) leverageNative( this, type, expectSync ); // Return false to allow normal processing in the caller return false; }, trigger: function() { // Force setup before trigger leverageNative( this, type ); // Return non-false to allow normal event-path propagation return true; }, delegateType: delegateType }; } ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). 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 mouseenter/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; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, 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 ); } ); } } ); var /* eslint-disable max-len */ // See https://github.com/eslint/eslint/issues/3229 rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, /* eslint-enable */ // Support: IE <=10 - 11, Edge 12 - 13 only // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return 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 ) { if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } return elem; } 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 ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.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 ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests 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; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { 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: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ 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 || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl && !node.noModule ) { jQuery._evalUrl( node.src, { nonce: node.nonce || node.getAttribute( "nonce" ) } ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = isAttached( elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://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; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { 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 ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, 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 domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, 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 domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, 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 = jQuery.htmlPrefilter( value ); 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 ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); 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: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0"; div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%"; documentElement.appendChild( container ).appendChild( div ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 // Some styles come back with percentage values, even though they shouldn't div.style.right = "60%"; pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; // Support: IE 9 - 11 only // Detect misreporting of content dimensions for box-sizing:border-box elements boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; // Support: IE 9 only // Detect overflow:scroll screwiness (gh-3699) // Support: Chrome <=64 // Don't get tricked when zoom affects offsetWidth (gh-4029) div.style.position = "absolute"; scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } function roundPixelMeasures( measure ) { return Math.round( parseFloat( measure ) ); } var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; jQuery.extend( support, { boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelBoxStyles: function() { computeStyleTests(); return pixelBoxStylesVal; }, pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; }, scrollboxSize: function() { computeStyleTests(); return scrollboxSizeVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.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 <=9 - 11 only // 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. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style, assetsProps = {}; // Return a assets-prefixed property or undefined function assetsPropName( name ) { // Check for assets prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a potentially-mapped jQuery.cssProps or assets prefixed property function finalPropName( name ) { var final = jQuery.cssProps[ name ] || assetsProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return assetsProps[ name ] = assetsPropName( name ) || name; } 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]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { return 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin if ( box === "margin" ) { delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" if ( !isBorderBox ) { // Add padding delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // For "border" or "margin", add border if ( box !== "padding" ) { delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); // But still keep track of it otherwise } else { extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } // If we get here with a border-box (content + padding + border), we're seeking "content" or // "padding" or "margin" } else { // For "content", subtract padding if ( box === "content" ) { delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // For "content" or "padding", subtract border if ( box !== "margin" ) { delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } // Account for positive content-box scroll gutter when requested by providing computedVal if ( !isBorderBox && computedVal >= 0 ) { // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border // Assuming integer scroll gutter, subtract the rest and round down delta += Math.max( 0, Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - computedVal - delta - extra - 0.5 // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter // Use an explicit zero to avoid NaN (gh-3964) ) ) || 0; } return delta; } function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style var styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). // Fake content-box until we know it's needed to know the true value. boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS( elem, dimension, styles ), offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); // Support: Firefox <=54 // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { if ( !extra ) { return val; } val = "auto"; } // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) // Support: Android <=4.1 - 4.3 only // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) // Support: IE 9-11 only // Also use offsetWidth/offsetHeight for when box sizing is unreliable // We use getClientRects() to check for hidden/disconnected. // In those cases, the computed value can be trusted to be border-box if ( ( !support.boxSizingReliable() && isBorderBox || val === "auto" || !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && elem.getClientRects().length ) { isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Where available, offsetWidth/offsetHeight approximate border box dimensions. // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the // retrieved value as a content box dimension. valueIsBorderBox = offsetProp in elem; if ( valueIsBorderBox ) { val = elem[ offsetProp ]; } } // Normalize "" and auto val = parseFloat( val ) || 0; // Adjust for the element's box model return ( val + boxModelAdjustment( elem, dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589) val ) ) + "px"; } 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: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "gridArea": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnStart": true, "gridRow": true, "gridRowEnd": true, "gridRowStart": 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: {}, // 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 = camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append // "px" to a few hardcoded values. if ( type === "number" && !isCustomProp ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values 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 ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { 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 = camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name 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 ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, dimension ) { jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, dimension, extra ); } ) : getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, styles = getStyles( elem ), // Only read styles.position if the test has a chance to fail // to avoid forcing a reflow. scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; // Account for unreliable border-box dimensions by comparing offset* to computed and // faking a content-box to get border and padding (gh-3699) if ( isBorderBox && scrollboxSizeBuggy ) { subtract -= Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - parseFloat( styles[ dimension ] ) - boxModelAdjustment( elem, dimension, "border", false, styles ) - 0.5 ); } // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ dimension ] = value; value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // 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 ( prefix !== "margin" ) { 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 ( Array.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 ); } } ); // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/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 = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var 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 ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // 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, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/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( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } function classesToArray( value ) { if ( Array.isArray( value ) ) { return value; } if ( typeof value === "string" ) { return value.match( rnothtmlwhite ) || []; } return []; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isValidValue = type === "string" || Array.isArray( value ); if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = classesToArray( value ); 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 ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", 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. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, valueIsFunction, 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; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } valueIsFunction = isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( valueIsFunction ) { 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 ( Array.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: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-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 !option.disabled && ( !option.parentNode.disabled || !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 ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // 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 ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion support.focusin = "onfocusin" in window; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function( e ) { e.stopPropagation(); }; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = lastElement = 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( "." ) > -1 ) { // 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.rnamespace = 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 && !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() ) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && 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 ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && isFunction( elem[ type ] ) && !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; if ( event.isPropagationStopped() ) { lastElement.addEventListener( type, stopPropagationCallback ); } elem[ type ](); if ( event.isPropagationStopped() ) { lastElement.removeEventListener( type, stopPropagationCallback ); } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { 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 ); } } } ); // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { 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 ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var 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 ( Array.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" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && toType( 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, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; if ( a == null ) { return ""; } // If an array was passed in, assume that it is an array of form elements. if ( Array.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( "&" ); }; 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(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( isFunction( html ) ) { html = html.call( 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 ( 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 htmlIsFunction = isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; // Support: Safari 8 only // In Safari 8 documents created via document.implementation.createHTMLDocument // collapse sibling forms: the second one becomes a child of the first one. // Because of that, this security measure has to be disabled in Safari 8. // https://bugs.webkit.org/show_bug.cgi?id=137337 support.createHTMLDocument = ( function() { var body = document.implementation.createHTMLDocument( "" ).body; body.innerHTML = "<form></form><form></form>"; return body.childNodes.length === 2; } )(); // Argument "data" should be 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 ( typeof data !== "string" ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var base, parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using document.implementation if ( support.createHTMLDocument ) { context = document.implementation.createHTMLDocument( "" ); // Set the base href for the created document // so any parsed elements with URLs // are based on the document's URL (gh-2965) base = context.createElement( "base" ); base.href = document.location.href; context.head.appendChild( base ); } else { context = document; } } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; 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 ( isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, 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() relates an element's border box to the document origin offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var rect, win, elem = this[ 0 ]; if ( !elem ) { return; } // Return zeros for disconnected and hidden (display: none) elements (gh-2310) // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } // Get document-relative position by adding viewport scroll to viewport-relative gBCR rect = elem.getBoundingClientRect(); win = elem.ownerDocument.defaultView; return { top: rect.top + win.pageYOffset, left: rect.left + win.pageXOffset }; }, // position() relates an element's margin box to its offset parent's padding box // This corresponds to the behavior of CSS absolute positioning position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, doc, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // position:fixed elements are offset from the viewport, which itself always has zero offset if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume position:fixed implies availability of getBoundingClientRect offset = elem.getBoundingClientRect(); } else { offset = this.offset(); // Account for the *real* offset parent, which can be the document or its root element // when a statically positioned element is identified doc = elem.ownerDocument; offsetParent = elem.offsetParent || doc.documentElement; while ( offsetParent && ( offsetParent === doc.body || offsetParent === doc.documentElement ) && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.parentNode; } if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) { // Incorporate borders into its offset, since they are outside its content origin parentOffset = jQuery( offsetParent ).offset(); parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent, "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 ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // 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 ) { // Coalesce documents and windows var win; if ( isWindow( elem ) ) { win = elem; } else if ( elem.nodeType === 9 ) { win = elem.defaultView; } if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari <=7 - 9.1, Chrome <=37 - 49 // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, 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 ( isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : 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 ); }; } ); } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup 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 ); } } ); jQuery.fn.extend( { 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 ); } } ); // Bind a function to a context, optionally partially applying any // arguments. // jQuery.proxy is deprecated to promote standards (specifically Function#bind) // However, it is not slated for removal any time soon jQuery.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 ( !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; }; jQuery.holdReady = function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }; jQuery.isArray = Array.isArray; jQuery.parseJSON = JSON.parse; jQuery.nodeName = nodeName; jQuery.isFunction = isFunction; jQuery.isWindow = isWindow; jQuery.camelCase = camelCase; jQuery.type = toType; jQuery.now = Date.now; jQuery.isNumeric = function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }; // 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 ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; } );
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirections = (props) => ( <SvgIcon {...props}> <path d="M21.71 11.29l-9-9c-.39-.39-1.02-.39-1.41 0l-9 9c-.39.39-.39 1.02 0 1.41l9 9c.39.39 1.02.39 1.41 0l9-9c.39-.38.39-1.01 0-1.41zM14 14.5V12h-4v3H8v-4c0-.55.45-1 1-1h5V7.5l3.5 3.5-3.5 3.5z"/> </SvgIcon> ); MapsDirections = pure(MapsDirections); MapsDirections.displayName = 'MapsDirections'; export default MapsDirections;
var appendView = function(view) { Ember.run(function() { view.appendTo('#qunit-fixture'); }); }; var set = function(object, key, value) { Ember.run(function() { Ember.set(object, key, value); }); }; var compile = function(template) { return Ember.Handlebars.compile(template); }; var buildContainer = function(namespace) { var container = new Ember.Container(); container.set = Ember.set; container.resolver = resolverFor(namespace); container.optionsForType('view', { singleton: false }); container.optionsForType('template', { instantiate: false }); container.register('application:main', namespace, { instantiate: false }); container.injection('router:main', 'namespace', 'application:main'); container.register('location:hash', Ember.HashLocation); container.register('controller:basic', Ember.Controller, { instantiate: false }); container.register('controller:object', Ember.ObjectController, { instantiate: false }); container.register('controller:array', Ember.ArrayController, { instantiate: false }); container.typeInjection('route', 'router', 'router:main'); return container; }; function resolverFor(namespace) { return function(fullName) { var nameParts = fullName.split(":"), type = nameParts[0], name = nameParts[1]; if (type === 'template') { var templateName = Ember.String.decamelize(name); if (Ember.TEMPLATES[templateName]) { return Ember.TEMPLATES[templateName]; } } var className = Ember.String.classify(name) + Ember.String.classify(type); var factory = Ember.get(namespace, className); if (factory) { return factory; } }; } var view, container; module("Handlebars {{render}} helper", { setup: function() { var namespace = Ember.Namespace.create(); container = buildContainer(namespace); container.register('view:default', Ember.View.extend()); container.register('router:main', Ember.Router.extend()); }, teardown: function() { Ember.run(function () { if (container) { container.destroy(); } if (view) { view.destroy(); } }); Ember.TEMPLATES = {}; } }); test("{{render}} helper should render given template", function() { var template = "<h1>HI</h1>{{render 'home'}}"; var controller = Ember.Controller.extend({container: container}); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['home'] = compile("<p>BYE</p>"); appendView(view); equal(view.$().text(), 'HIBYE'); ok(container.lookup('router:main')._lookupActiveView('home'), 'should register home as active view'); }); test("{{render}} helper should have assertion if neither template nor view exists", function() { var template = "<h1>HI</h1>{{render 'oops'}}"; var controller = Ember.Controller.extend({container: container}); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); expectAssertion(function() { appendView(view); }, 'You used `{{render \'oops\'}}`, but \'oops\' can not be found as either a template or a view.'); }); test("{{render}} helper should not have assertion if template is supplied in block-form", function() { var template = "<h1>HI</h1>{{#render 'good'}} {{name}}{{/render}}"; var controller = Ember.Controller.extend({container: container}); container.register('controller:good', Ember.Controller.extend({ name: 'Rob'})); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); appendView(view); equal(view.$().text(), 'HI Rob'); }); test("{{render}} helper should not have assertion if view exists without a template", function() { var template = "<h1>HI</h1>{{render 'oops'}}"; var controller = Ember.Controller.extend({container: container}); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); container.register('view:oops', Ember.View.extend()); appendView(view); equal(view.$().text(), 'HI'); }); test("{{render}} helper should render given template with a supplied model", function() { var template = "<h1>HI</h1>{{render 'post' post}}"; var post = { title: "Rails is omakase" }; var Controller = Ember.Controller.extend({ container: container, post: post }); var controller = Controller.create({ }); view = Ember.View.create({ controller: controller, template: Ember.Handlebars.compile(template) }); var PostController = Ember.ObjectController.extend(); container.register('controller:post', PostController); Ember.TEMPLATES['post'] = compile("<p>{{title}}</p>"); appendView(view); var postController = view.get('_childViews')[0].get('controller'); equal(view.$().text(), 'HIRails is omakase'); equal(postController.get('model'), post); set(controller, 'post', { title: "Rails is unagi" }); equal(view.$().text(), 'HIRails is unagi'); if (Ember.create.isSimulated) { equal(postController.get('model').title, "Rails is unagi"); } else { deepEqual(postController.get('model'), { title: "Rails is unagi" }); } }); test("{{render}} helper with a supplied model should not fire observers on the controller", function () { var template = "<h1>HI</h1>{{render 'post' post}}"; var post = { title: "Rails is omakase" }; view = Ember.View.create({ controller: Ember.Controller.create({ container: container, post: post }), template: Ember.Handlebars.compile(template) }); var PostController = Ember.ObjectController.extend({ contentDidChange: Ember.observer('content', function(){ contentDidChange++; }) }); container.register('controller:post', PostController); Ember.TEMPLATES['post'] = compile("<p>{{title}}</p>"); var contentDidChange = 0; appendView(view); equal(contentDidChange, 0, "content observer did not fire"); }); test("{{render}} helper should raise an error when a given controller name does not resolve to a controller", function() { var template = '<h1>HI</h1>{{render "home" controller="postss"}}'; var controller = Ember.Controller.extend({container: container}); container.register('controller:posts', Ember.ArrayController.extend()); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['home'] = compile("<p>BYE</p>"); expectAssertion(function() { appendView(view); }, 'The controller name you supplied \'postss\' did not resolve to a controller.'); }); test("{{render}} helper should render with given controller", function() { var template = '<h1>HI</h1>{{render "home" controller="posts"}}'; var controller = Ember.Controller.extend({container: container}); container.register('controller:posts', Ember.ArrayController.extend()); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['home'] = compile("<p>BYE</p>"); appendView(view); var renderedView = container.lookup('router:main')._lookupActiveView('home'); equal(container.lookup('controller:posts'), renderedView.get('controller'), 'rendered with correct controller'); }); test("{{render}} helper should render a template without a model only once", function() { var template = "<h1>HI</h1>{{render 'home'}}<hr/>{{render home}}"; var controller = Ember.Controller.extend({container: container}); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['home'] = compile("<p>BYE</p>"); expectAssertion(function() { appendView(view); }, /\{\{render\}\} helper once/i); }); test("{{render}} helper should render templates with models multiple times", function() { var template = "<h1>HI</h1> {{render 'post' post1}} {{render 'post' post2}}"; var post1 = { title: "Me first" }; var post2 = { title: "Then me" }; var Controller = Ember.Controller.extend({ container: container, post1: post1, post2: post2 }); var controller = Controller.create(); view = Ember.View.create({ controller: controller, template: Ember.Handlebars.compile(template) }); var PostController = Ember.ObjectController.extend(); container.register('controller:post', PostController, {singleton: false}); Ember.TEMPLATES['post'] = compile("<p>{{title}}</p>"); appendView(view); var postController1 = view.get('_childViews')[0].get('controller'); var postController2 = view.get('_childViews')[1].get('controller'); ok(view.$().text().match(/^HI ?Me first ?Then me$/)); equal(postController1.get('model'), post1); equal(postController2.get('model'), post2); set(controller, 'post1', { title: "I am new" }); ok(view.$().text().match(/^HI ?I am new ?Then me$/)); if (Ember.create.isSimulated) { equal(postController1.get('model').title, "I am new"); } else { deepEqual(postController1.get('model'), { title: "I am new" }); } }); test("{{render}} helper should not treat invocations with falsy contexts as context-less", function() { var template = "<h1>HI</h1> {{render 'post' zero}} {{render 'post' nonexistent}}"; view = Ember.View.create({ controller: Ember.Controller.createWithMixins({ container: container, zero: false }), template: Ember.Handlebars.compile(template) }); var PostController = Ember.ObjectController.extend(); container.register('controller:post', PostController, {singleton: false}); Ember.TEMPLATES['post'] = compile("<p>{{#unless content}}NOTHING{{/unless}}</p>"); appendView(view); var postController1 = view.get('_childViews')[0].get('controller'); var postController2 = view.get('_childViews')[1].get('controller'); ok(view.$().text().match(/^HI ?NOTHING ?NOTHING$/)); equal(postController1.get('model'), 0); equal(postController2.get('model'), undefined); }); test("{{render}} helper should render templates both with and without models", function() { var template = "<h1>HI</h1> {{render 'post'}} {{render 'post' post}}"; var post = { title: "Rails is omakase" }; var Controller = Ember.Controller.extend({ container: container, post: post }); var controller = Controller.create(); view = Ember.View.create({ controller: controller, template: Ember.Handlebars.compile(template) }); var PostController = Ember.ObjectController.extend(); container.register('controller:post', PostController, {singleton: false}); Ember.TEMPLATES['post'] = compile("<p>Title:{{title}}</p>"); appendView(view); var postController1 = view.get('_childViews')[0].get('controller'); var postController2 = view.get('_childViews')[1].get('controller'); ok(view.$().text().match(/^HI ?Title: ?Title:Rails is omakase$/)); equal(postController1.get('model'), null); equal(postController2.get('model'), post); set(controller, 'post', { title: "Rails is unagi" }); ok(view.$().text().match(/^HI ?Title: ?Title:Rails is unagi$/)); if (Ember.create.isSimulated) { equal(postController2.get('model').title, "Rails is unagi"); } else { deepEqual(postController2.get('model'), { title: "Rails is unagi" }); } }); test("{{render}} helper should link child controllers to the parent controller", function() { var parentTriggered = 0; var template = '<h1>HI</h1>{{render "posts"}}'; var controller = Ember.Controller.extend({ container: container, actions: { parentPlease: function() { parentTriggered++; } }, role: "Mom" }); container.register('controller:posts', Ember.ArrayController.extend()); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['posts'] = compile('<button id="parent-action" {{action "parentPlease"}}>Go to {{parentController.role}}</button>'); appendView(view); var button = Ember.$("#parent-action"), actionId = button.data('ember-action'), action = Ember.Handlebars.ActionHelper.registeredActions[actionId], handler = action.handler; equal(button.text(), "Go to Mom", "The parentController property is set on the child controller"); Ember.run(null, handler, new Ember.$.Event("click")); equal(parentTriggered, 1, "The event bubbled to the parent"); }); test("{{render}} helper should be able to render a template again when it was removed", function() { var template = "<h1>HI</h1>{{outlet}}"; var controller = Ember.Controller.extend({container: container}); view = Ember.View.create({ template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['home'] = compile("<p>BYE</p>"); appendView(view); Ember.run(function() { view.connectOutlet('main', Ember.View.create({ controller: controller.create(), template: compile("<p>1{{render 'home'}}</p>") })); }); equal(view.$().text(), 'HI1BYE'); Ember.run(function() { view.connectOutlet('main', Ember.View.create({ controller: controller.create(), template: compile("<p>2{{render 'home'}}</p>") })); }); equal(view.$().text(), 'HI2BYE'); }); test("{{render}} works with dot notation", function() { var template = '<h1>BLOG</h1>{{render "blog.post"}}'; var controller = Ember.Controller.extend({container: container}); container.register('controller:blog.post', Ember.ObjectController.extend()); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['blog.post'] = compile("<p>POST</p>"); appendView(view); var renderedView = container.lookup('router:main')._lookupActiveView('blog.post'); equal(renderedView.get('viewName'), 'blogPost', 'camelizes the view name'); equal(container.lookup('controller:blog.post'), renderedView.get('controller'), 'rendered with correct controller'); }); test("{{render}} works with slash notation", function() { var template = '<h1>BLOG</h1>{{render "blog/post"}}'; var controller = Ember.Controller.extend({container: container}); container.register('controller:blog.post', Ember.ObjectController.extend()); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['blog.post'] = compile("<p>POST</p>"); appendView(view); var renderedView = container.lookup('router:main')._lookupActiveView('blog.post'); equal(renderedView.get('viewName'), 'blogPost', 'camelizes the view name'); equal(container.lookup('controller:blog.post'), renderedView.get('controller'), 'rendered with correct controller'); }); test("Using quoteless templateName works properly (DEPRECATED)", function(){ var template = '<h1>HI</h1>{{render home}}'; var controller = Ember.Controller.extend({container: container}); view = Ember.View.create({ controller: controller.create(), template: Ember.Handlebars.compile(template) }); Ember.TEMPLATES['home'] = compile("<p>BYE</p>"); expectDeprecation("Using a quoteless parameter with {{render}} is deprecated. Please update to quoted usage '{{render \"home\"}}."); appendView(view); equal(view.$('p:contains(BYE)').length, 1, "template was rendered"); });
tinyMCE.addI18n('pl.pdw',{ desc : 'Show/hide toolbars' });
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _three = require('three'); var THREE = _interopRequireWildcard(_three); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _MaterialDescriptorBase = require('./MaterialDescriptorBase'); var _MaterialDescriptorBase2 = _interopRequireDefault(_MaterialDescriptorBase); var _UniformContainer = require('../../UniformContainer'); var _UniformContainer2 = _interopRequireDefault(_UniformContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ShaderMaterialDescriptor = function (_MaterialDescriptorBa) { _inherits(ShaderMaterialDescriptor, _MaterialDescriptorBa); function ShaderMaterialDescriptor(react3RendererInstance) { _classCallCheck(this, ShaderMaterialDescriptor); var _this = _possibleConstructorReturn(this, (ShaderMaterialDescriptor.__proto__ || Object.getPrototypeOf(ShaderMaterialDescriptor)).call(this, react3RendererInstance)); ['vertexShader', 'fragmentShader'].forEach(function (propName) { _this.hasProp(propName, { type: _propTypes2.default.string, update: _this.triggerRemount }); }); _this.hasProp('uniforms', { type: _propTypes2.default.any, simple: true, default: undefined }); _this.hasWireframe(); return _this; } _createClass(ShaderMaterialDescriptor, [{ key: 'getMaterialDescription', value: function getMaterialDescription(props) { var materialDescription = _get(ShaderMaterialDescriptor.prototype.__proto__ || Object.getPrototypeOf(ShaderMaterialDescriptor.prototype), 'getMaterialDescription', this).call(this, props); if (props.hasOwnProperty('uniforms')) { materialDescription.uniforms = props.uniforms; } if (props.hasOwnProperty('vertexShader')) { materialDescription.vertexShader = props.vertexShader; } if (props.hasOwnProperty('fragmentShader')) { materialDescription.fragmentShader = props.fragmentShader; } return materialDescription; } }, { key: 'construct', value: function construct(props) { var materialDescription = this.getMaterialDescription(props); return new THREE.ShaderMaterial(materialDescription); } }, { key: 'invalidChildInternal', value: function invalidChildInternal(child) { return !(child instanceof _UniformContainer2.default || _get(ShaderMaterialDescriptor.prototype.__proto__ || Object.getPrototypeOf(ShaderMaterialDescriptor.prototype), 'invalidChildInternal', this).call(this, child)); } }, { key: 'applyInitialProps', value: function applyInitialProps(threeObject, props) { _get(ShaderMaterialDescriptor.prototype.__proto__ || Object.getPrototypeOf(ShaderMaterialDescriptor.prototype), 'applyInitialProps', this).call(this, threeObject, props); if (!props.hasOwnProperty('uniforms')) { threeObject.uniforms = {}; } } }]); return ShaderMaterialDescriptor; }(_MaterialDescriptorBase2.default); module.exports = ShaderMaterialDescriptor;
/** * (c) jExcel v3.3.3 * * Author: Paul Hodel <paul.hodel@gmail.com> * Website: https://bossanova.uk/jexcel/ * Description: Create amazing web based spreadsheets. * * This software is distribute under MIT License */ 'use strict'; if (! jSuites && typeof(require) === 'function') { var jSuites = require('jsuites'); require('jsuites/dist/jsuites.css'); } var jexcel = (function(el, options) { // Create jexcel object var obj = {}; obj.options = {}; // Loading default configuration var defaults = { // External data url:null, // Data data:[[]], // Copy behavior copyCompatibility:false, // Rows and columns definitions rows:[], columns:[], // Deprected legacy options colHeaders:[], colWidths:[], colAlignments:[], nestedHeaders:null, // Column width that is used by default defaultColWidth:50, // Spare rows and columns minSpareRows:0, minSpareCols:0, // Minimal table dimensions minDimensions:[0,0], // Allow Export allowExport:true, // Allow column sorting columnSorting:true, // Allow column resizing columnDrag:false, // Allow column resizing columnResize:true, // Allow row resizing rowResize:false, // Allow row dragging rowDrag:true, // Allow table edition editable:true, // Allow new rows allowInsertRow:true, // Allow new rows allowManualInsertRow:true, // Allow new columns allowInsertColumn:true, // Allow new rows allowManualInsertColumn:true, // Allow row delete allowDeleteRow:true, // Allow column delete allowDeleteColumn:true, // Allow rename column allowRenameColumn:true, // Allow comments allowComments:false, // Global wrap wordWrap:false, // CSV source csv:null, // Filename csvFileName:'jexcel', // Consider first line as header csvHeaders:true, // Delimiters csvDelimiter:',', // Disable corner selection selectionCopy:true, // Merged cells mergeCells:[], // Create toolbar toolbar:null, // Allow search search:false, // Create pagination pagination:false, paginationOptions:null, // Full screen fullscreen:false, // Lazy loading lazyLoading:false, loadingSpin:false, // Table overflow tableOverflow:false, tableHeight:'300px', tableWidth:null, // Meta meta: null, // Style style:null, // Event handles onload:null, onchange:null, onbeforechange:null, onbeforeinsertrow: null, oninsertrow:null, onbeforeinsertcolumn: null, oninsertcolumn:null, onbeforedeleterow:null, ondeleterow:null, onbeforedeletecolumn:null, ondeletecolumn:null, onmoverow:null, onmovecolumn:null, onresizerow:null, onresizecolumn:null, onsort:null, onselection:null, onpaste:null, onmerge:null, onfocus:null, onblur:null, // Customize any cell behavior updateTable:null, // Texts text:{ noRecordsFound: 'No records found', showingPage: 'Showing page {0} of {1} entries', show: 'Show ', search: 'Search', entries: ' entries', insertANewColumnBefore: 'Insert a new column before', insertANewColumnAfter: 'Insert a new column after', deleteSelectedColumns: 'Delete selected columns', renameThisColumn: 'Rename this column', orderAscending: 'Order ascending', orderDescending: 'Order descending', insertANewRowBefore: 'Insert a new row before', insertANewRowAfter: 'Insert a new row after', deleteSelectedRows: 'Delete selected rows', editComments: 'Edit comments', addComments: 'Add comments', comments: 'Comments', clearComments: 'Clear comments', copy: 'Copy...', paste: 'Paste...', saveAs: 'Save as...', about: 'About', areYouSureToDeleteTheSelectedRows: 'Are you sure to delete the selected rows?', areYouSureToDeleteTheSelectedColumns: 'Are you sure to delete the selected columns?', thisActionWillDestroyAnyExistingMergedCellsAreYouSure: 'This action will destroy any existing merged cells. Are you sure?', thisActionWillClearYourSearchResultsAreYouSure: 'This action will clear your search results. Are you sure?', thereIsAConflictWithAnotherMergedCell: 'There is a conflict with another merged cell', invalidMergeProperties: 'Invalid merged properties', cellAlreadyMerged: 'Cell already merged', noCellsSelected: 'No cells selected', }, // About message about:"jExcel CE Spreadsheet\nVersion 3.3.3\nAuthor: Paul Hodel <paul.hodel@gmail.com>\nWebsite: https://jexcel.net/v3", }; // Loading initial configuration from user for (var property in defaults) { if (options && options.hasOwnProperty(property)) { obj.options[property] = (property == 'text') ? Object.assign(defaults[property], options[property]) : options[property]; } else { obj.options[property] = defaults[property]; } } // Global elements obj.el = el; obj.corner = null; obj.contextMenu = null; obj.textarea = null; obj.ads = null; obj.content = null; obj.table = null; obj.thead = null; obj.tbody = null; obj.rows = []; obj.results = null; obj.searchInput = null; obj.toolbar = null; obj.pagination = null; obj.pageNumber = null; obj.headerContainer = null; obj.colgroupContainer = null; // Containers obj.headers = []; obj.records = []; obj.history = []; obj.formula = []; obj.formulaStack = 0; obj.colgroup = []; obj.selection = []; obj.highlighted = []; obj.selectedCell = null; obj.selectedContainer = null; obj.style = []; obj.meta = []; obj.data = null; // Internal controllers obj.cursor = null; obj.historyIndex = -1; obj.ignoreEvents = false; obj.ignoreHistory = false; obj.edition = null; obj.hashString = null; obj.resizing = null; obj.dragging = null; // Lazy loading if (obj.options.lazyLoading == true && (obj.options.tableOverflow == false && obj.options.fullscreen == false)) { console.error('JEXCEL: The lazyloading only works when tableOverflow = yes or fullscreen = yes'); obj.options.lazyLoading = false; } /** * Prepare the jexcel table * * @Param config */ obj.prepareTable = function() { // Loading initial data from remote sources var results = []; // Number of columns var size = obj.options.columns.length; if (typeof obj.options.data[0] !== 'undefined' && obj.options.data[0].length > size) { size = obj.options.data[0].length; } // Minimal dimensions if (obj.options.minDimensions[0] > size) { size = obj.options.minDimensions[0]; } // Requests var requests = []; var requestsIndex = []; // Preparations for (var i = 0; i < size; i++) { // Deprected options. You should use only columns if (! obj.options.colHeaders[i]) { obj.options.colHeaders[i] = ''; } if (! obj.options.colWidths[i]) { obj.options.colWidths[i] = obj.options.defaultColWidth || '50'; } if (! obj.options.colAlignments[i]) { obj.options.colAlignments[i] = 'center'; } // Default column description if (! obj.options.columns[i]) { obj.options.columns[i] = { type:'text' }; } else if (! obj.options.columns[i]) { obj.options.columns[i].type = 'text'; } if (! obj.options.columns[i].source) { obj.options.columns[i].source = []; } if (! obj.options.columns[i].options) { obj.options.columns[i].options = []; } if (! obj.options.columns[i].editor) { obj.options.columns[i].editor = null; } if (! obj.options.columns[i].allowEmpty) { obj.options.columns[i].allowEmpty = false; } if (! obj.options.columns[i].title) { obj.options.columns[i].title = obj.options.colHeaders[i] ? obj.options.colHeaders[i] : ''; } if (! obj.options.columns[i].width) { obj.options.columns[i].width = obj.options.colWidths[i] ? obj.options.colWidths[i] : '50'; } if (! obj.options.columns[i].align) { obj.options.columns[i].align = obj.options.colAlignments[i] ? obj.options.colAlignments[i] : 'center'; } // Pre-load initial source for json autocomplete if (obj.options.columns[i].type == 'autocomplete' || obj.options.columns[i].type == 'dropdown') { // if remote content if (obj.options.columns[i].url) { requestsIndex.push(i); requests.push(fetch(obj.options.columns[i].url, { headers: new Headers({ 'content-type': 'text/json' }) }) .then(function(data) { return data.json(); })); } } else if (obj.options.columns[i].type == 'calendar') { // Default format for date columns if (! obj.options.columns[i].options.format) { obj.options.columns[i].options.format = 'DD/MM/YYYY'; } } } if (requests.length) { Promise.all(requests).then(function(data) { for (var i = 0; i < data.length; i++) { obj.options.columns[i].source = data[i]; } obj.createTable(); }); } else { // Create table obj.createTable(); } } obj.createTable = function() { // Elements obj.table = document.createElement('table'); obj.thead = document.createElement('thead'); obj.tbody = document.createElement('tbody'); // Create headers controllers obj.headers = []; obj.colgroup = []; // Create table container obj.content = document.createElement('div'); obj.content.classList.add('jexcel_content'); // Create toolbar object obj.toolbar = document.createElement('div'); obj.toolbar.classList.add('jexcel_toolbar'); // Search var searchContainer = document.createElement('div'); var searchText = document.createTextNode((obj.options.text.search) + ': '); obj.searchInput = document.createElement('input'); obj.searchInput.classList.add('jexcel_search'); searchContainer.appendChild(searchText); searchContainer.appendChild(obj.searchInput); obj.searchInput.onfocus = function() { obj.resetSelection(); } // Pagination select option var paginationUpdateContainer = document.createElement('div'); if (obj.options.pagination > 0 && obj.options.paginationOptions && obj.options.paginationOptions.length > 0) { obj.paginationDropdown = document.createElement('select'); obj.paginationDropdown.classList.add('jexcel_pagination_dropdown'); obj.paginationDropdown.onchange = function() { obj.options.pagination = parseInt(this.value); obj.page(0); } for (var i = 0; i < obj.options.paginationOptions.length; i++) { var temp = document.createElement('option'); temp.value = obj.options.paginationOptions[i]; temp.innerHTML = obj.options.paginationOptions[i]; obj.paginationDropdown.appendChild(temp); } paginationUpdateContainer.appendChild(document.createTextNode(obj.options.text.show)); paginationUpdateContainer.appendChild(obj.paginationDropdown); paginationUpdateContainer.appendChild(document.createTextNode(obj.options.text.entries)); } // Filter and pagination container obj.filter = document.createElement('div'); obj.filter.classList.add('jexcel_filter'); obj.filter.appendChild(paginationUpdateContainer); obj.filter.appendChild(searchContainer); // Colsgroup obj.colgroupContainer = document.createElement('colgroup'); var tempCol = document.createElement('col'); tempCol.setAttribute('width', 50); obj.colgroupContainer.appendChild(tempCol); // Nested if (obj.options.nestedHeaders && obj.options.nestedHeaders.length > 0) { // Flexible way to handle nestedheaders if (obj.options.nestedHeaders[0] && obj.options.nestedHeaders[0][0]) { for (var j = 0; j < obj.options.nestedHeaders.length; j++) { obj.thead.appendChild(obj.createNestedHeader(obj.options.nestedHeaders[j])); } } else { obj.thead.appendChild(obj.createNestedHeader(obj.options.nestedHeaders)); } } // Row obj.headerContainer = document.createElement('tr'); var tempCol = document.createElement('td'); tempCol.classList.add('jexcel_selectall'); obj.headerContainer.appendChild(tempCol); for (var i = 0; i < obj.options.columns.length; i++) { // Create header obj.createCellHeader(i); // Append cell to the container obj.headerContainer.appendChild(obj.headers[i]); obj.colgroupContainer.appendChild(obj.colgroup[i]); } obj.thead.appendChild(obj.headerContainer); // Content table obj.table = document.createElement('table'); obj.table.classList.add('jexcel'); obj.table.setAttribute('cellpadding', '0'); obj.table.setAttribute('cellspacing', '0'); obj.table.setAttribute('unselectable', 'yes'); obj.table.setAttribute('onselectstart', 'return false'); obj.table.appendChild(obj.colgroupContainer); obj.table.appendChild(obj.thead); obj.table.appendChild(obj.tbody); // Spreadsheet corner obj.corner = document.createElement('div'); obj.corner.className = 'jexcel_corner'; obj.corner.setAttribute('unselectable', 'on'); obj.corner.setAttribute('onselectstart', 'return false'); if (obj.options.selectionCopy == false) { obj.corner.style.display = 'none'; } // Textarea helper obj.textarea = document.createElement('textarea'); obj.textarea.className = 'jexcel_textarea'; obj.textarea.id = 'jexcel_textarea'; // Contextmenu container obj.contextMenu = document.createElement('div'); obj.contextMenu.className = 'jexcel_contextmenu'; // Create element jSuites.contextmenu(obj.contextMenu, { onclick:function() { obj.contextMenu.contextmenu.close(false); } }); // Powered by jExcel var ads = '<a href="https://bossanova.uk/jexcel/"><img src="//bossanova.uk/jexcel/logo.png">jExcel Spreadsheet</a>'; obj.ads = document.createElement('div'); obj.ads.className = 'jexcel_about'; if (typeof(sessionStorage) !== "undefined") { if (! sessionStorage.getItem('jexcel')) { sessionStorage.setItem('jexcel', true); obj.ads.innerHTML = ads; } } else { obj.ads.innerHTML = ads; } // Create table container TODO: frozen columns var container = document.createElement('div'); container.classList.add('jexcel_table'); // Pagination obj.pagination = document.createElement('div'); obj.pagination.classList.add('jexcel_pagination'); var paginationInfo = document.createElement('div'); var paginationPages = document.createElement('div'); obj.pagination.appendChild(paginationInfo); obj.pagination.appendChild(paginationPages); // Append containers to the table if (obj.options.search == true) { el.appendChild(obj.filter); } // Elements obj.content.appendChild(obj.table); obj.content.appendChild(obj.corner); obj.content.appendChild(obj.textarea); el.appendChild(obj.toolbar); el.appendChild(obj.content); el.appendChild(obj.pagination); el.appendChild(obj.contextMenu); el.appendChild(obj.ads); el.classList.add('jexcel_container'); // Create toolbar if (obj.options.toolbar && obj.options.toolbar.length) { obj.createToolbar(); } // Fullscreen if (obj.options.fullscreen == true) { el.classList.add('fullscreen'); if (obj.options.toolbar) { el.classList.add('with-toolbar'); } } else { // Overflow if (obj.options.tableOverflow == true) { if (obj.options.tableHeight) { obj.content.style['overflow-y'] = 'auto'; obj.content.style.height = obj.options.tableHeight; } if (obj.options.tableWidth) { obj.content.style['overflow-x'] = 'auto'; obj.content.style.width = obj.options.tableWidth; } } } // Actions if (obj.options.columnDrag == true) { obj.thead.classList.add('draggable'); } if (obj.options.columnResize == true) { obj.thead.classList.add('resizable'); } if (obj.options.rowDrag == true) { obj.tbody.classList.add('draggable'); } if (obj.options.rowResize == true) { obj.tbody.classList.add('resizable'); } // Load data obj.setData(); // Style if (obj.options.style) { obj.setStyle(obj.options.style, null, null, 1, 1); } } /** * Set data * * @param array data In case no data is sent, default is reloaded * @return void */ obj.setData = function(data) { // Update data if (data) { if (typeof(data) == 'string') { data = JSON.parse(data); } obj.options.data = data; } // Adjust minimal dimensions var j = 0; var i = 0; var size_i = obj.options.columns.length; var size_j = obj.options.data.length; var min_i = obj.options.minDimensions[0]; var min_j = obj.options.minDimensions[1]; var max_i = min_i > size_i ? min_i : size_i; var max_j = min_j > size_j ? min_j : size_j; for (j = 0; j < max_j; j++) { for (i = 0; i < max_i; i++) { if (obj.options.data[j] == undefined) { obj.options.data[j] = []; } if (obj.options.data[j][i] == undefined) { obj.options.data[j][i] = ''; } } } // Reset containers obj.rows = []; obj.results = null; obj.records = []; obj.history = []; // Reset internal controllers obj.historyIndex = -1; // Reset data obj.tbody.innerHTML = ''; // Lazy loading if (obj.options.lazyLoading == true) { // Load only 100 records var startNumber = 0 var finalNumber = obj.options.data.length < 100 ? obj.options.data.length : 100; if (obj.options.pagination) { obj.options.pagination = false; console.error('JEXCEL: Pagination will be disable due the lazyLoading'); } } else if (obj.options.pagination) { // Pagination if (! obj.pageNumber) { obj.pageNumber = 0; } var quantityPerPage = obj.options.pagination; startNumber = (obj.options.pagination * obj.pageNumber); finalNumber = (obj.options.pagination * obj.pageNumber) + obj.options.pagination; if (obj.options.data.length < finalNumber) { finalNumber = obj.options.data.length; } } else { var startNumber = 0; var finalNumber = obj.options.data.length; } // Append nodes to the HTML for (j = 0; j < obj.options.data.length; j++) { // Create row var tr = obj.createRow(j, obj.options.data[j]); // Append line to the table if (j >= startNumber && j < finalNumber) { obj.tbody.appendChild(tr); } } if (obj.options.lazyLoading == true) { // Do not create pagination with lazyloading activated } else if (obj.options.pagination) { obj.updatePagination(); } // Merge cells if (obj.options.mergeCells) { var keys = Object.keys(obj.options.mergeCells); for (var i = 0; i < keys.length; i++) { var num = obj.options.mergeCells[keys[i]]; obj.setMerge(keys[i], num[0], num[1], 1); } } // Updata table with custom configurations if applicable obj.updateTable(); // Onload if (! obj.ignoreEvents) { if (typeof(obj.options.onload) == 'function') { obj.options.onload(el); } } } /** * Get the whole table data * * @param integer row number * @return string value */ obj.getData = function(highlighted) { // Control vars var dataset = []; var px = 0; var py = 0; // Column and row length var x = obj.options.data[0].length var y = obj.options.data.length // Go through the columns to get the data for (var j = 0; j < y; j++) { px = 0; for (var i = 0; i < x; i++) { // Cell selected or fullset if (! highlighted || obj.records[j][i].classList.contains('highlight')) { // Get value if (! dataset[py]) { dataset[py] = []; } dataset[py][px] = obj.options.data[j][i]; px++; } } if (px > 0) { py++; } } return dataset; } /** * Get a row data by rowNumber */ obj.getRowData = function(rowNumber) { return obj.options.data[rowNumber]; } /** * Set a row data by rowNumber */ obj.setRowData = function(rowNumber, data) { for (var i = 0; i < obj.headers.length; i++) { // Update cell var columnName = jexcel.getColumnNameFromId([ i, rowNumber ]); // Set value obj.setValue(columnName, data[i]); } } /** * Get a column data by columnNumber */ obj.getColumnData = function(columnNumber) { var dataset = []; // Go through the rows to get the data for (var j = 0; j < obj.options.data.length; j++) { dataset.push(obj.options.data[j][columnNumber]); } return dataset; } /** * Create row */ obj.createRow = function(j, data) { // Create container if (! obj.records[j]) { obj.records[j] = []; } // New line of data to be append in the table obj.rows[j] = document.createElement('tr'); obj.rows[j].setAttribute('data-y', j); // Definitions if (obj.options.rows[j]) { if (obj.options.rows[j].height) { obj.rows[j].style.height = obj.options.rows[j].height; } } // Row number label var td = document.createElement('td'); td.innerHTML = parseInt(j + 1); td.setAttribute('data-y', j); td.className = 'jexcel_row'; obj.rows[j].appendChild(td); // Data columns for (i = 0; i < obj.options.columns.length; i++) { // New column of data to be append in the line obj.records[j][i] = obj.createCell(i, j, data[i]); // Add column to the row obj.rows[j].appendChild(obj.records[j][i]); } // Add row to the table body return obj.rows[j]; } /** * Create cell */ obj.createCell = function(i, j, value) { // Create cell and properties var td = document.createElement('td'); td.setAttribute('data-x', i); td.setAttribute('data-y', j); // Hidden column if (obj.options.columns[i].type == 'hidden') { td.style.display = 'none'; td.innerHTML = value; } else if (obj.options.columns[i].type == 'checkbox' || obj.options.columns[i].type == 'radio') { // Create input var element = document.createElement('input'); element.type = obj.options.columns[i].type; element.name = 'c' + i; element.checked = (value == 1 || value == true || value == 'true') ? true : false; element.onclick = function() { obj.setValue(td, this.checked); } if (obj.options.columns[i].readOnly == true) { element.setAttribute('disabled', 'disabled'); } // Append to the table td.appendChild(element); // Make sure the values are correct obj.options.data[j][i] = element.checked; } else if (obj.options.columns[i].type == 'calendar') { // Try formatted date var formatted = jSuites.calendar.extractDateFromString(value, obj.options.columns[i].options.format); // Create calendar cell td.innerHTML = jSuites.calendar.getDateString(formatted ? formatted : value, obj.options.columns[i].options.format); } else if (obj.options.columns[i].type == 'dropdown' || obj.options.columns[i].type == 'autocomplete') { // Create dropdown cell td.classList.add('dropdown'); td.innerHTML = obj.getDropDownValue(i, value); } else if (obj.options.columns[i].type == 'color') { if (obj.options.columns[i].render == 'square') { var color = document.createElement('div'); color.className = 'color'; color.style.backgroundColor = value; td.appendChild(color); } else { td.style.color = value; td.innerHTML = value; } } else if (obj.options.columns[i].type == 'image') { if (value && value.substr(0, 10) == 'data:image') { var img = document.createElement('img'); img.src = value; td.appendChild(img); } } else { if ((''+value).substr(0,1) == '=') { value = obj.executeFormula(value, i, j) } if (obj.options.columns[i].mask) { var decimal = obj.options.columns[i].decimal || '.'; value = '' + jSuites.mask.run(value, obj.options.columns[i].mask, decimal); } td.innerHTML = value; } // Readonly if (obj.options.columns[i].readOnly == true) { td.className = 'readonly'; } // Text align var colAlign = obj.options.columns[i].align ? obj.options.columns[i].align : 'center'; td.style.textAlign = colAlign; // Wrap option if (obj.options.wordWrap == true || obj.options.columns[i].wordWrap == true || td.innerHTML.length > 200) { td.style.whiteSpace = 'pre-wrap'; } // Overflow if (i > 0) { if (value || td.innerHTML) { obj.records[j][i-1].style.overflow = 'hidden'; } else { if (i == obj.options.columns.length - 1) { td.style.overflow = 'hidden'; } } } return td; } obj.createCellHeader = function(colNumber) { // Create col global control var colWidth = obj.options.columns[colNumber].width ? obj.options.columns[colNumber].width : obj.options.defaultColWidth; var colAlign = obj.options.columns[colNumber].align ? obj.options.columns[colNumber].align : 'center'; // Create header cell obj.headers[colNumber] = document.createElement('td'); obj.headers[colNumber].innerHTML = obj.options.columns[colNumber].title ? obj.options.columns[colNumber].title : jexcel.getColumnName(colNumber); obj.headers[colNumber].setAttribute('data-x', colNumber); obj.headers[colNumber].style.textAlign = colAlign; if (obj.options.columns[colNumber].title) { obj.headers[colNumber].setAttribute('title', obj.options.columns[colNumber].title); } // Width control obj.colgroup[colNumber] = document.createElement('col'); obj.colgroup[colNumber].setAttribute('width', colWidth); // Hidden column if (obj.options.columns[colNumber].type == 'hidden') { obj.headers[colNumber].style.display = 'none'; obj.colgroup[colNumber].style.display = 'none'; } } obj.createNestedHeader = function(nestedInformation) { var tr = document.createElement('tr'); tr.classList.add('jexcel_nested'); var td = document.createElement('td'); tr.appendChild(td); var headerIndex = 0; for (var i = 0; i < nestedInformation.length; i++) { // Default values if (! nestedInformation[i].colspan) { nestedInformation[i].colspan = 1; } if (! nestedInformation[i].align) { nestedInformation[i].align = 'center'; } if (! nestedInformation[i].title) { nestedInformation[i].title = ''; } // Classes container var column = []; // Header classes for this cell for (var x = 0; x < nestedInformation[i].colspan; x++) { column.push(headerIndex); headerIndex++; } // Created the nested cell var td = document.createElement('td'); td.setAttribute('data-column', column.join(',')); td.setAttribute('colspan', nestedInformation[i].colspan); td.setAttribute('align', nestedInformation[i].align); td.innerHTML = nestedInformation[i].title; tr.appendChild(td); } return tr; } /** * Create toolbar */ obj.createToolbar = function(toolbar) { if (toolbar) { obj.options.toolbar = toolbar; } else { var toolbar = obj.options.toolbar; } for (var i = 0; i < toolbar.length; i++) { if (toolbar[i].type == 'i') { var toolbarItem = document.createElement('i'); toolbarItem.classList.add('jexcel_toolbar_item'); toolbarItem.classList.add('material-icons'); toolbarItem.setAttribute('data-k', toolbar[i].k); toolbarItem.setAttribute('data-v', toolbar[i].v); // Tooltip if (toolbar[i].tooltip) { toolbarItem.setAttribute('title', toolbar[i].tooltip); } // Handle click if (toolbar[i].onclick && typeof(toolbar[i].onclick)) { toolbarItem.onclick = toolbar[i].onclick; } else { toolbarItem.onclick = function() { var k = this.getAttribute('data-k'); var v = this.getAttribute('data-v'); obj.setStyle(obj.highlighted, k, v); } } // Append element toolbarItem.innerHTML = toolbar[i].content; obj.toolbar.appendChild(toolbarItem); } else if (toolbar[i].type == 'select') { var toolbarItem = document.createElement('select'); toolbarItem.classList.add('jexcel_toolbar_item'); toolbarItem.setAttribute('data-k', toolbar[i].k); // Tooltip if (toolbar[i].tooltip) { toolbarItem.setAttribute('title', toolbar[i].tooltip); } // Handle onchange if (toolbar[i].onchange && typeof(toolbar[i].onchange)) { toolbarItem.onchange = toolbar[i].onchange; } else { toolbarItem.onchange = function() { var k = this.getAttribute('data-k'); obj.setStyle(obj.highlighted, k, this.value); } } // Add options to the dropdown for(var j = 0; j < toolbar[i].v.length; j++) { var toolbarDropdownOption = document.createElement('option'); toolbarDropdownOption.value = toolbar[i].v[j]; toolbarDropdownOption.innerHTML = toolbar[i].v[j]; toolbarItem.appendChild(toolbarDropdownOption); } obj.toolbar.appendChild(toolbarItem); } else if (toolbar[i].type == 'color') { var toolbarItem = document.createElement('i'); toolbarItem.classList.add('jexcel_toolbar_item'); toolbarItem.classList.add('material-icons'); toolbarItem.setAttribute('data-k', toolbar[i].k); toolbarItem.setAttribute('data-v', ''); // Tooltip if (toolbar[i].tooltip) { toolbarItem.setAttribute('title', toolbar[i].tooltip); } obj.toolbar.appendChild(toolbarItem); toolbarItem.onclick = function() { this.color.open(); } toolbarItem.innerHTML = toolbar[i].content; jSuites.color(toolbarItem, { onchange:function(o, v) { var k = o.getAttribute('data-k'); obj.setStyle(obj.highlighted, k, v); } }); } } } /** * Merge cells * @param cellName * @param colspan * @param rowspan * @param ignoreHistoryAndEvents */ obj.setMerge = function(cellName, colspan, rowspan, ignoreHistoryAndEvents) { var test = false; if (! cellName) { if (! obj.highlighted.length) { alert(obj.options.text.noCellsSelected); return null; } else { var x1 = parseInt(obj.highlighted[0].getAttribute('data-x')); var y1 = parseInt(obj.highlighted[0].getAttribute('data-y')); var x2 = parseInt(obj.highlighted[obj.highlighted.length-1].getAttribute('data-x')); var y2 = parseInt(obj.highlighted[obj.highlighted.length-1].getAttribute('data-y')); var cellName = jexcel.getColumnNameFromId([ x1, y1 ]); var colspan = (x2 - x1) + 1; var rowspan = (y2 - y1) + 1; } } var cell = jexcel.getIdFromColumnName(cellName, true); if (obj.options.mergeCells[cellName]) { if (obj.records[cell[1]][cell[0]].getAttribute('data-merged')) { test = obj.options.text.cellAlreadyMerged; } } else if ((! colspan || colspan < 2) && (! rowspan || rowspan < 2)) { test = obj.options.text.invalidMergeProperties; } else { var cells = []; for (var j = cell[1]; j < cell[1] + rowspan; j++) { for (var i = cell[0]; i < cell[0] + colspan; i++) { var columnName = jexcel.getColumnNameFromId([i, j]); if (obj.records[j][i].getAttribute('data-merged')) { test = obj.options.text.thereIsAConflictWithAnotherMergedCell; } } } } if (test) { alert(test); } else { // Add property if (colspan > 1) { obj.records[cell[1]][cell[0]].setAttribute('colspan', colspan); } else { colspan = 1; } if (rowspan > 1) { obj.records[cell[1]][cell[0]].setAttribute('rowspan', rowspan); } else { rowspan = 1; } // Keep links to the existing nodes obj.options.mergeCells[cellName] = [ colspan, rowspan, [] ]; // Mark cell as merged obj.records[cell[1]][cell[0]].setAttribute('data-merged', 'true'); // Overflow obj.records[cell[1]][cell[0]].style.overflow = 'hidden'; // History data var data = []; // Adjust the nodes for (var y = cell[1]; y < cell[1] + rowspan; y++) { for (var x = cell[0]; x < cell[0] + colspan; x++) { if (! (cell[0] == x && cell[1] == y)) { data.push(obj.options.data[y][x]); obj.updateCell(x, y, '', true); obj.options.mergeCells[cellName][2].push(obj.records[y][x]); obj.records[y][x].style.display = 'none'; obj.records[y][x] = obj.records[cell[1]][cell[0]]; } } } // In the initialization is not necessary keep the history obj.updateSelection(obj.records[cell[1]][cell[0]]); if (! ignoreHistoryAndEvents) { obj.setHistory({ action:'setMerge', column:cellName, colspan:colspan, rowspan:rowspan, data:data, }); if (typeof(obj.options.onmerge) == 'function') { obj.options.onmerge(el, column, width, oldWidth); } } } } /** * Merge cells * @param cellName * @param colspan * @param rowspan * @param ignoreHistoryAndEvents */ obj.getMerge = function(cellName) { var data = {}; if (cellName) { if (obj.options.mergeCells[cellName]) { data = [ obj.options.mergeCells[cellName][0], obj.options.mergeCells[cellName][1] ]; } else { data = null; } } else { if (obj.options.mergeCells) { var mergedCells = obj.options.mergeCells; var keys = Object.keys(obj.options.mergeCells); for (var i = 0; i < keys.length; i++) { data[keys[i]] = [ obj.options.mergeCells[keys[i]][0], obj.options.mergeCells[keys[i]][1] ]; } } } return data; } /** * Remove merge by cellname * @param cellName */ obj.removeMerge = function(cellName, data, keepOptions) { if (obj.options.mergeCells[cellName]) { var cell = jexcel.getIdFromColumnName(cellName, true); obj.records[cell[1]][cell[0]].removeAttribute('colspan'); obj.records[cell[1]][cell[0]].removeAttribute('rowspan'); obj.records[cell[1]][cell[0]].removeAttribute('data-merged'); var info = obj.options.mergeCells[cellName]; var index = 0; for (var j = 0; j < info[1]; j++) { for (var i = 0; i < info[0]; i++) { if (j > 0 || i > 0) { obj.records[cell[1]+j][cell[0]+i] = info[2][index]; obj.records[cell[1]+j][cell[0]+i].style.display = ''; // Recover data if (data && data[index]) { obj.updateCell(cell[0]+i, cell[1]+j, data[index]); } index++; } } } // Update selection obj.updateSelection(obj.records[cell[1]][cell[0]], obj.records[cell[1]+j-1][cell[0]+i-1]); if (! keepOptions) { delete(obj.options.mergeCells[cellName]); } } } /** * Remove all merged cells */ obj.destroyMerged = function(keepOptions) { // Remove any merged cells if (obj.options.mergeCells) { var mergedCells = obj.options.mergeCells; var keys = Object.keys(obj.options.mergeCells); for (var i = 0; i < keys.length; i++) { obj.removeMerge(keys[i], null, keepOptions); } } } /** * Is column merged */ obj.isColMerged = function(x, insertBefore) { var cols = []; // Remove any merged cells if (obj.options.mergeCells) { var keys = Object.keys(obj.options.mergeCells); for (var i = 0; i < keys.length; i++) { var info = jexcel.getIdFromColumnName(keys[i], true); var colspan = obj.options.mergeCells[keys[i]][0]; var x1 = info[0]; var x2 = info[0] + (colspan > 1 ? colspan - 1 : 0); if (insertBefore == null) { if ((x1 <= x && x2 >= x)) { cols.push(keys[i]); } } else { if (insertBefore) { if ((x1 < x && x2 >= x)) { cols.push(keys[i]); } } else { if ((x1 <= x && x2 > x)) { cols.push(keys[i]); } } } } } return cols; } /** * Is rows merged */ obj.isRowMerged = function(y, insertBefore) { var rows = []; // Remove any merged cells if (obj.options.mergeCells) { var keys = Object.keys(obj.options.mergeCells); for (var i = 0; i < keys.length; i++) { var info = jexcel.getIdFromColumnName(keys[i], true); var rowspan = obj.options.mergeCells[keys[i]][1]; var y1 = info[1]; var y2 = info[1] + (rowspan > 1 ? rowspan - 1 : 0); if (insertBefore == null) { if ((y1 <= y && y2 >= y)) { rows.push(keys[i]); } } else { if (insertBefore) { if ((y1 < y && y2 >= y)) { rows.push(keys[i]); } } else { if ((y1 <= y && y2 > y)) { rows.push(keys[i]); } } } } } return rows; } /** * Open the editor * * @param object cell * @return void */ obj.openEditor = function(cell, empty, e) { // Get cell position var y = cell.getAttribute('data-y'); var x = cell.getAttribute('data-x'); // Overflow if (x > 0) { obj.records[y][x-1].style.overflow = 'hidden'; } // Create editor var createEditor = function(type) { // Cell information let info = cell.getBoundingClientRect(); // Create dropdown var editor = document.createElement(type); editor.style.width = (info.width) + 'px'; editor.style.height = (info.height - 2) + 'px'; editor.style.minHeight = (info.height - 2) + 'px'; // Edit cell cell.classList.add('editor'); cell.innerHTML = ''; cell.appendChild(editor); return editor; } // Readonly if (cell.classList.contains('readonly') == true) { // Do nothing } else { // Holder obj.edition = [ obj.records[y][x], obj.records[y][x].innerHTML, x, y ]; // If there is a custom editor for it if (obj.options.columns[x].editor) { // Custom editors obj.options.columns[x].editor.openEditor(cell, el); } else { // Native functions if (obj.options.columns[x].type == 'hidden') { // Do nothing } else if (obj.options.columns[x].type == 'checkbox' || obj.options.columns[x].type == 'radio') { // Get value var value = cell.children[0].checked ? false : true; // Toogle value obj.setValue(cell, value); // Do not keep edition open obj.edition = null; } else if (obj.options.columns[x].type == 'dropdown' || obj.options.columns[x].type == 'autocomplete') { // Get current value var value = obj.options.data[y][x]; // Create dropdown if (typeof(obj.options.columns[x].filter) == 'function') { var source = obj.options.columns[x].filter(el, cell, x, y, obj.options.columns[x].source); } else { var source = obj.options.columns[x].source; } // Create editor var editor = createEditor('div'); var options = { data: source, multiple: obj.options.columns[x].multiple ? true : false, autocomplete: obj.options.columns[x].autocomplete || obj.options.columns[x].type == 'autocomplete' ? true : false, opened:true, value: obj.options.columns[x].multiple ? value.split(';') : value, width:'100%', height:editor.style.minHeight, position: (obj.options.tableOverflow == true || obj.options.fullscreen == true) ? true : false, onclose:function() { obj.closeEditor(cell, true); } }; if (obj.options.columns[x].options && obj.options.columns[x].options.type) { options.type = obj.options.columns[x].options.type; } jSuites.dropdown(editor, options); } else if (obj.options.columns[x].type == 'calendar' || obj.options.columns[x].type == 'color') { // Value var value = obj.options.data[y][x]; // Create editor var editor = createEditor('input'); editor.value = value; if (obj.options.tableOverflow == true || obj.options.fullscreen == true) { obj.options.columns[x].options.position = true; } obj.options.columns[x].options.value = obj.options.data[y][x]; obj.options.columns[x].options.onclose = function(el, value) { obj.closeEditor(cell, true); } // Current value if (obj.options.columns[x].type == 'color') { jSuites.color(editor, obj.options.columns[x].options); } else { var calendar = jSuites.calendar(editor, obj.options.columns[x].options); calendar.setValue(value); } // Focus on editor editor.focus(); } else if (obj.options.columns[x].type == 'image') { // Value var img = cell.children[0]; // Create editor var editor = createEditor('div'); editor.style.position = 'relative'; var div = document.createElement('div'); div.classList.add('jclose'); if (img && img.src) { div.appendChild(img); } editor.appendChild(div); jSuites.image(div); const rect = cell.getBoundingClientRect(); const rectContent = div.getBoundingClientRect(); if (window.innerHeight < rect.bottom + rectContent.height) { div.style.top = (rect.top - (rectContent.height + 2)) + 'px'; } else { div.style.top = (rect.top) + 'px'; } } else { // Value var value = empty == true ? '' : obj.options.data[y][x]; // Basic editor if (obj.options.wordWrap == true || obj.options.columns[x].wordWrap == true || value.length > 200) { var editor = createEditor('textarea'); } else { var editor = createEditor('input'); // Mask if (obj.options.columns[x].mask) { editor.setAttribute('data-mask', obj.options.columns[x].mask); } } editor.value = value; editor.onblur = function() { obj.closeEditor(cell, true); }; editor.focus(); } } } } /** * Close the editor and save the information * * @param object cell * @param boolean save * @return void */ obj.closeEditor = function(cell, save) { var x = parseInt(cell.getAttribute('data-x')); var y = parseInt(cell.getAttribute('data-y')); // Get cell properties if (save == true) { // If custom editor if (obj.options.columns[x].editor) { // Custom editor var value = obj.options.columns[x].editor.closeEditor(cell, save); } else { // Native functions if (obj.options.columns[x].type == 'checkbox' || obj.options.columns[x].type == 'radio' || obj.options.columns[x].type == 'hidden') { // Do nothing } else if (obj.options.columns[x].type == 'dropdown' || obj.options.columns[x].type == 'autocomplete') { var value = cell.children[0].dropdown.close(true); } else if (obj.options.columns[x].type == 'calendar') { var value = cell.children[0].calendar.close(true); } else if (obj.options.columns[x].type == 'color') { var value = cell.children[1].color.close(true); } else if (obj.options.columns[x].type == 'image') { var img = cell.children[0].children[0].children[0]; var value = img && img.tagName == 'IMG' ? img.src : ''; } else if (obj.options.columns[x].type == 'numeric') { var value = cell.children[0].value; if (value.substr(0,1) != '=') { if (value == '') { value = obj.options.columns[x].allowEmpty ? '' : 0; } } cell.children[0].onblur = null; } else { var value = cell.children[0].value; cell.children[0].onblur = null; } } // Update values var ignoreEvents = obj.ignoreEvents ? true : false; var ignoreHistory = obj.ignoreHistory ? true : false; // Ignore changes if the value is the same if (obj.options.data[y][x] == value) { // Disabled events and history obj.ignoreEvents = true; obj.ignoreHistory = true; } // Save value does not affect the table if (obj.edition[1] == value) { cell.innerHTML = obj.edition[1]; } else { obj.setValue(cell, value); } // Restore events and history flag obj.ignoreEvents = ignoreEvents; obj.ignoreHistory = ignoreHistory; } else { if (obj.options.columns[x].editor) { // Custom editor obj.options.columns[x].editor.closeEditor(cell, save); } else { if (obj.options.columns[x].type == 'dropdown' || obj.options.columns[x].type == 'autocomplete') { cell.children[0].dropdown.close(false); } else if (obj.options.columns[x].type == 'calendar') { cell.children[0].calendar.close(false); } else if (obj.options.columns[x].type == 'color') { cell.children[1].color.close(false); } else { cell.children[0].onblur = null; } } // Restore value cell.innerHTML = obj.edition[1]; } // Remove editor class cell.classList.remove('editor'); // Finish edition obj.edition = null; }, /** * Get the value from a cell * * @param object cell * @return string value */ obj.getValue = function(cell) { if (typeof(cell) == 'object') { var x = cell.getAttribute('data-x'); var y = cell.getAttribute('data-y'); } else { cell = jexcel.getIdFromColumnName(cell, true); var x = cell[0]; var y = cell[1]; } if (x != null && y != null) { return obj.options.data[y][x]; } return null; } /** * Get the value from a coords * * @param int x * @param int y * @return string value */ obj.getValueFromCoords = function(x, y) { if (x != null && y != null) { return obj.options.data[y][x]; } } /** * Set a cell value * * @param object cell destination cell * @param object value value * @return void */ obj.setValue = function(cell, value, force) { var records = []; if (typeof(cell) == 'string') { var columnId = jexcel.getIdFromColumnName(cell, true); var x = columnId[0]; var y = columnId[1]; // Update cell records.push(obj.updateCell(x, y, value)); } else { var keys = Object.keys(cell); if (keys.length > 0) { for (var i = 0; i < keys.length; i++) { var x = cell[i].getAttribute('data-x'); var y = cell[i].getAttribute('data-y'); // Update cell records.push(obj.updateCell(x, y, value)); } } else { var x = cell.getAttribute('data-x'); var y = cell.getAttribute('data-y'); // Update cell records.push(obj.updateCell(x, y, value)); } } // Update all formulas in the chain obj.updateFormulaChain(x, y, records); // Update history obj.setHistory({ action:'setValue', records:records, selection:obj.selectedCell, }); // Update table with custom configurations if applicable obj.updateTable(); } /** * Toogle */ obj.setCheckRadioValue = function() { var records = []; var keys = Object.keys(obj.highlighted); for (var i = 0; i < keys.length; i++) { var x = obj.highlighted[i].getAttribute('data-x'); var y = obj.highlighted[i].getAttribute('data-y'); if (obj.options.columns[x].type == 'checkbox' || obj.options.columns[x].type == 'radio') { // Update cell records.push(obj.updateCell(x, y, ! obj.options.data[y][x])); } } if (records.length) { // Update history obj.setHistory({ action:'setValue', records:records, selection:obj.selectedCell, }); } } /** * Update cell content * * @param object cell * @return void */ obj.updateCell = function(x, y, value, force) { // Changing value depending on the column type if (obj.records[y][x].classList.contains('readonly') == true && ! force) { // Do nothing } else { // On change if (! obj.ignoreEvents) { if (typeof(obj.options.onbeforechange) == 'function') { obj.options.onbeforechange(el, obj.records[y][x], x, y, value); } } // History format var record = { col: x, row: y, newValue: value, oldValue: obj.options.data[y][x], } if (obj.options.columns[x].editor) { // Update data and cell obj.options.data[y][x] = value; obj.options.columns[x].editor.setValue(obj.records[y][x], value, force); } else { // Native functions if (obj.options.columns[x].type == 'checkbox' || obj.options.columns[x].type == 'radio') { // Unchecked all options if (obj.options.columns[x].type == 'radio') { for (var j = 0; j < obj.options.data.length; j++) { obj.options.data[j][x] = false; } } // Update data and cell obj.records[y][x].children[0].checked = (value == 1 || value == true || value == 'true') ? true : false; obj.options.data[y][x] = obj.records[y][x].children[0].checked; } else if (obj.options.columns[x].type == 'dropdown' || obj.options.columns[x].type == 'autocomplete') { // Update data and cell obj.options.data[y][x] = value; obj.records[y][x].innerHTML = obj.getDropDownValue(x, value); } else if (obj.options.columns[x].type == 'calendar') { // Update calendar var formatted = jSuites.calendar.extractDateFromString(value, obj.options.columns[x].options.format); // Update data and cell obj.options.data[y][x] = value; obj.records[y][x].innerHTML = jSuites.calendar.getDateString(formatted ? formatted : value, obj.options.columns[x].options.format); } else if (obj.options.columns[x].type == 'color') { // Update color obj.options.data[y][x] = value; // Render if (obj.options.columns[x].render == 'square') { var color = document.createElement('div'); color.className = 'color'; color.style.backgroundColor = value; obj.records[y][x].innerHTML = ''; obj.records[y][x].appendChild(color); } else { obj.records[y][x].style.color = value; obj.records[y][x].innerHTML = value; } } else if (obj.options.columns[x].type == 'image') { value = ''+value; obj.options.data[y][x] = value; obj.records[y][x].innerHTML = ''; if (value && value.substr(0, 10) == 'data:image') { var img = document.createElement('img'); img.src = value; obj.records[y][x].appendChild(img); } } else { // Update data and cell if (obj.options.columns[x].autoCasting != false) { obj.options.data[y][x] = (value && Number(value) == value) ? Number(value) : value; } else { obj.options.data[y][x] = value; } // Label if (('' + value).substr(0,1) == '=') { value = obj.executeFormula(value, x, y); } if (obj.options.columns[x].mask) { var decimal = obj.options.columns[x].decimal || '.'; value = '' + jSuites.mask.run(value, obj.options.columns[x].mask, decimal); } obj.records[y][x].innerHTML = value; // Handle big text inside a cell if (obj.records[y][x].innerHTML.length > 200) { obj.records[y][x].style.whiteSpace = 'pre-wrap'; } else { if (obj.options.wordWrap == false && obj.options.columns[x].wordWrap == false) { obj.records[y][x].style.whiteSpace = ''; } } } } // Overflow if (x > 0) { if (obj.options.data[y][x] || (obj.options.columns[x].type != 'text' && obj.options.columns[x].type != 'number')) { obj.records[y][x-1].style.overflow = 'hidden'; } else { obj.records[y][x-1].style.overflow = ''; } } // On change if (! obj.ignoreEvents) { if (typeof(obj.options.onchange) == 'function') { obj.options.onchange(el, obj.records[y][x], x, y, value); } } } return record; } /** * Helper function to copy data using the corner icon */ obj.copyData = function(o, d) { // Get data from all selected cells var data = obj.getData(true); // Selected cells var t0 = obj.selectedContainer[1]; var t1 = obj.selectedContainer[3]; // Cells var x1 = parseInt(o.getAttribute('data-x')); var y1 = parseInt(o.getAttribute('data-y')); var x2 = parseInt(d.getAttribute('data-x')); var y2 = parseInt(d.getAttribute('data-y')); // Records var records = []; var recordsChain = []; var lineNumber = 1; var breakControl = false; // Copy data procedure var posx = 0; var posy = 0; for (var j = y1; j <= y2; j++) { if (obj.rows[j].style.display == 'none') { continue; } // Controls if (data[posy] == undefined) { posy = 0; } posx = 0; // Data columns for (var i = x1; i <= x2; i++) { // Update non-readonly if (obj.records[j][i] && ! obj.records[j][i].classList.contains('readonly') && obj.records[j][i].style.display != 'none' && breakControl == false) { // Stop if contains value if (! obj.selection.length) { if (obj.options.data[j][i]) { breakControl = true; continue; } } // Column if (data[posy] == undefined) { posx = 0; } else if (data[posy][posx] == undefined) { posx = 0; } else { var value = data[posy][posx]; } if (value && t0 == t1) { if (obj.options.columns[i].type == 'text' || obj.options.columns[i].type == 'number') { if ((''+value).substr(0,1) == '=') { var tokens = value.match(/([A-Z]+[0-9]+)/g); if (tokens) { var affectedTokens = []; for (var index = 0; index < tokens.length; index++) { var position = jexcel.getIdFromColumnName(tokens[index], 1); position[1] += lineNumber; var token = jexcel.getColumnNameFromId([position[0], position[1]]); if (token != tokens[index]) { affectedTokens[tokens[index]] = token; } } // Update formula if (affectedTokens) { value = obj.updateFormula(value, affectedTokens) } } } else { if (value == Number(value)) { value = Number(value) + lineNumber; } } } else if (obj.options.columns[i].type == 'calendar') { var date = new Date(value); date.setDate(date.getDate() + lineNumber); value = date.getFullYear() + '-' + parseInt(date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':00'; } } records.push(obj.updateCell(i, j, value)); // Update formulas chain if ((''+value).substr(0,1) == '=') { recordsChain[i + ',' + j] = true; } } posx++; } posy++; lineNumber++; } // Update all formulas in the chain var keys = Object.keys(recordsChain); for (var i = 0; i < keys.length; i++) { var k = keys[i].split(','); obj.updateFormulaChain(k[0], k[1], records); } // Update history obj.setHistory({ action:'setValue', records:records, selection:obj.selectedCell, }); // Update table with custom configuration if applicable obj.updateTable(); } /** * Refresh current selection */ obj.refreshSelection = function() { if (obj.selectedCell) { obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } } /** * Move coords to A1 in case ovelaps with an excluded cell */ obj.conditionalSelectionUpdate = function(type, o, d) { if (type == 1) { if (obj.selectedCell && ((o >= obj.selectedCell[1] && o <= obj.selectedCell[3]) || (d >= obj.selectedCell[1] && d <= obj.selectedCell[3]))) { obj.resetSelection(); return; } } else { if (obj.selectedCell && ((o >= obj.selectedCell[0] && o <= obj.selectedCell[2]) || (d >= obj.selectedCell[0] && d <= obj.selectedCell[2]))) { obj.resetSelection(); return; } } } /** * Clear table selection */ obj.resetSelection = function(blur) { // Remove style if (! obj.highlighted.length) { var previousStatus = 0; } else { var previousStatus = 1; for (var i = 0; i < obj.highlighted.length; i++) { obj.highlighted[i].classList.remove('highlight'); obj.highlighted[i].classList.remove('highlight-left'); obj.highlighted[i].classList.remove('highlight-right'); obj.highlighted[i].classList.remove('highlight-top'); obj.highlighted[i].classList.remove('highlight-bottom'); obj.highlighted[i].classList.remove('highlight-selected'); var px = parseInt(obj.highlighted[i].getAttribute('data-x')); var py = parseInt(obj.highlighted[i].getAttribute('data-y')); // Check for merged cells if (obj.highlighted[i].getAttribute('data-merged')) { var colspan = parseInt(obj.highlighted[i].getAttribute('colspan')); var rowspan = parseInt(obj.highlighted[i].getAttribute('rowspan')); var ux = colspan > 0 ? px + (colspan - 1) : px; var uy = rowspan > 0 ? py + (rowspan - 1): py; } else { var ux = px; var uy = py; } // Remove selected from headers for (var j = px; j <= ux; j++) { if (obj.headers[j]) { obj.headers[j].classList.remove('selected'); } } // Remove selected from rows for (var j = py; j <= uy; j++) { if (obj.rows[j]) { obj.rows[j].classList.remove('selected'); } } } } // Reset highlighed cells obj.highlighted = []; // Reset obj.selectedCell = null; // Hide corner obj.corner.style.top = '-2000px'; obj.corner.style.left = '-2000px'; if (obj.ignoreEvents != true && blur == true) { if (obj.options.onblur) { if (typeof(obj.options.onblur) == 'function') { if (previousStatus == 1) { obj.options.onblur(el); } } } } return previousStatus; } /** * Update selection based on two cells */ obj.updateSelection = function(el1, el2, origin) { var x1 = el1.getAttribute('data-x'); var y1 = el1.getAttribute('data-y'); if (el2) { var x2 = el2.getAttribute('data-x'); var y2 = el2.getAttribute('data-y'); } else { var x2 = x1; var y2 = y1; } obj.updateSelectionFromCoords(x1, y1, x2, y2, origin); } /** * Update selection from coords */ obj.updateSelectionFromCoords = function(x1, y1, x2, y2, origin) { // Reset Selection var updated = null; var previousState = obj.resetSelection(); // Same element if (x2 == null) { x2 = x1; } if (y2 == null) { y2 = y1; } // Selection must be within the existing data if (x1 >= obj.headers.length) { x1 = obj.headers.length - 1; } if (y1 >= obj.rows.length) { y1 = obj.rows.length - 1; } if (x2 >= obj.headers.length) { x2 = obj.headers.length - 1; } if (y2 >= obj.rows.length) { y2 = obj.rows.length - 1; } // Keep selected cell obj.selectedCell = [x1, y1, x2, y2]; // Select cells if (x1 != null) { // Add selected cell obj.records[y1][x1].classList.add('highlight-selected') // Origin & Destination if (parseInt(x1) < parseInt(x2)) { var px = parseInt(x1); var ux = parseInt(x2); } else { var px = parseInt(x2); var ux = parseInt(x1); } if (parseInt(y1) < parseInt(y2)) { var py = parseInt(y1); var uy = parseInt(y2); } else { var py = parseInt(y2); var uy = parseInt(y1); } // Verify merged columns for (var i = px; i <= ux; i++) { for (var j = py; j <= uy; j++) { if (obj.records[j][i].getAttribute('data-merged')) { var x = parseInt(obj.records[j][i].getAttribute('data-x')); var y = parseInt(obj.records[j][i].getAttribute('data-y')); var colspan = parseInt(obj.records[j][i].getAttribute('colspan')); var rowspan = parseInt(obj.records[j][i].getAttribute('rowspan')); if (colspan > 1) { if (x < px) { px = x; } if (x + colspan > ux) { ux = x + colspan - 1; } } if (rowspan) { if (y < py) { py = y; } if (y + rowspan > uy) { uy = y + rowspan - 1; } } } } } // Limits var borderLeft = null; var borderRight = null; var borderTop = null; var borderBottom = null; // Vertical limits for (var j = py; j <= uy; j++) { if (obj.rows[j].style.display != 'none') { if (borderTop == null) { borderTop = j; } borderBottom = j; } } // Redefining styles for (var i = px; i <= ux; i++) { for (var j = py; j <= uy; j++) { if (obj.rows[j].style.display != 'none' && obj.records[j][i].style.display != 'none') { obj.records[j][i].classList.add('highlight'); obj.highlighted.push(obj.records[j][i]); } } // Horizontal limits if (obj.options.columns[i].type != 'hidden') { if (borderLeft == null) { borderLeft = i; } borderRight = i; } } // Create borders if (! borderLeft) { borderLeft = 0; } if (! borderRight) { borderRight = 0; } for (var i = borderLeft; i <= borderRight; i++) { if (obj.options.columns[i].type != 'hidden') { // Top border obj.records[borderTop][i].classList.add('highlight-top'); // Bottom border obj.records[borderBottom][i].classList.add('highlight-bottom'); // Add selected from headers obj.headers[i].classList.add('selected'); } } for (var j = borderTop; j <= borderBottom; j++) { if (obj.rows[j].style.display != 'none') { // Left border obj.records[j][borderLeft].classList.add('highlight-left'); // Right border obj.records[j][borderRight].classList.add('highlight-right'); // Add selected from rows obj.rows[j].classList.add('selected'); } } obj.selectedContainer = [borderLeft, borderTop, borderRight, borderBottom]; } // Handle events if (obj.ignoreEvents != true) { if (obj.options.onfocus) { if (typeof(obj.options.onfocus) == 'function') { if (previousState == 0) { obj.options.onfocus(el); } } } if (typeof(obj.options.onselection) == 'function') { obj.options.onselection(el, borderLeft, borderTop, borderRight, borderBottom, origin); } } // Find corner cell obj.updateCornerPosition(); } /** * Remove copy selection * * @return void */ obj.removeCopySelection = function() { // Remove current selection for (var i = 0; i < obj.selection.length; i++) { obj.selection[i].classList.remove('selection'); obj.selection[i].classList.remove('selection-left'); obj.selection[i].classList.remove('selection-right'); obj.selection[i].classList.remove('selection-top'); obj.selection[i].classList.remove('selection-bottom'); } obj.selection = []; } /** * Update copy selection * * @param int x, y * @return void */ obj.updateCopySelection = function(x3, y3) { // Remove selection obj.removeCopySelection(); // Get elements first and last var x1 = obj.selectedContainer[0]; var y1 = obj.selectedContainer[1]; var x2 = obj.selectedContainer[2]; var y2 = obj.selectedContainer[3]; if (x3 && y3) { if (x3 - x2 > 0) { var px = parseInt(x2) + 1; var ux = parseInt(x3); } else { var px = parseInt(x3); var ux = parseInt(x1) - 1; } if (y3 - y2 > 0) { var py = parseInt(y2) + 1; var uy = parseInt(y3); } else { var py = parseInt(y3); var uy = parseInt(y1) - 1; } if (ux - px < uy - py) { var px = parseInt(x1); var ux = parseInt(x2); } else { var py = parseInt(y1); var uy = parseInt(y2); } for (var j = py; j <= uy; j++) { for (var i = px; i <= ux; i++) { if (obj.records[j][i] && obj.rows[j].style.display != 'none' && obj.records[j][i].style.display != 'none') { obj.records[j][i].classList.add('selection'); obj.records[py][i].classList.add('selection-top'); obj.records[uy][i].classList.add('selection-bottom'); obj.records[j][px].classList.add('selection-left'); obj.records[j][ux].classList.add('selection-right'); // Persist selected elements obj.selection.push(obj.records[j][i]); } } } } } /** * Update corner position * * @return void */ obj.updateCornerPosition = function() { // If any selected cells if (! obj.highlighted.length) { obj.corner.style.top = '-2000px'; obj.corner.style.left = '-2000px'; } else { // Get last cell var last = obj.highlighted[obj.highlighted.length-1]; var x1 = obj.content.getBoundingClientRect().left; var y1 = obj.content.getBoundingClientRect().top; var x2 = last.getBoundingClientRect().left; var y2 = last.getBoundingClientRect().top; var w2 = last.getBoundingClientRect().width; var h2 = last.getBoundingClientRect().height; var x = (x2 - x1) + obj.content.scrollLeft + w2 - 4; var y = (y2 - y1) + obj.content.scrollTop + h2 - 4; // Place the corner in the correct place obj.corner.style.top = y + 'px'; obj.corner.style.left = x + 'px'; } } /** * Update scroll position based on the selection */ obj.updateScroll = function(direction) { // jExcel Container information var x1 = obj.content.getBoundingClientRect().left; var y1 = obj.content.getBoundingClientRect().top; var w1 = obj.content.getBoundingClientRect().width; var h1 = obj.content.getBoundingClientRect().height; // Direction Left or Up var reference = obj.records[obj.selectedCell[3]][obj.selectedCell[2]]; var x2 = reference.getBoundingClientRect().left; var y2 = reference.getBoundingClientRect().top; var w2 = reference.getBoundingClientRect().width; var h2 = reference.getBoundingClientRect().height; // Direction if (direction == 0 || direction == 1) { var x = (x2 - x1) + obj.content.scrollLeft; var y = (y2 - y1) + obj.content.scrollTop - 2; } else { var x = (x2 - x1) + obj.content.scrollLeft + w2; var y = (y2 - y1) + obj.content.scrollTop + h2; } // Top position check if (y > (obj.content.scrollTop + 30) && y < (obj.content.scrollTop + h1)) { // In the viewport } else { // Out of viewport if (y < obj.content.scrollTop + 30) { obj.content.scrollTop = y - h2; } else { obj.content.scrollTop = y - (h1 - 2); } } // Left position check - TODO: change that to the bottom border of the element if (x > (obj.content.scrollLeft) && x < (obj.content.scrollLeft + w1)) { // In the viewport } else { // Out of viewport if (x < obj.content.scrollLeft + 30) { obj.content.scrollLeft = x; if (obj.content.scrollLeft < 50) { obj.content.scrollLeft = 0; } } else { obj.content.scrollLeft = x - (w1 - 20); } } } /** * Get the column width * * @param int column column number (first column is: 0) * @return int current width */ obj.getWidth = function(column) { if (! column) { // Get all headers var data = []; for (var i = 0; i < obj.headers.length; i++) { data.push(obj.options.columns[i].width); } } else { // In case the column is an object if (typeof(column) == 'object') { column = $(column).getAttribute('data-x'); } data = obj.colgroup[column].getAttribute('width') } return data; } /** * Set the column width * * @param int column number (first column is: 0) * @param int new column width * @param int old column width */ obj.setWidth = function (column, width, oldWidth) { if (width > 0) { // In case the column is an object if (typeof(column) == 'object') { column = $(column).getAttribute('data-x'); } // Oldwidth if (! oldWidth) { obj.colgroup[column].getAttribute('width'); } // Set width obj.colgroup[column].setAttribute('width', width); obj.options.columns[column].width = width; // Keeping history of changes obj.setHistory({ action:'setWidth', column:column, oldValue:oldWidth, newValue:width, }); // On resize column if (obj.ignoreEvents != true) { if (typeof(obj.options.onresizecolumn) == 'function') { obj.options.onresizecolumn(el, column, width, oldWidth); } } // Update corner position obj.updateCornerPosition(); } } /** * Set the row height * * @param row - row number (first row is: 0) * @param height - new row height * @param oldHeight - old row height */ obj.setHeight = function (row, height, oldHeight) { if (height > 0) { // In case the column is an object if (typeof(row) == 'object') { column = $(row).getAttribute('data-y'); } // Oldwidth if (! oldHeight) { obj.rows[row].getAttribute('height'); } // Set width obj.rows[row].setAttribute('height', height); // Keep options updated if (! obj.options.rows[row]) { obj.options.rows[row] = {}; } obj.options.rows[row].height = height; // Keeping history of changes obj.setHistory({ action:'setHeight', row:row, oldValue:oldHeight, newValue:height, }); // On resize column if (obj.ignoreEvents != true) { if (typeof(obj.options.onresizerow) == 'function') { obj.options.onresizerow(el, row, height, oldHeight); } } // Update corner position obj.updateCornerPosition(); } } /** * Get the row height * * @param row - row number (first column is: 0) * @return height - current row height */ obj.getHeight = function(row) { if (! row) { } else { // In case the column is an object if (typeof(row) == 'object') { row = $(row).getAttribute('data-y'); } data = obj.rows[row].getAttribute('height') } return data; } /** * Get the column title * * @param column - column number (first column is: 0) * @param title - new column title */ obj.getHeader = function(column) { return obj.headers[column].innerText; } /** * Set the column title * * @param column - column number (first column is: 0) * @param title - new column title */ obj.setHeader = function(column, newValue) { if (obj.headers[column]) { var oldValue = obj.headers[column].innerText; if (! newValue) { newValue = prompt('Column name', oldValue) } if (newValue) { obj.headers[column].innerHTML = newValue; } obj.setHistory({ action: 'setHeader', column: column, oldValue: oldValue, newValue: newValue }); } } /** * Get the headers * * @param asArray * @return mixed */ obj.getHeaders = function (asArray) { var title = []; for (var i = 0; i < obj.headers.length; i++) { title.push(obj.getHeader(i)); } return asArray ? title : title.join(','); } /** * Get meta information from cell(s) * * @return integer */ obj.getMeta = function(cell, key) { if (! cell) { return obj.options.meta; } else { return key ? obj.options.meta[cell][key] : obj.options.meta[cell]; } } /** * Set meta information to cell(s) * * @return integer */ obj.setMeta = function(o, k, v) { if (! obj.options.meta) { obj.options.meta = {} } if (k && v) { // Set data value if (! obj.options.meta[o]) { obj.options.meta[o] = {}; } obj.options.meta[o][k] = v; } else { // Apply that for all cells var keys = Object.keys(o); for (var i = 0; i < keys.length; i++) { if (! obj.options.meta[keys[i]]) { obj.options.meta[keys[i]] = {}; } var prop = Object.keys(o[keys[i]]); for (var j = 0; j < prop.length; j++) { obj.options.meta[keys[i]][prop[j]] = o[keys[i]][prop[j]]; } } } } /** * Get style information from cell(s) * * @return integer */ obj.getStyle = function(cell, key) { // Cell if (! cell) { // Control vars var data = {}; // Column and row length var x = obj.options.data[0].length; var y = obj.options.data.length; // Go through the columns to get the data for (var j = 0; j < y; j++) { for (var i = 0; i < x; i++) { // Value var v = key ? obj.records[j][i].style[key] : obj.records[j][i].getAttribute('style'); // Any meta data for this column? if (v) { // Column name var k = jexcel.getColumnNameFromId([i, j]); // Value data[k] = v; } } } return data; } else { cell = jexcel.getIdFromColumnName(cell, true); return key ? obj.records[cell[1]][cell[0]].style[key] : obj.records[cell[1]][cell[0]].getAttribute('style'); } }, obj.resetStyle = function(o, ignoreHistoryAndEvents) { var keys = Object.keys(o); for (var i = 0; i < keys.length; i++) { // Position var cell = jexcel.getIdFromColumnName(keys[i], true); if (obj.records[cell[1]] && obj.records[cell[1]][cell[0]]) { obj.records[cell[1]][cell[0]].setAttribute('style', ''); } } obj.setStyle(o, null, null, null, ignoreHistoryAndEvents); } /** * Set meta information to cell(s) * * @return integer */ obj.setStyle = function(o, k, v, force, ignoreHistoryAndEvents) { var newValue = {}; var oldValue = {}; // Apply style var applyStyle = function(cellId, key, value) { // Position var cell = jexcel.getIdFromColumnName(cellId, true); if (obj.records[cell[1]] && obj.records[cell[1]][cell[0]]) { // Current value var currentValue = obj.records[cell[1]][cell[0]].style[key]; // Change layout if (currentValue == value && ! force) { value = ''; obj.records[cell[1]][cell[0]].style[key] = ''; } else { obj.records[cell[1]][cell[0]].style[key] = value; } // History if (! oldValue[cellId]) { oldValue[cellId] = []; } if (! newValue[cellId]) { newValue[cellId] = []; } oldValue[cellId].push([key + ':' + currentValue]); newValue[cellId].push([key + ':' + value]); } } if (k && v) { // Get object from string if (typeof(o) == 'string') { applyStyle(o, k, v); } else { // Avoid duplications var oneApplication = []; // Apply that for all cells for (var i = 0; i < o.length; i++) { var x = o[i].getAttribute('data-x'); var y = o[i].getAttribute('data-y'); var cellName = jexcel.getColumnNameFromId([x, y]); // This happens when is a merged cell if (! oneApplication[cellName]) { applyStyle(cellName, k, v); oneApplication[cellName] = true; } } } } else { var keys = Object.keys(o); for (var i = 0; i < keys.length; i++) { var style = o[keys[i]]; if (typeof(style) == 'string') { style = style.split(';'); } for (var j = 0; j < style.length; j++) { if (typeof(style[j]) == 'string') { style[j] = style[j].split(':'); } // Apply value if (style[j][0].trim()) { applyStyle(keys[i], style[j][0].trim(), style[j][1]); } } } } var keys = Object.keys(oldValue); for (var i = 0; i < keys.length; i++) { oldValue[keys[i]] = oldValue[keys[i]].join(';'); } var keys = Object.keys(newValue); for (var i = 0; i < keys.length; i++) { newValue[keys[i]] = newValue[keys[i]].join(';'); } if (! ignoreHistoryAndEvents) { // Keeping history of changes obj.setHistory({ action: 'setStyle', oldValue: oldValue, newValue: newValue, }); } } /** * Get cell comments */ obj.getComments = function(cell, withAuthor) { if (typeof(cell) == 'string') { var cell = jexcel.getIdFromColumnName(cell, true); } if (withAuthor) { return [obj.records[cell[1]][cell[0]].getAttribute('title'), obj.records[cell[1]][cell[0]].getAttribute('author')]; } else { return obj.records[cell[1]][cell[0]].getAttribute('title') || ''; } } /** * Set cell comments */ obj.setComments = function(cellId, comments, author) { if (typeof(cellId) == 'string') { var cell = jexcel.getIdFromColumnName(cellId, true); } else { var cell = cellId; } // Keep old value var title = obj.records[cell[1]][cell[0]].getAttribute('title'); var author = obj.records[cell[1]][cell[0]].getAttribute('data-author'); var oldValue = [ title, author ]; // Set new values obj.records[cell[1]][cell[0]].setAttribute('title', comments ? comments : ''); obj.records[cell[1]][cell[0]].setAttribute('data-author', author ? author : ''); // Remove class if there is no comment if (comments) { obj.records[cell[1]][cell[0]].classList.add('jexcel_comments'); } else { obj.records[cell[1]][cell[0]].classList.remove('jexcel_comments'); } // Save history obj.setHistory({ action:'setComments', column: cellId, newValue: [ comments, author ], oldValue: oldValue, }); } /** * Get table config information */ obj.getConfig = function() { var options = obj.options; options.style = obj.getStyle(); options.mergeCells = obj.getMerge(); return options; } /** * Sort data and reload table */ obj.orderBy = function(column, order) { if (column >= 0) { // Merged cells if (Object.keys(obj.options.mergeCells).length > 0) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { // Remove merged cells obj.destroyMerged(); } } // Direction if (order == null) { order = obj.headers[column].classList.contains('arrow-down') ? 1 : 0; } else { order = order ? 1 : 0; } // Filter Array.prototype.orderBy = function(p, o) { return this.slice(0).sort(function(a, b) { var valueA = Number(a[p]) == a[p] ? Number(a[p]) : a[p].toLowerCase(); var valueB = Number(b[p]) == b[p] ? Number(b[p]) : b[p].toLowerCase(); if (! o) { return (valueA > valueB) ? 1 : (valueA < valueB) ? -1 : 0; } else { return (valueA > valueB) ? -1 : (valueA < valueB) ? 1 : 0; } }); } // Test order var temp = []; if (obj.options.columns[column].type == 'calendar' || obj.options.columns[column].type == 'checkbox' || obj.options.columns[column].type == 'radio') { for (var j = 0; j < obj.options.data.length; j++) { temp[j] = [ j, obj.options.data[j][column] ]; } } else { for (var j = 0; j < obj.options.data.length; j++) { temp[j] = [ j, obj.records[j][column].innerHTML ]; } } temp = temp.orderBy(1, order); // Save history var newValue = []; for (var j = 0; j < temp.length; j++) { newValue[j] = temp[j][0]; } // Save history obj.setHistory({ action: 'orderBy', rows: newValue, column: column, order: order, }); // Update order obj.updateOrderArrow(column, order); obj.updateOrder(newValue); // On sort event if (obj.ignoreEvents != true) { if (typeof(obj.options.onsort) == 'function') { obj.options.onsort(el, column, order); } } return true; } } /** * Update order arrow */ obj.updateOrderArrow = function(column, order) { // Remove order for (var i = 0; i < obj.headers.length; i++) { obj.headers[i].classList.remove('arrow-up'); obj.headers[i].classList.remove('arrow-down'); } // No order specified then toggle order if (order) { obj.headers[column].classList.add('arrow-up'); } else { obj.headers[column].classList.add('arrow-down'); } } /** * Update rows position */ obj.updateOrder = function(rows) { // History var data = [] for (var j = 0; j < rows.length; j++) { data[j] = obj.options.data[rows[j]]; } obj.options.data = data; var data = [] for (var j = 0; j < rows.length; j++) { data[j] = obj.records[rows[j]]; } obj.records = data; var data = [] for (var j = 0; j < rows.length; j++) { data[j] = obj.rows[rows[j]]; } obj.rows = data; // Update references obj.updateTableReferences(); // Redo search if (obj.searchInput.value) { obj.search(obj.searchInput.value); } else { // Create page obj.results = null; obj.pageNumber = 0; if (obj.options.pagination > 0) { obj.page(0); } else if (obj.options.lazyLoading == true) { obj.loadPage(0); } else { for (var j = 0; j < obj.rows.length; j++) { obj.tbody.appendChild(obj.rows[j]); } } } } /** * Move row * * @return void */ obj.moveRow = function(o, d, ignoreDom) { if (Object.keys(obj.options.mergeCells).length > 0) { if (obj.isRowMerged(d).length) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { obj.destroyMerged(); } } } if (obj.options.search == true) { if (obj.results && obj.results.length != obj.rows.length) { if (confirm(obj.options.text.thisActionWillClearYourSearchResultsAreYouSure)) { obj.resetSearch(); } else { return false; } } obj.results = null; } if (! ignoreDom) { if (Array.prototype.indexOf.call(obj.tbody.children, obj.rows[d]) >= 0) { if (o > d) { obj.tbody.insertBefore(obj.rows[o], obj.rows[d]); } else { obj.tbody.insertBefore(obj.rows[o], obj.rows[d].nextSibling); } } else { obj.tbody.removeChild(obj.rows[o]); } } // Place references in the correct position obj.rows.splice(d, 0, obj.rows.splice(o, 1)[0]); obj.records.splice(d, 0, obj.records.splice(o, 1)[0]); obj.options.data.splice(d, 0, obj.options.data.splice(o, 1)[0]); // Respect pagination if (obj.options.pagination > 0 && obj.tbody.children.length != obj.options.pagination) { obj.page(obj.pageNumber); } // Keeping history of changes obj.setHistory({ action:'moveRow', oldValue: o, newValue: d, }); // Update table references obj.updateTableReferences(); // Events if (obj.ignoreEvents != true) { if (typeof(obj.options.onmoverow) == 'function') { obj.options.onmoverow(el, o, d); } } } /** * Insert a new row * * @param mixed - number of blank lines to be insert or a single array with the data of the new row * @param rowNumber * @param insertBefore * @return void */ obj.insertRow = function(mixed, rowNumber, insertBefore) { // Configuration if (obj.options.allowInsertRow == true) { // Records var records = []; // Data to be insert var data = []; // The insert could be lead by number of rows or the array of data if (mixed > 0) { var numOfRows = mixed; } else { var numOfRows = 1; if (mixed) { data = mixed; } } // Direction var insertBefore = insertBefore ? true : false; // Current column number var lastRow = obj.options.data.length - 1; if (rowNumber == undefined || rowNumber >= parseInt(lastRow) || rowNumber < 0) { rowNumber = lastRow; } // Onbeforeinsertrow if (typeof(obj.options.onbeforeinsertrow) == 'function') { if (! obj.options.onbeforeinsertrow(el, rowNumber, numOfRows, insertBefore)) { console.log('onbeforeinsertrow returned false'); return false; } } // Merged cells if (Object.keys(obj.options.mergeCells).length > 0) { if (obj.isRowMerged(rowNumber, insertBefore).length) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { obj.destroyMerged(); } } } // Clear any search if (obj.options.search == true) { if (obj.results && obj.results.length != obj.rows.length) { if (confirm(obj.options.text.thisActionWillClearYourSearchResultsAreYouSure)) { obj.resetSearch(); } else { return false; } } obj.results = null; } // Insertbefore var rowIndex = (! insertBefore) ? rowNumber + 1 : rowNumber; // Keep the current data var currentRecords = obj.records.splice(rowIndex); var currentData = obj.options.data.splice(rowIndex); var currentRows = obj.rows.splice(rowIndex); // Adding lines var rowRecords = []; var rowData = []; var rowNode = []; for (var row = rowIndex; row < (numOfRows + rowIndex); row++) { // Push data to the data container obj.options.data[row] = []; for (var col = 0; col < obj.options.columns.length; col++) { obj.options.data[row][col] = data[col] ? data[col] : ''; } // Create row var tr = obj.createRow(row, obj.options.data[row]); // Append node if (! currentRows[0] || Array.prototype.indexOf.call(obj.tbody.children, currentRows[0]) >= 0) { obj.tbody.insertBefore(tr, currentRows[0]); } // Record History rowRecords.push(obj.records[row]); rowData.push(obj.options.data[row]); rowNode.push(tr); } // Copy the data back to the main data Array.prototype.push.apply(obj.records, currentRecords); Array.prototype.push.apply(obj.options.data, currentData); Array.prototype.push.apply(obj.rows, currentRows); // Respect pagination if (obj.options.pagination > 0) { obj.page(obj.pageNumber); } // Keep history obj.setHistory({ action: 'insertRow', rowNumber: rowNumber, numOfRows: numOfRows, insertBefore: insertBefore, rowRecords: rowRecords, rowData: rowData, rowNode: rowNode, }); // Remove table references obj.updateTableReferences(); // Events if (obj.ignoreEvents != true) { if (typeof(obj.options.oninsertrow) == 'function') { obj.options.oninsertrow(el, rowNumber, numOfRows, rowRecords, insertBefore); } } } } /** * Delete a row by number * * @param integer rowNumber - row number to be excluded * @param integer numOfRows - number of lines * @return void */ obj.deleteRow = function(rowNumber, numOfRows) { // Global Configuration if (obj.options.allowDeleteRow == true) { if (obj.options.data.length > 1) { // Delete row definitions if (rowNumber == undefined) { var number = obj.getSelectedRows(); if (! number[0]) { rowNumber = obj.options.data.length - 1; numOfRows = 1; } else { rowNumber = parseInt(number[0].getAttribute('data-y')); numOfRows = number.length; } } // Last column var lastRow = obj.options.data.length - 1; if (rowNumber == undefined || rowNumber > lastRow || rowNumber < 0) { rowNumber = lastRow; } if (! numOfRows) { numOfRows = 1; } // Do not delete more than the number of recoreds if (rowNumber + numOfRows >= obj.options.data.length) { numOfRows = obj.options.data.length - rowNumber; } // Onbeforedeleterow if (typeof(obj.options.onbeforedeleterow) == 'function') { if (! obj.options.onbeforedeleterow(el, rowNumber, numOfRows)) { console.log('onbeforedeleterow returned false'); return false; } } if (parseInt(rowNumber) > -1) { // Merged cells var mergeExists = false; if (Object.keys(obj.options.mergeCells).length > 0) { for (var row = rowNumber; row < rowNumber + numOfRows; row++) { if (obj.isRowMerged(row, false).length) { mergeExists = true; } } } if (mergeExists) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { obj.destroyMerged(); } } // Clear any search if (obj.options.search == true) { if (obj.results && obj.results.length != obj.rows.length) { if (confirm(obj.options.text.thisActionWillClearYourSearchResultsAreYouSure)) { obj.resetSearch(); } else { return false; } } obj.results = null; } // Remove node for (var row = rowNumber; row < rowNumber + numOfRows; row++) { if (Array.prototype.indexOf.call(obj.tbody.children, obj.rows[row]) >= 0) { obj.rows[row].className = ''; obj.rows[row].remove(); } } // Remove data var rowRecords = obj.records.splice(rowNumber, numOfRows); var rowData = obj.options.data.splice(rowNumber, numOfRows); var rowNode = obj.rows.splice(rowNumber, numOfRows); // Respect pagination if (obj.options.pagination > 0 && obj.tbody.children.length != obj.options.pagination) { obj.page(obj.pageNumber); } // Remove selection obj.conditionalSelectionUpdate(1, rowNumber, (rowNumber + numOfRows) - 1); // Keep history obj.setHistory({ action: 'deleteRow', rowNumber: rowNumber, numOfRows: numOfRows, insertBefore: 1, rowRecords: rowRecords, rowData: rowData, rowNode: rowNode }); // Remove table references obj.updateTableReferences(); // Events if (obj.ignoreEvents != true) { if (typeof(obj.options.ondeleterow) == 'function') { obj.options.ondeleterow(el, rowNumber, numOfRows, rowRecords); } } } } else { console.error('JEXCEL. It is not possible to delete the last row'); } } } /** * Move column * * @return void */ obj.moveColumn = function(o, d) { if (Object.keys(obj.options.mergeCells).length > 0) { if (obj.isColMerged(d).length) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { obj.destroyMerged(); } } } var o = parseInt(o); var d = parseInt(d); if (o > d) { obj.headerContainer.insertBefore(obj.headers[o], obj.headers[d]); obj.colgroupContainer.insertBefore(obj.colgroup[o], obj.colgroup[d]); for (var j = 0; j < obj.rows.length; j++) { obj.rows[j].insertBefore(obj.records[j][o], obj.records[j][d]); } } else { obj.headerContainer.insertBefore(obj.headers[o], obj.headers[d].nextSibling); obj.colgroupContainer.insertBefore(obj.colgroup[o], obj.colgroup[d].nextSibling); for (var j = 0; j < obj.rows.length; j++) { obj.rows[j].insertBefore(obj.records[j][o], obj.records[j][d].nextSibling); } } obj.options.columns.splice(d, 0, obj.options.columns.splice(o, 1)[0]); obj.headers.splice(d, 0, obj.headers.splice(o, 1)[0]); obj.colgroup.splice(d, 0, obj.colgroup.splice(o, 1)[0]); for (var j = 0; j < obj.rows.length; j++) { obj.options.data[j].splice(d, 0, obj.options.data[j].splice(o, 1)[0]); obj.records[j].splice(d, 0, obj.records[j].splice(o, 1)[0]); } // Keeping history of changes obj.setHistory({ action:'moveColumn', oldValue: o, newValue: d, }); // Update table references obj.updateTableReferences(); // Events if (obj.ignoreEvents != true) { if (typeof(obj.options.onmovecolumn) == 'function') { obj.options.onmovecolumn(el, o, d); } } } /** * Insert a new column * * @param mixed - num of columns to be added or data to be added in one single column * @param int columnNumber - number of columns to be created * @param bool insertBefore * @param object properties - column properties * @return void */ obj.insertColumn = function(mixed, columnNumber, insertBefore, properties) { // Configuration if (obj.options.allowInsertColumn == true) { // Records var records = []; // Data to be insert var data = []; // The insert could be lead by number of rows or the array of data if (mixed > 0) { var numOfColumns = mixed; } else { var numOfColumns = 1; if (mixed) { data = mixed; } } // Direction var insertBefore = insertBefore ? true : false; // Current column number var lastColumn = obj.options.columns.length - 1; // Confirm position if (columnNumber == undefined || columnNumber >= parseInt(lastColumn) || columnNumber < 0) { columnNumber = lastColumn; } // Onbeforeinsertcolumn if (typeof(obj.options.onbeforeinsertcolumn) == 'function') { if (! obj.options.onbeforeinsertcolumn(el, columnNumber, numOfColumns, insertBefore)) { console.log('onbeforeinsertcolumn returned false'); return false; } } // Merged cells if (Object.keys(obj.options.mergeCells).length > 0) { if (obj.isColMerged(columnNumber, insertBefore).length) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { obj.destroyMerged(); } } } // Create default properties if (! properties) { properties = []; } if (! properties.columns) { properties.columns = []; } for (var i = 0; i < numOfColumns; i++) { if (! properties.columns[i]) { properties.columns[i] = { type:'text', source:[], options:[], width:'50', align:'center' }; } } // Insert before var columnIndex = (! insertBefore) ? columnNumber + 1 : columnNumber; obj.options.columns = jexcel.injectArray(obj.options.columns, columnIndex, properties.columns); // Open space in the containers var currentHeaders = obj.headers.splice(columnIndex); var currentColgroup = obj.colgroup.splice(columnIndex); // History var historyHeaders = []; var historyColgroup = []; var historyRecords = []; var historyData = []; // Add new headers for (var col = columnIndex; col < (numOfColumns + columnIndex); col++) { obj.createCellHeader(col); obj.headerContainer.insertBefore(obj.headers[col], obj.headerContainer.children[col+1]); obj.colgroupContainer.insertBefore(obj.colgroup[col], obj.colgroupContainer.children[col+1]); historyHeaders.push(obj.headers[col]); historyColgroup.push(obj.colgroup[col]); } // Adding visual columns for (var row = 0; row < obj.options.data.length; row++) { // Keep the current data var currentData = obj.options.data[row].splice(columnIndex); var currentRecord = obj.records[row].splice(columnIndex); // History historyData[row] = []; historyRecords[row] = []; for (var col = columnIndex; col < (numOfColumns + columnIndex); col++) { // New value var value = data[row] ? data[row] : ''; obj.options.data[row][col] = value; // New cell var td = obj.createCell(col, row, obj.options.data[row][col]); obj.records[row][col] = td; // Add cell to the row if (obj.rows[row]) { obj.rows[row].insertBefore(td, obj.rows[row].children[col+1]); } // Record History historyData[row].push(value); historyRecords[row].push(td); } // Copy the data back to the main data Array.prototype.push.apply(obj.options.data[row], currentData); Array.prototype.push.apply(obj.records[row], currentRecord); } Array.prototype.push.apply(obj.headers, currentHeaders); Array.prototype.push.apply(obj.colgroup, currentColgroup); // Adjust nested headers if (obj.options.nestedHeaders && obj.options.nestedHeaders.length > 0) { // Flexible way to handle nestedheaders if (obj.options.nestedHeaders[0] && obj.options.nestedHeaders[0][0]) { for (var j = 0; j < obj.options.nestedHeaders.length; j++) { var colspan = parseInt(obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan) + numOfColumns; obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan = colspan; obj.thead.children[j].children[obj.thead.children[j].children.length-1].setAttribute('colspan', colspan); } } else { var colspan = parseInt(obj.options.nestedHeaders[0].colspan) + numOfColumns; obj.options.nestedHeaders[0].colspan = colspan; obj.thead.children[0].children[obj.thead.children[0].children.length-1].setAttribute('colspan', colspan); } } // Keep history obj.setHistory({ action: 'insertColumn', columnNumber:columnNumber, numOfColumns:numOfColumns, insertBefore:insertBefore, columns:properties.columns, headers:historyHeaders, colgroup:historyColgroup, records:historyRecords, data:historyData, }); // Remove table references obj.updateTableReferences(); // Events if (obj.ignoreEvents != true) { if (typeof(obj.options.oninsertcolumn) == 'function') { obj.options.oninsertcolumn(el, columnNumber, numOfColumns); } } } } /** * Delete a column by number * * @param integer columnNumber - reference column to be excluded * @param integer numOfColumns - number of columns to be excluded from the reference column * @return void */ obj.deleteColumn = function(columnNumber, numOfColumns) { // Global Configuration if (obj.options.allowDeleteColumn == true) { if (obj.headers.length > 1) { // Delete column definitions if (columnNumber == undefined) { var number = obj.getSelectedColumns(true); if (! number.length) { // Remove last column columnNumber = obj.headers.length - 1; numOfColumns = 1; } else { // Remove selected columnNumber = parseInt(number[0]); numOfColumns = parseInt(number.length); } } // Lasat column var lastColumn = obj.options.data[0].length - 1; if (columnNumber == undefined || columnNumber > lastColumn || columnNumber < 0) { columnNumber = lastColumn; } // Minimum of columns to be delete is 1 if (! numOfColumns) { numOfColumns = 1; } // Can't delete more than the limit of the table if (numOfColumns > obj.options.data[0].length - columnNumber) { numOfColumns = obj.options.data[0].length - columnNumber; } // onbeforedeletecolumn if (typeof(obj.options.onbeforedeletecolumn) == 'function') { if (! obj.options.onbeforedeletecolumn(el, columnNumber, numOfColumns)) { console.log('onbeforedeletecolumn returned false'); return false; } } // Can't remove the last column if (parseInt(columnNumber) > -1) { // Merged cells var mergeExists = false; if (Object.keys(obj.options.mergeCells).length > 0) { for (var col = columnNumber; col < columnNumber + numOfColumns; col++) { if (obj.isColMerged(col, false).length) { mergeExists = true; } } } if (mergeExists) { if (! confirm(obj.options.text.thisActionWillDestroyAnyExistingMergedCellsAreYouSure)) { return false; } else { obj.destroyMerged(); } } // Delete the column properties var columns = obj.options.columns.splice(columnNumber, numOfColumns); for (var col = columnNumber; col < columnNumber + numOfColumns; col++) { obj.colgroup[col].className = ''; obj.headers[col].className = ''; obj.colgroup[col].remove(); obj.headers[col].remove(); } var historyHeaders = obj.headers.splice(columnNumber, numOfColumns); var historyColgroup = obj.colgroup.splice(columnNumber, numOfColumns); var historyRecords = []; var historyData = []; for (var row = 0; row < obj.options.data.length; row++) { for (var col = columnNumber; col < columnNumber + numOfColumns; col++) { obj.records[row][col].className = ''; obj.records[row][col].remove(); } } // Delete headers for (var row = 0; row < obj.options.data.length; row++) { // History historyData[row] = obj.options.data[row].splice(columnNumber, numOfColumns); historyRecords[row] = obj.records[row].splice(columnNumber, numOfColumns); } // Remove selection obj.conditionalSelectionUpdate(0, columnNumber, (columnNumber + numOfColumns) - 1); // Adjust nested headers if (obj.options.nestedHeaders && obj.options.nestedHeaders.length > 0) { // Flexible way to handle nestedheaders if (obj.options.nestedHeaders[0] && obj.options.nestedHeaders[0][0]) { for (var j = 0; j < obj.options.nestedHeaders.length; j++) { var colspan = parseInt(obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan) - numOfColumns; obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan = colspan; obj.thead.children[j].children[obj.thead.children[j].children.length-1].setAttribute('colspan', colspan); } } else { var colspan = parseInt(obj.options.nestedHeaders[0].colspan) - numOfColumns; obj.options.nestedHeaders[0].colspan = colspan; obj.thead.children[0].children[obj.thead.children[0].children.length-1].setAttribute('colspan', colspan); } } // Keeping history of changes obj.setHistory({ action:'deleteColumn', columnNumber:columnNumber, numOfColumns:numOfColumns, insertBefore: 1, columns:columns, headers:historyHeaders, colgroup:historyColgroup, records:historyRecords, data:historyData, }); // Update table references obj.updateTableReferences(); // Delete if (obj.ignoreEvents != true) { if (typeof(obj.options.ondeletecolumn) == 'function') { obj.options.ondeletecolumn(el, columnNumber, numOfColumns, records); } } } } else { console.error('JEXCEL. It is not possible to delete the last column'); } } } /** * Get seleted rows numbers * * @return array */ obj.getSelectedRows = function(asIds) { var rows = []; // Get all selected rows for (var j = 0; j < obj.rows.length; j++) { if (obj.rows[j].classList.contains('selected')) { if (asIds) { rows.push(j); } else { rows.push(obj.rows[j]); } } } return rows; }, /** * Get seleted column numbers * * @return array */ obj.getSelectedColumns = function() { var cols = []; // Get all selected cols for (var i = 0; i < obj.headers.length; i++) { if (obj.headers[i].classList.contains('selected')) { cols.push(i); } } return cols; } /** * Get highlighted * * @return array */ obj.getHighlighted = function() { return obj.highlighted; } /** * Update cell references * * @return void */ obj.updateTableReferences = function() { // Update headers for (var i = 0; i < obj.headers.length; i++) { var x = obj.headers[i].getAttribute('data-x'); if (x != i) { // Update coords obj.headers[i].setAttribute('data-x', i); // Title if (! obj.headers[i].getAttribute('title')) { obj.headers[i].innerHTML = jexcel.getColumnName(i); } } } // Update all rows for (var j = 0; j < obj.rows.length; j++) { var y = obj.rows[j].getAttribute('data-y'); if (y != j) { // Update coords obj.rows[j].setAttribute('data-y', j); obj.rows[j].children[0].setAttribute('data-y', j); // Row number obj.rows[j].children[0].innerHTML = j + 1; } } // Regular cells affected by this change var affectedTokens = []; var mergeCellUpdates = []; // Update cell var updatePosition = function(x,y,i,j) { if (x != i) { obj.records[j][i].setAttribute('data-x', i); } if (y != j) { obj.records[j][i].setAttribute('data-y', j); } // Other updates if (x != i || y != j) { var columnIdFrom = jexcel.getColumnNameFromId([x, y]); var columnIdTo = jexcel.getColumnNameFromId([i, j]); affectedTokens[columnIdFrom] = columnIdTo; } } for (var j = 0; j < obj.records.length; j++) { for (var i = 0; i < obj.records[0].length; i++) { // Current values var x = obj.records[j][i].getAttribute('data-x'); var y = obj.records[j][i].getAttribute('data-y'); // Update column if (obj.records[j][i].getAttribute('data-merged')) { var columnIdFrom = jexcel.getColumnNameFromId([x, y]); var columnIdTo = jexcel.getColumnNameFromId([i, j]); if (mergeCellUpdates[columnIdFrom] == null) { if (columnIdFrom == columnIdTo) { mergeCellUpdates[columnIdFrom] = false; } else { var totalX = parseInt(i - x); var totalY = parseInt(j - y); mergeCellUpdates[columnIdFrom] = [ columnIdTo, totalX, totalY ]; } } } else { updatePosition(x,y,i,j); } } } // Update merged if applicable var keys = Object.keys(mergeCellUpdates); if (keys.length) { for (var i = 0; i < keys.length; i++) { if (mergeCellUpdates[keys[i]]) { var info = jexcel.getIdFromColumnName(keys[i], true) var x = info[0]; var y = info[1]; updatePosition(x,y,x + mergeCellUpdates[keys[i]][1],y + mergeCellUpdates[keys[i]][2]); var columnIdFrom = keys[i]; var columnIdTo = mergeCellUpdates[keys[i]][0]; for (var j = 0; j < obj.options.mergeCells[columnIdFrom][2].length; j++) { var x = parseInt(obj.options.mergeCells[columnIdFrom][2][j].getAttribute('data-x')); var y = parseInt(obj.options.mergeCells[columnIdFrom][2][j].getAttribute('data-y')); obj.options.mergeCells[columnIdFrom][2][j].setAttribute('data-x', x + mergeCellUpdates[keys[i]][1]); obj.options.mergeCells[columnIdFrom][2][j].setAttribute('data-y', y + mergeCellUpdates[keys[i]][2]); } obj.options.mergeCells[columnIdTo] = obj.options.mergeCells[columnIdFrom]; delete(obj.options.mergeCells[columnIdFrom]); } } } // Update formulas obj.updateFormulas(affectedTokens); // Refresh selection obj.refreshSelection(); // Update table with custom configuration if applicable obj.updateTable(); } /** * Custom settings for the cells */ obj.updateTable = function() { // Check for spare if (obj.options.minSpareRows > 0) { var numBlankRows = 0; for (var j = obj.rows.length - 1; j >= 0; j--) { var test = false; for (var i = 0; i < obj.headers.length; i++) { if (obj.options.data[j][i]) { test = true; } } if (test) { break; } else { numBlankRows++; } } if (obj.options.minSpareRows - numBlankRows > 0) { obj.insertRow(obj.options.minSpareRows - numBlankRows) } } if (obj.options.minSpareCols > 0) { var numBlankCols = 0; for (var i = obj.headers.length - 1; i >= 0 ; i--) { var test = false; for (var j = 0; j < obj.rows.length; j++) { if (obj.options.data[j][i]) { test = true; } } if (test) { break; } else { numBlankCols++; } } if (obj.options.minSpareCols - numBlankCols > 0) { obj.insertColumn(obj.options.minSpareCols - numBlankCols) } } // Customizations by the developer if (typeof(obj.options.updateTable) == 'function') { for (var j = 0; j < obj.rows.length; j++) { for (var i = 0; i < obj.headers.length; i++) { obj.options.updateTable(el, obj.records[j][i], i, j, obj.options.data[j][i], obj.records[j][i].innerText, jexcel.getColumnNameFromId([i, j])); } } } // Update corner position setTimeout(function() { obj.updateCornerPosition(); },0); } /** * Show index column */ obj.showIndex = function() { obj.colgroupContainer.children[0].width = 40; } /** * Hide index column */ obj.hideIndex = function() { obj.colgroupContainer.children[0].width = 0; } /** * Update all related cells in the chain */ obj.updateFormulaChain = function(x, y, records) { var cellId = jexcel.getColumnNameFromId([x, y]); if (obj.formula[cellId] && obj.formula[cellId].length > 0) { for (var i = 0; i < obj.formula[cellId].length; i++) { var cell = jexcel.getIdFromColumnName(obj.formula[cellId][i], true); // Update cell var value = ''+obj.options.data[cell[1]][cell[0]]; if (value.substr(0,1) == '=') { records.push(obj.updateCell(cell[0], cell[1], value, true)); } else { // No longer a formula, remove from the chain Object.keys(obj.formula)[i] = null; } obj.updateFormulaChain(cell[0], cell[1], records); } } } /** * Update formulas */ obj.updateFormulas = function(referencesToUpdate) { // Update formulas for (var j = 0; j < obj.options.data.length; j++) { for (var i = 0; i < obj.options.data[0].length; i++) { var value = '' + obj.options.data[j][i]; // Is formula if (value.substr(0,1) == '=') { // Replace tokens var newFormula = obj.updateFormula(value, referencesToUpdate); if (newFormula != value) { obj.options.data[j][i] = newFormula; } } } } // Update formula chain var formula = []; var keys = Object.keys(obj.formula); for (var j = 0; j < keys.length; j++) { // Current key and values var key = keys[j]; var value = obj.formula[key]; // Update key if (referencesToUpdate[key]) { key = referencesToUpdate[key]; } // Update values formula[key] = []; for (var i = 0; i < value.length; i++) { var letter = value[i]; if (referencesToUpdate[letter]) { letter = referencesToUpdate[letter]; } formula[key].push(letter); } } obj.formula = formula; } /** * Update formula */ obj.updateFormula = function(formula, referencesToUpdate) { var testLetter = /[A-Z]/; var testNumber = /[0-9]/; var newFormula = ''; var letter = null; var number = null; var token = ''; for (var index = 0; index < formula.length; index++) { if (testLetter.exec(formula[index])) { letter = 1; number = 0; token += formula[index]; } else if (testNumber.exec(formula[index])) { number = letter ? 1 : 0; token += formula[index]; } else { if (letter && number) { token = referencesToUpdate[token] ? referencesToUpdate[token] : token; } newFormula += token; newFormula += formula[index]; letter = 0; number = 0; token = ''; } } if (token) { if (letter && number) { token = referencesToUpdate[token] ? referencesToUpdate[token] : token; } newFormula += token; } return newFormula; } /** * Parse formulas */ obj.executeFormula = function(expression, x, y) { // Code protection obj.formulaStack++; if (obj.formulaStack > 5) { console.error('Too many executions...'); return 0; } // Parent column identification var parentId = jexcel.getColumnNameFromId([x, y]); // Convert range tokens var tokensUpdate = function(tokens) { for (var index = 0; index < tokens.length; index++) { var f = []; var token = tokens[index].split(':'); var e1 = jexcel.getIdFromColumnName(token[0], true); var e2 = jexcel.getIdFromColumnName(token[1], true); if (e1[0] <= e2[0]) { var x1 = e1[0]; var x2 = e2[0]; } else { var x1 = e2[0]; var x2 = e1[0]; } if (e1[1] <= e2[1]) { var y1 = e1[1]; var y2 = e2[1]; } else { var y1 = e2[1]; var y2 = e1[1]; } for (var j = y1; j <= y2; j++) { for (var i = x1; i <= x2; i++) { f.push(jexcel.getColumnNameFromId([i, j])); } } expression = expression.replace(tokens[index], f.join(',')); } } var tokens = expression.match(/([A-Z]+[0-9]+)\:([A-Z]+[0-9]+)/g); if (tokens && tokens.length) { tokensUpdate(tokens); } // Get tokens var tokens = expression.match(/([A-Z]+[0-9]+)/g); if (tokens) { var evalstring = ""; for (var i = 0; i < tokens.length; i++) { // Keep chain if (! obj.formula[tokens[i]]) { obj.formula[tokens[i]] = []; } // Is already in the register if (obj.formula[tokens[i]].indexOf(parentId) < 0) { obj.formula[tokens[i]].push(parentId); } // Do not calculate again if (eval('typeof(' + tokens[i] + ') == "undefined"')) { // Declaretion evalstring += "var " + tokens[i] + " = null;"; // Coords var position = jexcel.getIdFromColumnName(tokens[i], 1); // Get value if (obj.records[position[1]] && obj.records[position[1]][position[0]]) { var value = obj.records[position[1]][position[0]].innerHTML; } else if (obj.options.data[position[1]] && obj.options.data[position[1]][position[0]]) { var value = obj.options.data[position[1]][position[0]]; } else { var value = ''; } // Get column data if ((''+value).substr(0,1) == '=') { value = obj.executeFormula(value, position[0], position[1]); } // Type! if ((''+value).trim() == '' || value != Number(value)) { // Trying any formatted number var number = ('' + value); var decimal = obj.options.columns[position[0]].decimal || '.'; number = number.split(decimal); number[0] = number[0].match(/[0-9]*/g).join(''); if (number[1]) { number[1] = number[1].match(/[0-9]*/g).join(''); } // Got a valid number if (number[0] != '' && Number(number[0]) >= 0) { if (! number[1]) { evalstring += "var " + tokens[i] + " = " + number[0] + ".00;"; } else { evalstring += "var " + tokens[i] + " = " + number[0] + '.' + number[1] + ";"; } } else { // Render as string evalstring += "var " + tokens[i] + " = '" + value + "';"; } } else { // Number evalstring += "var " + tokens[i] + " = " + value + ";"; } } } } obj.formulaStack = 0; // Convert formula to javascript try { var res = eval(evalstring + expression.substr(1)); } catch (e) { var res = '#ERROR'; } return res; } /** * Get row number */ obj.row = function(cell) { } /** * Get col number */ obj.col = function(cell) { } obj.up = function(shiftKey, ctrlKey) { if (shiftKey) { if (obj.selectedCell[3] > 0) { obj.up.visible(1, ctrlKey ? 0 : 1) } } else { if (obj.selectedCell[1] > 0) { obj.up.visible(0, ctrlKey ? 0 : 1) } obj.selectedCell[2] = obj.selectedCell[0]; obj.selectedCell[3] = obj.selectedCell[1]; } // Update selection obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); // Change page if (obj.options.lazyLoading == true) { if (obj.selectedCell[1] == 0 || obj.selectedCell[3] == 0) { obj.loadPage(0); obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } else { if (obj.loadValidation()) { obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } else { var item = parseInt(obj.tbody.firstChild.getAttribute('data-y')); if (obj.selectedCell[1] - item < 30) { obj.loadUp(); obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } } } } else if (obj.options.pagination > 0) { var pageNumber = obj.whichPage(obj.selectedCell[3]); if (pageNumber != obj.pageNumber) { obj.page(pageNumber); } } obj.updateScroll(1); } obj.up.visible = function(group, direction) { if (group == 0) { var x = parseInt(obj.selectedCell[0]); var y = parseInt(obj.selectedCell[1]); } else { var x = parseInt(obj.selectedCell[2]); var y = parseInt(obj.selectedCell[3]); } if (direction == 0) { for (var j = 0; j < y; j++) { if (obj.records[j][x].style.display != 'none' && obj.rows[j].style.display != 'none') { y = j; break; } } } else { y = obj.up.get(x, y); } if (group == 0) { obj.selectedCell[0] = x; obj.selectedCell[1] = y; } else { obj.selectedCell[2] = x; obj.selectedCell[3] = y; } } obj.up.get = function(x, y) { var x = parseInt(x); var y = parseInt(y); for (var j = (y - 1); j >= 0; j--) { if (obj.records[j][x].style.display != 'none' && obj.rows[j].style.display != 'none') { if (obj.records[j][x].getAttribute('data-merged')) { if (obj.records[j][x] == obj.records[y][x]) { continue; } } y = j; break; } } return y; } obj.down = function(shiftKey, ctrlKey) { if (shiftKey) { if (obj.selectedCell[3] < obj.records.length - 1) { obj.down.visible(1, ctrlKey ? 0 : 1) } } else { if (obj.selectedCell[1] < obj.records.length - 1) { obj.down.visible(0, ctrlKey ? 0 : 1) } obj.selectedCell[2] = obj.selectedCell[0]; obj.selectedCell[3] = obj.selectedCell[1]; } obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); // Change page if (obj.options.lazyLoading == true) { if ((obj.selectedCell[1] == obj.records.length - 1 || obj.selectedCell[3] == obj.records.length - 1)) { obj.loadPage(-1); obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } else { if (obj.loadValidation()) { obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } else { var item = parseInt(obj.tbody.lastChild.getAttribute('data-y')); if (item - obj.selectedCell[3] < 30) { obj.loadDown(); obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } } } } else if (obj.options.pagination > 0) { var pageNumber = obj.whichPage(obj.selectedCell[3]); if (pageNumber != obj.pageNumber) { obj.page(pageNumber); } } obj.updateScroll(3); } obj.down.visible = function(group, direction) { if (group == 0) { var x = parseInt(obj.selectedCell[0]); var y = parseInt(obj.selectedCell[1]); } else { var x = parseInt(obj.selectedCell[2]); var y = parseInt(obj.selectedCell[3]); } if (direction == 0) { for (var j = obj.rows.length - 1; j > y; j--) { if (obj.records[j][x].style.display != 'none' && obj.rows[j].style.display != 'none') { y = j; break; } } } else { y = obj.down.get(x, y); } if (group == 0) { obj.selectedCell[0] = x; obj.selectedCell[1] = y; } else { obj.selectedCell[2] = x; obj.selectedCell[3] = y; } } obj.down.get = function(x, y) { var x = parseInt(x); var y = parseInt(y); for (var j = (y + 1); j < obj.rows.length; j++) { if (obj.records[j][x].style.display != 'none' && obj.rows[j].style.display != 'none') { if (obj.records[j][x].getAttribute('data-merged')) { if (obj.records[j][x] == obj.records[y][x]) { continue; } } y = j; break; } } return y; } obj.right = function(shiftKey, ctrlKey) { if (shiftKey) { if (obj.selectedCell[2] < obj.headers.length - 1) { obj.right.visible(1, ctrlKey ? 0 : 1) } } else { if (obj.selectedCell[0] < obj.headers.length - 1) { obj.right.visible(0, ctrlKey ? 0 : 1) } obj.selectedCell[2] = obj.selectedCell[0]; obj.selectedCell[3] = obj.selectedCell[1]; } obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); obj.updateScroll(2); } obj.right.visible = function(group, direction) { if (group == 0) { var x = parseInt(obj.selectedCell[0]); var y = parseInt(obj.selectedCell[1]); } else { var x = parseInt(obj.selectedCell[2]); var y = parseInt(obj.selectedCell[3]); } if (direction == 0) { for (var i = obj.headers.length - 1; i > x; i--) { if (obj.records[y][i].style.display != 'none') { x = i; break; } } } else { x = obj.right.get(x, y); } if (group == 0) { obj.selectedCell[0] = x; obj.selectedCell[1] = y; } else { obj.selectedCell[2] = x; obj.selectedCell[3] = y; } } obj.right.get = function(x, y) { var x = parseInt(x); var y = parseInt(y); for (var i = (x + 1); i < obj.headers.length; i++) { if (obj.records[y][i].style.display != 'none') { if (obj.records[y][i].getAttribute('data-merged')) { if (obj.records[y][i] == obj.records[y][x]) { continue; } } x = i; break; } } return x; } obj.left = function(shiftKey, ctrlKey) { if (shiftKey) { if (obj.selectedCell[2] > 0) { obj.left.visible(1, ctrlKey ? 0 : 1) } } else { if (obj.selectedCell[0] > 0) { obj.left.visible(0, ctrlKey ? 0 : 1) } obj.selectedCell[2] = obj.selectedCell[0]; obj.selectedCell[3] = obj.selectedCell[1]; } obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); obj.updateScroll(0); } obj.left.visible = function(group, direction) { if (group == 0) { var x = parseInt(obj.selectedCell[0]); var y = parseInt(obj.selectedCell[1]); } else { var x = parseInt(obj.selectedCell[2]); var y = parseInt(obj.selectedCell[3]); } if (direction == 0) { for (var i = 0; i < x; i++) { if (obj.records[y][i].style.display != 'none') { x = i; break; } } } else { x = obj.left.get(x, y); } if (group == 0) { obj.selectedCell[0] = x; obj.selectedCell[1] = y; } else { obj.selectedCell[2] = x; obj.selectedCell[3] = y; } } obj.left.get = function(x, y) { var x = parseInt(x); var y = parseInt(y); for (var i = (x - 1); i >= 0; i--) { if (obj.records[y][i].style.display != 'none') { if (obj.records[y][i].getAttribute('data-merged')) { if (obj.records[y][i] == obj.records[y][x]) { continue; } } x = i; break; } } return x; } obj.first = function(shiftKey, ctrlKey) { if (shiftKey) { if (ctrlKey) { obj.selectedCell[3] = 0; } else { obj.left.visible(1, 0); } } else { if (ctrlKey) { obj.selectedCell[1] = 0; } else { obj.left.visible(0, 0); } obj.selectedCell[2] = obj.selectedCell[0]; obj.selectedCell[3] = obj.selectedCell[1]; } // Change page if (obj.options.lazyLoading == true && (obj.selectedCell[1] == 0 || obj.selectedCell[3] == 0)) { obj.loadPage(0); } else if (obj.options.pagination > 0) { var pageNumber = obj.whichPage(obj.selectedCell[3]); if (pageNumber != obj.pageNumber) { obj.page(pageNumber); } } obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); obj.updateScroll(1); } obj.last = function(shiftKey, ctrlKey) { if (shiftKey) { if (ctrlKey) { obj.selectedCell[3] = obj.records.length - 1; } else { obj.right.visible(1, 0); } } else { if (ctrlKey) { obj.selectedCell[1] = obj.records.length - 1; } else { obj.right.visible(0, 0); } obj.selectedCell[2] = obj.selectedCell[0]; obj.selectedCell[3] = obj.selectedCell[1]; } // Change page if (obj.options.lazyLoading == true && (obj.selectedCell[1] == obj.records.length - 1 || obj.selectedCell[3] == obj.records.length - 1)) { obj.loadPage(-1); } else if (obj.options.pagination > 0) { var pageNumber = obj.whichPage(obj.selectedCell[3]); if (pageNumber != obj.pageNumber) { obj.page(pageNumber); } } obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); obj.updateScroll(3); } obj.selectAll = function() { if (! obj.selectedCell) { obj.selectedCell = []; } obj.selectedCell[0] = 0; obj.selectedCell[1] = 0; obj.selectedCell[2] = obj.headers.length - 1; obj.selectedCell[3] = obj.records.length - 1; obj.updateSelectionFromCoords(obj.selectedCell[0], obj.selectedCell[1], obj.selectedCell[2], obj.selectedCell[3]); } /** * Go to a page in a lazyLoading */ obj.loadPage = function(pageNumber) { // Search if (obj.options.search == true && obj.results) { var results = obj.results; } else { var results = obj.rows; } // Per page var quantityPerPage = 100; // pageNumber if (pageNumber == null || pageNumber == -1) { // Last page pageNumber = Math.ceil(results.length / quantityPerPage); } var startRow = (pageNumber * quantityPerPage); var finalRow = (pageNumber * quantityPerPage) + quantityPerPage; if (finalRow > results.length) { finalRow = results.length; } startRow = finalRow - 100; if (startRow < 0) { startRow = 0; } // Appeding items for (var j = startRow; j < finalRow; j++) { if (obj.options.search == true && obj.results) { obj.tbody.appendChild(obj.rows[results[j]]); } else { obj.tbody.appendChild(obj.rows[j]); } if (obj.tbody.children.length > quantityPerPage) { obj.tbody.removeChild(obj.tbody.firstChild); } } } obj.loadUp = function() { // Search if (obj.options.search == true && obj.results) { var results = obj.results; } else { var results = obj.rows; } var test = 0; if (results.length > 100) { // Get the first element in the page var item = parseInt(obj.tbody.firstChild.getAttribute('data-y')); if (obj.options.search == true && obj.results) { item = results.indexOf(item); } if (item > 0) { for (var j = 0; j < 30; j++) { item = item - 1; if (item > -1) { if (obj.options.search == true && obj.results) { obj.tbody.insertBefore(obj.rows[results[item]], obj.tbody.firstChild); } else { obj.tbody.insertBefore(obj.rows[item], obj.tbody.firstChild); } if (obj.tbody.children.length > 100) { obj.tbody.removeChild(obj.tbody.lastChild); test = 1; } } } } } return test; } obj.loadDown = function() { // Search if (obj.options.search == true && obj.results) { var results = obj.results; } else { var results = obj.rows; } var test = 0; if (results.length > 100) { // Get the last element in the page var item = parseInt(obj.tbody.lastChild.getAttribute('data-y')); if (obj.options.search == true && obj.results) { item = results.indexOf(item); } if (item < obj.rows.length - 1) { for (var j = 0; j <= 30; j++) { if (item < results.length) { if (obj.options.search == true && obj.results) { obj.tbody.appendChild(obj.rows[results[item]]); } else { obj.tbody.appendChild(obj.rows[item]); } if (obj.tbody.children.length > 100) { obj.tbody.removeChild(obj.tbody.firstChild); test = 1; } } item = item + 1; } } } return test; } obj.loadValidation = function() { if (obj.selectedCell) { var currentPage = parseInt(obj.tbody.firstChild.getAttribute('data-y')) / 100; var selectedPage = parseInt(obj.selectedCell[3] / 100); var totalPages = parseInt(obj.rows.length / 100); if (currentPage != selectedPage && selectedPage <= totalPages) { if (! Array.prototype.indexOf.call(obj.tbody.children, obj.rows[obj.selectedCell[3]])) { obj.loadPage(selectedPage); return true; } } } return false; } /** * Reset search */ obj.resetSearch = function() { obj.searchInput.value = ''; obj.search(''); obj.results = null; } /** * Search */ obj.search = function(query) { // Query if (query) { var query = query.toLowerCase(); } // Reset selection obj.resetSelection(); // Total of results obj.pageNumber = 0; obj.results = []; if (query) { // Search filter var search = function(item, query) { for (var i = 0; i < item.length; i++) { if ((''+item[i]).toLowerCase().search(query) >= 0) { return true; } } return false; } // Result var addToResult = function(k) { if (obj.results.indexOf(k) == -1) { obj.results.push(k); } } // Filter var data = obj.options.data.filter(function(v, k) { if (search(v, query)) { // Merged rows found var rows = obj.isRowMerged(k); if (rows.length) { for (var i = 0; i < rows.length; i++) { var row = jexcel.getIdFromColumnName(rows[i], true); for (var j = 0; j < obj.options.mergeCells[rows[i]][1]; j++) { addToResult(row[1]+j); } } } else { // Normal row found addToResult(k); } return true; } else { return false; } }); } else { obj.results = null; } var total = 0; var index = 0; // Page 1 if (obj.options.lazyLoading == true) { total = 100; } else if (obj.options.pagination > 0) { total = obj.options.pagination; } else { if (obj.results) { total = obj.results.length; } else { total = obj.rows.length; } } // Hide all records from the table obj.tbody.innerHTML = ''; for (var j = 0; j < obj.rows.length; j++) { if (! obj.results || obj.results.indexOf(j) > -1) { if (index < total) { obj.tbody.appendChild(obj.rows[j]); index++; } obj.rows[j].style.display = ''; } else { obj.rows[j].style.display = 'none'; } } if (obj.options.pagination > 0) { obj.updatePagination(); } return total; } /** * Which page the cell is */ obj.whichPage = function(cell) { return (Math.ceil((parseInt(cell) + 1) / parseInt(obj.options.pagination))) - 1; } /** * Go to page */ obj.page = function(pageNumber) { // Search if (obj.options.search == true && obj.results) { var results = obj.results; } else { var results = obj.rows; } // Per page var quantityPerPage = parseInt(obj.options.pagination); // pageNumber if (pageNumber == null || pageNumber == -1) { // Last page pageNumber = Math.ceil(results.length / quantityPerPage); } // Page number obj.pageNumber = pageNumber; var startRow = (pageNumber * quantityPerPage); var finalRow = (pageNumber * quantityPerPage) + quantityPerPage; if (finalRow > results.length) { finalRow = results.length; } if (startRow < 0) { startRow = 0; } // Reset container obj.tbody.innerHTML = ''; // Appeding items for (var j = startRow; j < finalRow; j++) { if (obj.options.search == true && obj.results) { obj.tbody.appendChild(obj.rows[results[j]]); } else { obj.tbody.appendChild(obj.rows[j]); } } if (obj.options.pagination > 0) { obj.updatePagination(); } // Update corner position obj.updateCornerPosition(); } /** * Update the pagination */ obj.updatePagination = function() { // Reset container obj.pagination.children[0].innerHTML = ''; obj.pagination.children[1].innerHTML = ''; // Start pagination if (obj.options.pagination) { // Searchable if (obj.options.search == true && obj.results) { var results = obj.results.length; } else { var results = obj.rows.length; } if (! results) { // No records found obj.pagination.children[0].innerHTML = obj.options.text.noRecordsFound; } else { // Pagination container var quantyOfPages = Math.ceil(results / obj.options.pagination); if (obj.pageNumber < 6) { var startNumber = 1; var finalNumber = quantyOfPages < 10 ? quantyOfPages : 10; } else if (quantyOfPages - obj.pageNumber < 5) { var startNumber = quantyOfPages - 9; var finalNumber = quantyOfPages; } else { var startNumber = obj.pageNumber - 4; var finalNumber = obj.pageNumber + 5; } // First if (startNumber > 1) { var paginationItem = document.createElement('div'); paginationItem.className = 'jexcel_page'; paginationItem.innerHTML = '<'; paginationItem.title = 1; obj.pagination.children[1].appendChild(paginationItem); } // Get page links for (var i = startNumber; i <= finalNumber; i++) { var paginationItem = document.createElement('div'); paginationItem.className = 'jexcel_page'; paginationItem.innerHTML = i; obj.pagination.children[1].appendChild(paginationItem); if (obj.pageNumber == (i-1)) { paginationItem.classList.add('jexcel_page_selected'); } } // Last if (finalNumber < quantyOfPages) { var paginationItem = document.createElement('div'); paginationItem.className = 'jexcel_page'; paginationItem.innerHTML = '>'; paginationItem.title = quantyOfPages; obj.pagination.children[1].appendChild(paginationItem); } // Text var format = function(format) { var args = Array.prototype.slice.call(arguments, 1); return format.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; obj.pagination.children[0].innerHTML = format(obj.options.text.showingPage, obj.pageNumber + 1, quantyOfPages) } } } /** * Download CSV table * * @return null */ obj.download = function(includeHeaders) { if (obj.options.allowExport == false) { console.error('Export not allowed'); } else { // Data var data = ''; if (includeHeaders == true) { data += obj.getHeaders(); } // Get data data += obj.copy(false, ',', true); // Download element var pom = document.createElement('a'); var blob = new Blob([data], {type: 'text/csv;charset=utf-8;'}); var url = URL.createObjectURL(blob); pom.href = url; pom.setAttribute('download', obj.options.csvFileName + '.csv'); document.body.appendChild(pom); pom.click(); pom.remove(); } } /** * Initializes a new history record for undo/redo * * @return null */ obj.setHistory = function(changes) { if (obj.ignoreHistory != true) { // Increment and get the current history index var index = ++obj.historyIndex; // Slice the array to discard undone changes obj.history = (obj.history = obj.history.slice(0, index + 1)); // Keep history obj.history[index] = changes; } } /** * Copy method * * @param bool highlighted - Get only highlighted cells * @param delimiter - \t default to keep compatibility with excel * @return string value */ obj.copy = function(highlighted, delimiter, returnData) { if (! delimiter) { delimiter = "\t"; } // Controls var col = []; var colLabel = []; var row = []; var rowLabel = []; var x = obj.options.data[0].length var y = obj.options.data.length var tmp = ''; // Reset container obj.style = []; // Go through the columns to get the data for (var j = 0; j < y; j++) { col = []; colLabel = []; for (var i = 0; i < x; i++) { // If cell is highlighted if (! highlighted || obj.records[j][i].classList.contains('highlight')) { // Values var value = obj.options.data[j][i]; if (value.match && (value.match(/,/g) || value.match(/\n/) || value.match(/\"/))) { value = value.replace(new RegExp('"', 'g'), '""'); value = '"' + value + '"'; } col.push(value); // Labels var label = obj.records[j][i].innerHTML; if (label.match && (label.match(/,/g) || label.match(/\n/) || label.match(/\"/))) { // Scape double quotes label = label.replace(new RegExp('"', 'g'), '""'); label = '"' + label + '"'; } colLabel.push(label); // Get style tmp = obj.records[j][i].getAttribute('style'); obj.style.push(tmp ? tmp : ''); } } if (col.length) { row.push(col.join(delimiter)); } if (colLabel.length) { rowLabel.push(colLabel.join(delimiter)); } } // Final string var str = row.join("\n"); var strLabel = rowLabel.join("\n"); // Create a hidden textarea to copy the values if (! returnData) { if (obj.options.copyCompatibility == true) { obj.textarea.value = strLabel; } else { obj.textarea.value = str; } obj.textarea.select(); jexcel.copyControls.enabled = false; document.execCommand("copy"); jexcel.copyControls.enabled = true; } // Keep data obj.data = str; // Keep non visible information obj.hashString = obj.hash(obj.textarea.value); // Highlight /*for (var i = 0; i < obj.highlighted.length; i++) { obj.highlighted[i].classList.add('copying'); if (obj.highlighted[i].classList.contains('highlight-top')) { obj.highlighted[i].classList.add('copying-top'); } if (obj.highlighted[i].classList.contains('highlight-right')) { obj.highlighted[i].classList.add('copying-right'); } if (obj.highlighted[i].classList.contains('highlight-bottom')) { obj.highlighted[i].classList.add('copying-bottom'); } if (obj.highlighted[i].classList.contains('highlight-left')) { obj.highlighted[i].classList.add('copying-left'); } }*/ return str; } /** * jExcel paste method * * @param integer row number * @return string value */ obj.paste = function(x, y, data) { // Paste filter if (typeof(obj.options.onbeforepaste) == 'function') { var data = obj.options.onbeforepaste(data); } // Controls var hash = obj.hash(data); var style = (hash == obj.hashString) ? obj.style : null; // Depending on the behavior if (obj.options.copyCompatibility == true && hash == obj.hashString) { var data = obj.data; } // Split new line var data = obj.parseCSV(data, "\t"); if (x != null && y != null && data) { // Records var i = 0; var j = 0; var records = []; var newStyle = {}; var oldStyle = {}; var styleIndex = 0; // Index var colIndex = parseInt(x); var rowIndex = parseInt(y); var row = null; // Go through the columns to get the data while (row = data[j]) { i = 0; var colIndex = parseInt(x); while (row[i] != null) { // Update and keep history var record = obj.updateCell(colIndex, rowIndex, row[i]); // Keep history records.push(record); // Style if (style) { var columnName = jexcel.getColumnNameFromId([colIndex, rowIndex]); newStyle[columnName] = style[styleIndex]; oldStyle[columnName] = obj.getStyle(columnName); obj.records[rowIndex][colIndex].style = style[styleIndex]; styleIndex++ } i++; if (row[i] != null) { if (colIndex >= obj.headers.length - 1) { obj.insertColumn(); } colIndex = obj.right.get(colIndex, rowIndex); } } j++; if (data[j]) { if (rowIndex >= obj.rows.length-1) { obj.insertRow(); } var rowIndex = obj.down.get(x, rowIndex); } } // Select the new cells obj.updateSelectionFromCoords(x, y, colIndex, rowIndex); // Update history obj.setHistory({ action:'setValue', records:records, selection:obj.selectedCell, newStyle:newStyle, oldStyle:oldStyle, }); // Paste event if (typeof(obj.options.onpaste) == 'function') { obj.options.onpaste(el, records); } // Update table obj.updateTable(); } } /** * Process row */ obj.historyProcessRow = function(type, historyRecord) { var rowIndex = (! historyRecord.insertBefore) ? historyRecord.rowNumber + 1 : historyRecord.rowNumber; if (obj.options.search == true) { if (obj.results && obj.results.length != obj.rows.length) { obj.resetSearch(); } } // Remove row if (type == 1) { var numOfRows = historyRecord.numOfRows; // Remove nodes for (var j = rowIndex; j < (numOfRows + rowIndex); j++) { obj.rows[j].remove(); } // Remove references obj.records.splice(rowIndex, numOfRows); obj.options.data.splice(rowIndex, numOfRows); obj.rows.splice(rowIndex, numOfRows); obj.conditionalSelectionUpdate(1, rowIndex, (numOfRows + rowIndex) - 1); } else { // Insert data obj.records = jexcel.injectArray(obj.records, rowIndex, historyRecord.rowRecords); obj.options.data = jexcel.injectArray(obj.options.data, rowIndex, historyRecord.rowData); obj.rows = jexcel.injectArray(obj.rows, rowIndex, historyRecord.rowNode); // Insert nodes var index = 0 for (var j = rowIndex; j < (historyRecord.numOfRows + rowIndex); j++) { obj.tbody.insertBefore(historyRecord.rowNode[index], obj.tbody.children[j]); index++; } } // Respect pagination if (obj.options.pagination > 0) { obj.page(obj.pageNumber); } obj.updateTableReferences(); } /** * Process column */ obj.historyProcessColumn = function(type, historyRecord) { var columnIndex = (! historyRecord.insertBefore) ? historyRecord.columnNumber + 1 : historyRecord.columnNumber; // Remove column if (type == 1) { var numOfColumns = historyRecord.numOfColumns; obj.options.columns.splice(columnIndex, numOfColumns); for (var i = columnIndex; i < (numOfColumns + columnIndex); i++) { obj.headers[i].remove(); obj.colgroup[i].remove(); } obj.headers.splice(columnIndex, numOfColumns); obj.colgroup.splice(columnIndex, numOfColumns); for (var j = 0; j < historyRecord.data.length; j++) { for (var i = columnIndex; i < (numOfColumns + columnIndex); i++) { obj.records[j][i].remove(); } obj.records[j].splice(columnIndex, numOfColumns); obj.options.data[j].splice(columnIndex, numOfColumns); } obj.conditionalSelectionUpdate(0, columnIndex, (numOfColumns + columnIndex) - 1); } else { // Insert data obj.options.columns = jexcel.injectArray(obj.options.columns, columnIndex, historyRecord.columns); obj.headers = jexcel.injectArray(obj.headers, columnIndex, historyRecord.headers); obj.colgroup = jexcel.injectArray(obj.colgroup, columnIndex, historyRecord.colgroup); var index = 0 for (var i = columnIndex; i < (historyRecord.numOfColumns + columnIndex); i++) { obj.headerContainer.insertBefore(historyRecord.headers[index], obj.headerContainer.children[i+1]); obj.colgroupContainer.insertBefore(historyRecord.colgroup[index], obj.colgroupContainer.children[i+1]); index++; } for (var j = 0; j < historyRecord.data.length; j++) { obj.options.data[j] = jexcel.injectArray(obj.options.data[j], columnIndex, historyRecord.data[j]); obj.records[j] = jexcel.injectArray(obj.records[j], columnIndex, historyRecord.records[j]); var index = 0 for (var i = columnIndex; i < (historyRecord.numOfColumns + columnIndex); i++) { obj.rows[j].insertBefore(historyRecord.records[j][index], obj.rows[j].children[i+1]); index++; } } } // Adjust nested headers if (obj.options.nestedHeaders && obj.options.nestedHeaders.length > 0) { // Flexible way to handle nestedheaders if (obj.options.nestedHeaders[0] && obj.options.nestedHeaders[0][0]) { for (var j = 0; j < obj.options.nestedHeaders.length; j++) { if (type == 1) { var colspan = parseInt(obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan) - historyRecord.numOfColumns; } else { var colspan = parseInt(obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan) + historyRecord.numOfColumns; } obj.options.nestedHeaders[j][obj.options.nestedHeaders[j].length-1].colspan = colspan; obj.thead.children[j].children[obj.thead.children[j].children.length-1].setAttribute('colspan', colspan); } } else { if (type == 1) { var colspan = parseInt(obj.options.nestedHeaders[0].colspan) - historyRecord.numOfColumns; } else { var colspan = parseInt(obj.options.nestedHeaders[0].colspan) + historyRecord.numOfColumns; } obj.options.nestedHeaders[0].colspan = colspan; obj.thead.children[0].children[obj.thead.children[0].children.length-1].setAttribute('colspan', colspan); } } obj.updateTableReferences(); } /** * Undo last action */ obj.undo = function() { // Ignore events and history var ignoreEvents = obj.ignoreEvents ? true : false; var ignoreHistory = obj.ignoreHistory ? true : false; obj.ignoreEvents = true; obj.ignoreHistory = true; // Records var records = []; // Update cells if (obj.historyIndex >= 0) { // History var historyRecord = obj.history[obj.historyIndex--]; if (historyRecord.action == 'insertRow') { obj.historyProcessRow(1, historyRecord); } else if (historyRecord.action == 'deleteRow') { obj.historyProcessRow(0, historyRecord); } else if (historyRecord.action == 'insertColumn') { obj.historyProcessColumn(1, historyRecord); } else if (historyRecord.action == 'deleteColumn') { obj.historyProcessColumn(0, historyRecord); } else if (historyRecord.action == 'moveRow') { obj.moveRow(historyRecord.newValue, historyRecord.oldValue); } else if (historyRecord.action == 'moveColumn') { obj.moveColumn(historyRecord.newValue, historyRecord.oldValue); } else if (historyRecord.action == 'setMerge') { obj.removeMerge(historyRecord.column, historyRecord.data); } else if (historyRecord.action == 'setStyle') { obj.setStyle(historyRecord.oldValue, null, null, 1); } else if (historyRecord.action == 'setWidth') { obj.setWidth(historyRecord.column, historyRecord.oldValue); } else if (historyRecord.action == 'setHeight') { obj.setHeight(historyRecord.row, historyRecord.oldValue); } else if (historyRecord.action == 'setHeader') { obj.setHeader(historyRecord.column, historyRecord.oldValue); } else if (historyRecord.action == 'setComments') { obj.setComments(historyRecord.column, historyRecord.oldValue[0], historyRecord.oldValue[1]); } else if (historyRecord.action == 'orderBy') { var rows = []; for (var j = 0; j < historyRecord.rows.length; j++) { rows[historyRecord.rows[j]] = j; } obj.updateOrderArrow(historyRecord.column, historyRecord.order ? 0 : 1); obj.updateOrder(rows); } else if (historyRecord.action == 'setValue') { // Redo for changes in cells for (var i = 0; i < historyRecord.records.length; i++) { obj.updateCell(historyRecord.records[i].col, historyRecord.records[i].row, historyRecord.records[i].oldValue); obj.updateFormulaChain(historyRecord.records[i].col, historyRecord.records[i].row, records); if (historyRecord.oldStyle) { obj.resetStyle(historyRecord.oldStyle, true); } } // Update selection if (! historyRecord.selection) { historyRecord.selection = [historyRecord.records[0].col, historyRecord.records[0].row]; } obj.updateSelectionFromCoords(historyRecord.selection[0], historyRecord.selection[1], historyRecord.selection[2], historyRecord.selection[3]); // Update table obj.updateTable(); } } obj.ignoreEvents = ignoreEvents; obj.ignoreHistory = ignoreHistory; } /** * Redo previously undone action */ obj.redo = function() { // Ignore events and history var ignoreEvents = obj.ignoreEvents ? true : false; var ignoreHistory = obj.ignoreHistory ? true : false; obj.ignoreEvents = true; obj.ignoreHistory = true; // Records var records = []; // Update cells if (obj.historyIndex < obj.history.length - 1) { // History var historyRecord = obj.history[++obj.historyIndex]; if (historyRecord.action == 'insertRow') { obj.historyProcessRow(0, historyRecord); } else if (historyRecord.action == 'deleteRow') { obj.historyProcessRow(1, historyRecord); } else if (historyRecord.action == 'insertColumn') { obj.historyProcessColumn(0, historyRecord); } else if (historyRecord.action == 'deleteColumn') { obj.historyProcessColumn(1, historyRecord); } else if (historyRecord.action == 'moveRow') { obj.moveRow(historyRecord.oldValue, historyRecord.newValue); } else if (historyRecord.action == 'moveColumn') { obj.moveColumn(historyRecord.oldValue, historyRecord.newValue); } else if (historyRecord.action == 'setMerge') { obj.setMerge(historyRecord.column, historyRecord.colspan, historyRecord.rowspan, 1); } else if (historyRecord.action == 'setStyle') { obj.setStyle(historyRecord.newValue, null, null, 1); } else if (historyRecord.action == 'setWidth') { obj.setWidth(historyRecord.column, historyRecord.newValue); } else if (historyRecord.action == 'setHeight') { obj.setHeight(historyRecord.row, historyRecord.newValue); } else if (historyRecord.action == 'setHeader') { obj.setHeader(historyRecord.column, historyRecord.newValue); } else if (historyRecord.action == 'setComments') { obj.setComments(historyRecord.column, historyRecord.newValue[0], historyRecord.newValue[1]); } else if (historyRecord.action == 'orderBy') { obj.updateOrderArrow(historyRecord.column, historyRecord.order); obj.updateOrder(historyRecord.rows); } else if (historyRecord.action == 'setValue') { // Redo for changes in cells for (var i = 0; i < historyRecord.records.length; i++) { obj.updateCell(historyRecord.records[i].col, historyRecord.records[i].row, historyRecord.records[i].newValue); obj.updateFormulaChain(historyRecord.records[i].col, historyRecord.records[i].row, records); if (historyRecord.newStyle) { obj.resetStyle(historyRecord.newStyle, true); } } // Update selection if (! historyRecord.selection) { historyRecord.selection = [historyRecord.records[0].col, historyRecord.records[0].row]; } obj.updateSelectionFromCoords(historyRecord.selection[0], historyRecord.selection[1], historyRecord.selection[2], historyRecord.selection[3]); // Update table obj.updateTable(); } } obj.ignoreEvents = ignoreEvents; obj.ignoreHistory = ignoreHistory; } /** * Get dropdown value from key */ obj.getDropDownValue = function(column, key) { var value = []; if (obj.options.columns[column] && obj.options.columns[column].source) { // Create array from source var combo = []; var source = obj.options.columns[column].source; for (var i = 0; i < source.length; i++) { if (typeof(source[i]) == 'object') { combo[source[i].id] = source[i].name; } else { combo[source[i]] = source[i]; } } // Garante single multiple compatibily var keys = ('' + key).split(';') for (var i = 0; i < keys.length; i++) { if (combo[keys[i]]) { value.push(combo[keys[i]]); } } } else { console.error('Invalid column'); } return (value.length > 0) ? value.join('; ') : ''; } /** * From starckoverflow contributions */ obj.parseCSV = function(str, delimiter) { // Remove last line break str = str.replace(/\r?\n$|\r$|\n$/g, ""); // Last caracter is the delimiter if (str.charCodeAt(str.length-1) == 9) { str += "\0"; } // user-supplied delimeter or default comma delimiter = (delimiter || ","); var arr = []; var quote = false; // true means we're inside a quoted field // iterate over each character, keep track of current row and column (of the returned array) for (var row = 0, col = 0, c = 0; c < str.length; c++) { var cc = str[c], nc = str[c+1]; arr[row] = arr[row] || []; arr[row][col] = arr[row][col] || ''; // If the current character is a quotation mark, and we're inside a quoted field, and the next character is also a quotation mark, add a quotation mark to the current column and skip the next character if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; } // If it's just one quotation mark, begin/end quoted field if (cc == '"') { quote = !quote; continue; } // If it's a comma and we're not in a quoted field, move on to the next column if (cc == delimiter && !quote) { ++col; continue; } // If it's a newline (CRLF) and we're not in a quoted field, skip the next character and move on to the next row and move to column 0 of that new row if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; } // If it's a newline (LF or CR) and we're not in a quoted field, move on to the next row and move to column 0 of that new row if (cc == '\n' && !quote) { ++row; col = 0; continue; } if (cc == '\r' && !quote) { ++row; col = 0; continue; } // Otherwise, append the current character to the current column arr[row][col] += cc; } return arr; } obj.hash = function(str) { var output = ''; for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 30 && str.charCodeAt(i) <= 127) { output += str.charAt(i); } } return output.split('').reduce((prevHash, currVal) => ((prevHash << 5) - prevHash) + currVal.charCodeAt(0), 0); } /** * Initialization method */ obj.init = function() { jexcel.current = obj; // Build handlers if (typeof(jexcel.build) == 'function') { jexcel.build(); jexcel.build = null; } // Loading if (obj.options.loadingSpin == true) { jSuites.loading.show(); } // Load the table data based on an CSV file if (obj.options.csv) { // Load CSV file fetch(obj.options.csv) .then(function(data) { data.text().then(function(data) { // Convert data var data = obj.parseCSV(data, obj.options.csvDelimiter) // Headers if (obj.options.csvHeaders == true && data.length > 0) { var headers = data.shift(); for(var i = 0; i < headers.length; i++) { if (! obj.options.columns[i]) { obj.options.columns[i] = { type:'text', align:'center', width:obj.options.defaultColWidth }; } // Precedence over pre-configurated titles if (typeof obj.options.columns[i].title === 'undefined') { obj.options.columns[i].title = headers[i]; } } } // Data obj.options.data = data; // Prepare table obj.prepareTable(); // Hide spin if (obj.options.loadingSpin == true) { jSuites.loading.hide(); } }); }); } else if (obj.options.url) { fetch(obj.options.url, { headers: new Headers({ 'content-type': 'text/json' }) }) .then(function(data) { data.json().then(function(result) { // Data obj.options.data = (result.data) ? result.data : result; // Prepare table obj.prepareTable(); // Hide spin if (obj.options.loadingSpin == true) { jSuites.loading.hide(); } }); }); } else { // Prepare table obj.prepareTable(); } } // Context menu if (options && options.contextMenu != null) { obj.options.contextMenu = options.contextMenu; } else { obj.options.contextMenu = function(el, x, y, e) { var items = []; if (y == null) { // Insert a new column if (obj.options.allowInsertColumn == true) { items.push({ title:obj.options.text.insertANewColumnBefore, onclick:function() { obj.insertColumn(1, parseInt(x), 1); } }); } if (obj.options.allowInsertColumn == true) { items.push({ title:obj.options.text.insertANewColumnAfter, onclick:function() { obj.insertColumn(1, parseInt(x), 0); } }); } // Delete a column if (obj.options.allowDeleteColumn == true) { items.push({ title:obj.options.text.deleteSelectedColumns, onclick:function() { obj.deleteColumn(); } }); } // Rename column if (obj.options.allowRenameColumn == true) { items.push({ title:obj.options.text.renameThisColumn, onclick:function() { obj.setHeader(x); } }); } // Line items.push({ type:'line' }); // Sorting if (obj.options.columnSorting == true) { items.push({ title:obj.options.text.orderAscending, onclick:function() { obj.orderBy(x, 0); } }); items.push({ title:obj.options.text.orderDescending, onclick:function() { obj.orderBy(x, 1); } }); } } else { // Insert new row if (obj.options.allowInsertRow == true) { items.push({ title:obj.options.text.insertANewRowBefore, onclick:function() { obj.insertRow(1, parseInt(y), 1); } }); items.push({ title:obj.options.text.insertANewRowAfter, onclick:function() { obj.insertRow(1, parseInt(y)); } }); } if (obj.options.allowDeleteRow == true) { items.push({ title:obj.options.text.deleteSelectedRows, onclick:function() { obj.deleteRow(); } }); } if (x) { if (obj.options.allowComments == true) { items.push({ type:'line' }); var title = obj.records[y][x].getAttribute('title') || ''; items.push({ title: title ? obj.options.text.editComments : obj.options.text.addComments, onclick:function() { obj.setComments([ x, y ], prompt(obj.options.text.comments, title)); } }); if (title) { items.push({ title:obj.options.text.clearComments, onclick:function() { obj.setComments([ x, y ], ''); } }); } } } } // Line items.push({ type:'line' }); // Copy items.push({ title:obj.options.text.copy, shortcut:'Ctrl + C', onclick:function() { obj.copy(true); } }); // Paste if (navigator && navigator.clipboard) { items.push({ title:obj.options.text.paste, shortcut:'Ctrl + V', onclick:function() { if (obj.selectedCell) { navigator.clipboard.readText().then(function(text) { if (text) { jexcel.current.paste(obj.selectedCell[0], obj.selectedCell[1], text); } }); } } }); } // Save items.push({ title:obj.options.text.saveAs, shortcut:'Ctrl + S', onclick:function() { obj.download(true); } }); // About if (obj.options.about) { items.push({ title:obj.options.text.about, onclick:function() { alert(obj.options.about); } }); } return items; } } obj.scrollControls = function(e) { if (obj.options.lazyLoading == true) { if (jexcel.timeControlLoading == null) { jexcel.timeControlLoading = setTimeout(function() { if (obj.content.scrollTop + obj.content.clientHeight >= obj.content.scrollHeight) { if (obj.loadDown()) { if (obj.content.scrollTop + obj.content.clientHeight > obj.content.scrollHeight - 10) { obj.content.scrollTop = obj.content.scrollTop - obj.content.clientHeight; } obj.updateCornerPosition(); } } else if (obj.content.scrollTop <= obj.content.clientHeight) { if (obj.loadUp()) { if (obj.content.scrollTop < 10) { obj.content.scrollTop = obj.content.scrollTop + obj.content.clientHeight; } obj.updateCornerPosition(); } } jexcel.timeControlLoading = null; }, 100); } } // Close editor if (obj.options.lazyLoading == true || obj.options.tableOverflow == true) { if (obj.edition && e.target.className.substr(0,9) != 'jdropdown') { obj.closeEditor(obj.edition[0], true); } } } el.addEventListener("scroll", obj.scrollControls); el.addEventListener("mousewheel", obj.scrollControls); obj.init(); el.jexcel = obj; return obj; }); jexcel.current = null; jexcel.timeControl = null; jexcel.timeControlLoading= null; jexcel.destroy = function(element, destroyEventHandlers) { if (element.jexcel) { element.jexcel = null; element.innerHTML = ''; if (destroyEventHandlers) { document.removeEventListener("keydown", jexcel.keyDownControls); document.removeEventListener("mouseup", jexcel.mouseUpControls); document.removeEventListener("mousedown", jexcel.mouseDownControls); document.removeEventListener("mousemove", jexcel.mouseMoveControls); document.removeEventListener("mouseover", jexcel.mouseOverControls); document.removeEventListener("dblclick", jexcel.doubleClickControls); document.removeEventListener("copy", jexcel.copyControls); document.removeEventListener("cut", jexcel.cutControls); document.removeEventListener("paste", jexcel.pasteControls); document.removeEventListener("contextmenu", jexcel.contextMenuControls); document.removeEventListener("touchstart", jexcel.touchStartControls); document.removeEventListener("touchend", jexcel.touchEndControls); document.removeEventListener("touchcancel", jexcel.touchEndControls); jexcel = null; } } } jexcel.build = function() { document.addEventListener("keydown", jexcel.keyDownControls); document.addEventListener("mouseup", jexcel.mouseUpControls); document.addEventListener("mousedown", jexcel.mouseDownControls); document.addEventListener("mousemove", jexcel.mouseMoveControls); document.addEventListener("mouseover", jexcel.mouseOverControls); document.addEventListener("dblclick", jexcel.doubleClickControls); document.addEventListener("copy", jexcel.copyControls); document.addEventListener("cut", jexcel.cutControls); document.addEventListener("paste", jexcel.pasteControls); document.addEventListener("contextmenu", jexcel.contextMenuControls); document.addEventListener("touchstart", jexcel.touchStartControls); document.addEventListener("touchend", jexcel.touchEndControls); document.addEventListener("touchcancel", jexcel.touchEndControls); document.addEventListener("touchmove", jexcel.touchEndControls); } /** * Helper injectArray */ jexcel.injectArray = function(o, idx, arr) { return o.slice(0, idx).concat(arr).concat(o.slice(idx)); } /** * Get letter based on a number * * @param integer i * @return string letter */ jexcel.getColumnName = function(i) { var letter = ''; if (i > 701) { letter += String.fromCharCode(64 + parseInt(i / 676)); letter += String.fromCharCode(64 + parseInt((i % 676) / 26)); } else if (i > 25) { letter += String.fromCharCode(64 + parseInt(i / 26)); } letter += String.fromCharCode(65 + (i % 26)); return letter; } /** * Convert excel like column to jexcel id * * @param string id * @return string id */ jexcel.getIdFromColumnName = function (id, arr) { // Get the letters var t = /^[a-zA-Z]+/.exec(id); if (t) { // Base 26 calculation var code = 0; for (var i = 0; i < t[0].length; i++) { code += parseInt(t[0].charCodeAt(i) - 64) * Math.pow(26, (t[0].length - 1 - i)); } code--; // Make sure jexcel starts on zero if (code < 0) { code = 0; } // Number var number = parseInt(/[0-9]+$/.exec(id)); if (number > 0) { number--; } if (arr == true) { id = [ code, number ]; } else { id = code + '-' + number; } } return id; } /** * Convert jexcel id to excel like column name * * @param string id * @return string id */ jexcel.getColumnNameFromId = function (cellId) { if (! Array.isArray(cellId)) { cellId = cellId.split('-'); } return jexcel.getColumnName(parseInt(cellId[0])) + (parseInt(cellId[1]) + 1); } /** * Inside jexcel table * * @param string id * @return string id */ jexcel.getElement = function(element) { var jexcelSection = 0; var jexcelElement = 0; function path (element) { if (element.className) { if (element.classList.contains('jexcel_container')) { jexcelElement = element; } } if (element.tagName == 'THEAD') { jexcelSection = 1; } else if (element.tagName == 'TBODY') { jexcelSection = 2; } if (element.parentNode) { path(element.parentNode); } } path(element); return [ jexcelElement, jexcelSection ]; } /** * Events */ jexcel.keyDownControls = function(e) { if (jexcel.current) { if (jexcel.current.edition) { if (e.which == 27) { // Escape if (jexcel.current.edition) { // Exit without saving jexcel.current.closeEditor(jexcel.current.edition[0], false); } e.preventDefault(); } else if (e.which == 13) { // Enter if (jexcel.current.options.columns[jexcel.current.edition[2]].type == 'calendar') { jexcel.current.editor[0].children[0].calendar.close(1); } else if (jexcel.current.options.columns[jexcel.current.edition[2]].type == 'dropdown' || jexcel.current.options.columns[jexcel.current.edition[2]].type == 'autocomplete') { // Do nothing } else { // Alt enter -> do not close editor if ((jexcel.current.options.wordWrap == true || jexcel.current.options.columns[jexcel.current.edition[2]].wordWrap == true || jexcel.current.options.data[jexcel.current.edition[3]][jexcel.current.edition[2]].length > 200) && e.altKey) { // Add new line to the editor var editorTextarea = jexcel.current.edition[0].children[0]; var editorValue = jexcel.current.edition[0].children[0].value; var editorIndexOf = editorTextarea.selectionStart; editorValue = editorValue.slice(0, editorIndexOf) + "\n" + editorValue.slice(editorIndexOf); editorTextarea.value = editorValue; editorTextarea.focus(); editorTextarea.selectionStart = editorIndexOf + 1; editorTextarea.selectionEnd = editorIndexOf + 1; } else { jexcel.current.edition[0].children[0].blur(); } } } else if (e.which == 9) { // Tab if (jexcel.current.options.columns[jexcel.current.edition[2]].type == 'calendar') { jexcel.current.edition[0].children[0].calendar.close(1); } else { jexcel.current.edition[0].children[0].blur(); } } } if (! jexcel.current.edition && jexcel.current.selectedCell) { // Which key if (e.which == 37) { jexcel.current.left(e.shiftKey, e.ctrlKey); e.preventDefault(); } else if (e.which == 39) { jexcel.current.right(e.shiftKey, e.ctrlKey); e.preventDefault(); } else if (e.which == 38) { jexcel.current.up(e.shiftKey, e.ctrlKey); e.preventDefault(); } else if (e.which == 40) { jexcel.current.down(e.shiftKey, e.ctrlKey); e.preventDefault(); } else if (e.which == 36) { jexcel.current.first(e.shiftKey, e.ctrlKey); e.preventDefault(); } else if (e.which == 35) { jexcel.current.last(e.shiftKey, e.ctrlKey); e.preventDefault(); } else if (e.which == 32) { if (jexcel.current.options.editable == true) { jexcel.current.setCheckRadioValue(); } e.preventDefault(); } else if (e.which == 46) { // Delete if (jexcel.current.options.editable == true) { if (jexcel.current.selectedRow) { if (jexcel.current.options.allowDeleteRow == true) { if (confirm(jexcel.current.options.text.areYouSureToDeleteTheSelectedRows)) { jexcel.current.deleteRow(); } } } else if (jexcel.current.selectedHeader) { if (jexcel.current.options.allowDeleteColumn == true) { if (confirm(jexcel.current.options.text.areYouSureToDeleteTheSelectedColumns)) { jexcel.current.deleteColumn(); } } } else { // Change value jexcel.current.setValue(jexcel.current.highlighted, ''); } } } else if (e.which == 13) { // Move cursor if (e.shiftKey) { jexcel.current.up(); } else { if (jexcel.current.options.allowInsertRow == true) { if (jexcel.current.options.allowManualInsertRow == true) { if (jexcel.current.selectedCell[1] == jexcel.current.options.data.length - 1) { // New record in case selectedCell in the last row jexcel.current.insertRow(); } } } jexcel.current.down(); } e.preventDefault(); } else if (e.which == 9) { // Tab if (e.shiftKey) { jexcel.current.left(); } else { if (jexcel.current.options.allowInsertColumn == true) { if (jexcel.current.options.allowManualInsertColumn == true) { if (jexcel.current.selectedCell[0] == jexcel.current.options.data[0].length - 1) { // New record in case selectedCell in the last column jexcel.current.insertColumn(); } } } jexcel.current.right(); } e.preventDefault(); } else { if (! e.shiftKey) { if (e.ctrlKey || e.metaKey) { if (e.which == 65) { // Ctrl + A jexcel.current.selectAll(); e.preventDefault(); } else if (e.which == 83) { // Ctrl + S jexcel.current.download(); e.preventDefault(); } else if (e.which == 89) { // Ctrl + Y jexcel.current.redo(); e.preventDefault(); } else if (e.which == 90) { // Ctrl + Z jexcel.current.undo(); e.preventDefault(); } } else { if (jexcel.current.selectedCell) { if (jexcel.current.options.editable == true) { var rowId = jexcel.current.selectedCell[1]; var columnId = jexcel.current.selectedCell[0]; // If is not readonly if (jexcel.current.options.columns[columnId].type != 'readonly') { // Characters able to start a edition if (e.keyCode == 32) { // Space if (jexcel.current.options.columns[columnId].type == 'checkbox' || jexcel.current.options.columns[columnId].type == 'radio') { e.preventDefault(); } else { // Start edition jexcel.current.openEditor(jexcel.current.records[rowId][columnId], true); } } else if ((e.keyCode == 8) || (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode >= 96 && e.keyCode <= 122) || (e.keyCode >= 187 && e.keyCode <= 190)) { // Start edition jexcel.current.openEditor(jexcel.current.records[rowId][columnId], true); // Prevent entries in the calendar if (jexcel.current.options.columns[columnId].type == 'calendar') { e.preventDefault(); } } else if (e.keyCode == 113) { // Start edition with current content F2 jexcel.current.openEditor(jexcel.current.records[rowId][columnId], false); } } } } } } } } else { if (e.target.classList.contains('jexcel_search')) { if (jexcel.timeControl) { clearTimeout(jexcel.timeControl); } jexcel.timeControl = setTimeout(function() { jexcel.current.search(e.target.value); }, 200); } } } } jexcel.isMouseAction = false; jexcel.mouseDownControls = function(e) { e = e || window.event; if ("buttons" in e) { var mouseButton = e.buttons; } else { var mouseButton = e.which || e.button; } // Get elements var jexcelTable = jexcel.getElement(e.target); if (jexcelTable[0]) { if (jexcel.current != jexcelTable[0].jexcel) { if (jexcel.current) { jexcel.current.resetSelection(); } jexcel.current = jexcelTable[0].jexcel; } } else { if (jexcel.current) { jexcel.current.resetSelection(true); jexcel.current = null; } } if (jexcel.current && mouseButton == 1) { if (e.target.classList.contains('jexcel_selectall')) { if (jexcel.current) { jexcel.current.selectAll(); } } else if (e.target.classList.contains('jexcel_corner')) { if (jexcel.current.options.editable == true) { jexcel.current.selectedCorner = true; } } else { // Header found if (jexcelTable[1] == 1) { var columnId = e.target.getAttribute('data-x'); if (columnId) { // Update cursor var info = e.target.getBoundingClientRect(); if (jexcel.current.options.columnResize == true && info.width - e.offsetX < 6) { // Resize helper jexcel.current.resizing = { mousePosition: e.pageX, column: columnId, width: info.width, }; // Border indication jexcel.current.headers[columnId].classList.add('resizing'); for (var j = 0; j < jexcel.current.records.length; j++) { jexcel.current.records[j][columnId].classList.add('resizing'); } } else if (jexcel.current.options.columnDrag == true && info.height - e.offsetY < 6) { if (jexcel.current.isColMerged(columnId).length) { console.error('JEXCEL: This column is part of a merged cell.'); } else { // Reset selection jexcel.current.resetSelection(); // Drag helper jexcel.current.dragging = { element: e.target, column:columnId, destination:columnId, }; // Border indication jexcel.current.headers[columnId].classList.add('dragging'); for (var j = 0; j < jexcel.current.records.length; j++) { jexcel.current.records[j][columnId].classList.add('dragging'); } } } else { if (jexcel.current.selectedHeader && (e.shiftKey || e.ctrlKey)) { var o = jexcel.current.selectedHeader; var d = columnId; } else { // Press to rename if (jexcel.current.selectedHeader == columnId && jexcel.current.options.allowRenameColumn == true) { jexcel.timeControl = setTimeout(function() { jexcel.current.setHeader(columnId); }, 800); } // Keep track of which header was selected first jexcel.current.selectedHeader = columnId; // Update selection single column var o = columnId; var d = columnId; } // Update selection jexcel.current.updateSelectionFromCoords(o, 0, d, jexcel.current.options.data.length - 1); } } else { if (e.target.parentNode.classList.contains('jexcel_nested')) { var column = e.target.getAttribute('data-column').split(','); var c1 = parseInt(column[0]); var c2 = parseInt(column[column.length-1]); jexcel.current.updateSelectionFromCoords(c1, 0, c2, jexcel.current.options.data.length - 1); } } } else { jexcel.current.selectedHeader = false; } // Body found if (jexcelTable[1] == 2) { var rowId = e.target.getAttribute('data-y'); if (e.target.classList.contains('jexcel_row')) { var info = e.target.getBoundingClientRect(); if (jexcel.current.options.rowResize == true && info.height - e.offsetY < 6) { // Resize helper jexcel.current.resizing = { element: e.target.parentNode, mousePosition: e.pageY, row: rowId, height: info.height, }; // Border indication e.target.parentNode.classList.add('resizing'); } else if (jexcel.current.options.rowDrag == true && info.width - e.offsetX < 6) { if (jexcel.current.isRowMerged(rowId).length) { console.error('JEXCEL: This row is part of a merged cell'); } else if (jexcel.current.options.search == true && jexcel.current.results) { console.error('JEXCEL: Please clear your search before perform this action'); } else { // Reset selection jexcel.current.resetSelection(); // Drag helper jexcel.current.dragging = { element: e.target.parentNode, row:rowId, destination:rowId, }; // Border indication e.target.parentNode.classList.add('dragging'); } } else { if (jexcel.current.selectedRow && (e.shiftKey || e.ctrlKey)) { var o = jexcel.current.selectedRow; var d = rowId; } else { // Keep track of which header was selected first jexcel.current.selectedRow = rowId; // Update selection single column var o = rowId; var d = rowId; } // Update selection jexcel.current.updateSelectionFromCoords(0, o, jexcel.current.options.data[0].length - 1, d); } } else { // Jclose if (e.target.classList.contains('jclose') && e.target.clientWidth - e.offsetX < 50 && e.offsetY < 50) { jexcel.current.closeEditor(jexcel.current.edition[0], true); } else { var getCellCoords = function(element) { var x = element.getAttribute('data-x'); var y = element.getAttribute('data-y'); if (x && y) { return [x, y]; } else { if (element.parentNode) { return getCellCoords(element.parentNode); } } }; var position = getCellCoords(e.target); if (position) { var columnId = position[0]; var rowId = position[1]; // Close edition if (jexcel.current.edition) { if (jexcel.current.edition[2] != columnId || jexcel.current.edition[3] != rowId) { jexcel.current.closeEditor(jexcel.current.edition[0], true); } } if (! jexcel.current.edition) { // Update cell selection if (e.shiftKey) { jexcel.current.updateSelectionFromCoords(jexcel.current.selectedCell[0], jexcel.current.selectedCell[1], columnId, rowId); } else { jexcel.current.updateSelectionFromCoords(columnId, rowId); } } // No full row selected jexcel.current.selectedHeader = null; jexcel.current.selectedRow = null; } } } } else { jexcel.current.selectedRow = false; } // Pagination if (e.target.classList.contains('jexcel_page')) { if (e.target.innerText == '<') { jexcel.current.page(0); } else if (e.target.innerText == '>') { jexcel.current.page(e.target.getAttribute('title') - 1); } else { jexcel.current.page(e.target.innerText - 1); } } } if (jexcel.current.edition) { jexcel.isMouseAction = false; } else { jexcel.isMouseAction = true; } } else { jexcel.isMouseAction = false; } } jexcel.mouseUpControls = function(e) { if (jexcel.current) { // Update cell size if (jexcel.current.resizing) { // Columns to be updated if (jexcel.current.resizing.column) { // Remove Class jexcel.current.headers[jexcel.current.resizing.column].classList.remove('resizing'); var newWidth = jexcel.current.colgroup[jexcel.current.resizing.column].getAttribute('width'); jexcel.current.setWidth(jexcel.current.resizing.column, newWidth, jexcel.current.resizing.width); // Remove border jexcel.current.headers[jexcel.current.resizing.column].classList.remove('resizing'); for (var j = 0; j < jexcel.current.records.length; j++) { jexcel.current.records[j][jexcel.current.resizing.column].classList.remove('resizing'); } } else { // Remove Class jexcel.current.rows[jexcel.current.resizing.row].children[0].classList.remove('resizing'); var newHeight = jexcel.current.rows[jexcel.current.resizing.row].getAttribute('height'); jexcel.current.setHeight(jexcel.current.resizing.row, newHeight, jexcel.current.resizing.height); // Remove border jexcel.current.resizing.element.classList.remove('resizing'); } // Reset resizing helper jexcel.current.resizing = null; } else if (jexcel.current.dragging) { // Reset dragging helper if (jexcel.current.dragging) { if (jexcel.current.dragging.column) { // Target var columnId = e.target.getAttribute('data-x'); // Remove move style jexcel.current.headers[jexcel.current.dragging.column].classList.remove('dragging'); for (var j = 0; j < jexcel.current.rows.length; j++) { jexcel.current.records[j][jexcel.current.dragging.column].classList.remove('dragging'); } for (var i = 0; i < jexcel.current.headers.length; i++) { jexcel.current.headers[i].classList.remove('dragging-left'); jexcel.current.headers[i].classList.remove('dragging-right'); } // Update position if (columnId) { if (jexcel.current.dragging.column != jexcel.current.dragging.destination) { jexcel.current.moveColumn(jexcel.current.dragging.column, jexcel.current.dragging.destination); } } } else { var position = Array.prototype.indexOf.call(jexcel.current.dragging.element.parentNode.children, jexcel.current.dragging.element); if (jexcel.current.dragging.row != position) { jexcel.current.moveRow(jexcel.current.dragging.row, position, true); } jexcel.current.dragging.element.classList.remove('dragging'); } jexcel.current.dragging = null; } } else { // Close any corner selection if (jexcel.current.selectedCorner) { jexcel.current.selectedCorner = false; // Data to be copied if (jexcel.current.selection.length > 0) { // Copy data jexcel.current.copyData(jexcel.current.selection[0], jexcel.current.selection[jexcel.current.selection.length - 1]); // Remove selection jexcel.current.removeCopySelection(); } } } } // Clear any time control if (jexcel.timeControl) { clearTimeout(jexcel.timeControl); jexcel.timeControl = null; } // Mouse up jexcel.isMouseAction = false; } // Mouse move controls jexcel.mouseMoveControls = function(e) { e = e || window.event; if ("buttons" in e) { var mouseButton = e.buttons; } else { var mouseButton = e.which || e.button; } if (! mouseButton) { jexcel.isMouseAction = false; } if (jexcel.current && jexcel.isMouseAction == true) { // Resizing is ongoing if (jexcel.current.resizing) { if (jexcel.current.resizing.column) { var width = e.pageX - jexcel.current.resizing.mousePosition; if (jexcel.current.resizing.width + width > 0) { var tempWidth = jexcel.current.resizing.width + width; jexcel.current.colgroup[jexcel.current.resizing.column].setAttribute('width', tempWidth); jexcel.current.updateCornerPosition(); } } else { var height = e.pageY - jexcel.current.resizing.mousePosition; if (jexcel.current.resizing.height + height > 0) { var tempHeight = jexcel.current.resizing.height + height; jexcel.current.rows[jexcel.current.resizing.row].setAttribute('height', tempHeight); jexcel.current.updateCornerPosition(); } } } } } jexcel.mouseOverControls = function(e) { e = e || window.event; if ("buttons" in e) { var mouseButton = e.buttons; } else { var mouseButton = e.which || e.button; } if (! mouseButton) { jexcel.isMouseAction = false; } if (jexcel.current && jexcel.isMouseAction == true) { // Get elements var jexcelTable = jexcel.getElement(e.target); if (jexcelTable[0]) { // Avoid cross reference if (jexcel.current != jexcelTable[0].jexcel) { if (jexcel.current) { return false; } } var columnId = e.target.getAttribute('data-x'); var rowId = e.target.getAttribute('data-y'); if (jexcel.current.dragging) { if (jexcel.current.dragging.column) { if (columnId) { if (jexcel.current.isColMerged(columnId).length) { console.error('JEXCEL: This column is part of a merged cell.'); } else { for (var i = 0; i < jexcel.current.headers.length; i++) { jexcel.current.headers[i].classList.remove('dragging-left'); jexcel.current.headers[i].classList.remove('dragging-right'); } if (jexcel.current.dragging.column == columnId) { jexcel.current.dragging.destination = parseInt(columnId); } else { if (e.target.clientWidth / 2 > e.offsetX) { if (jexcel.current.dragging.column < columnId) { jexcel.current.dragging.destination = parseInt(columnId) - 1; } else { jexcel.current.dragging.destination = parseInt(columnId); } jexcel.current.headers[columnId].classList.add('dragging-left'); } else { if (jexcel.current.dragging.column < columnId) { jexcel.current.dragging.destination = parseInt(columnId); } else { jexcel.current.dragging.destination = parseInt(columnId) + 1; } jexcel.current.headers[columnId].classList.add('dragging-right'); } } } } } else { if (rowId) { if (jexcel.current.isRowMerged(rowId).length) { console.error('JEXCEL: This row is part of a merged cell.'); } else { var target = (e.target.clientHeight / 2 > e.offsetY) ? e.target.parentNode.nextSibling : e.target.parentNode; e.target.parentNode.parentNode.insertBefore(jexcel.current.dragging.element, target); } } } } else if (jexcel.current.resizing) { } else { // Header found if (jexcelTable[1] == 1) { if (jexcel.current.selectedHeader) { var columnId = e.target.getAttribute('data-x'); var o = jexcel.current.selectedHeader; var d = columnId; // Update selection jexcel.current.updateSelectionFromCoords(o, 0, d, jexcel.current.options.data.length - 1); } } // Body found if (jexcelTable[1] == 2) { if (e.target.classList.contains('jexcel_row')) { if (jexcel.current.selectedRow) { var o = jexcel.current.selectedRow; var d = rowId; // Update selection jexcel.current.updateSelectionFromCoords(0, o, jexcel.current.options.data[0].length - 1, d); } } else { // Do not select edtion is in progress if (! jexcel.current.edition) { if (columnId && rowId) { if (jexcel.current.selectedCorner) { jexcel.current.updateCopySelection(columnId, rowId); } else { if (jexcel.current.selectedCell) { jexcel.current.updateSelectionFromCoords(jexcel.current.selectedCell[0], jexcel.current.selectedCell[1], columnId, rowId); } } } } } } } } } // Clear any time control if (jexcel.timeControl) { clearTimeout(jexcel.timeControl); jexcel.timeControl = null; } } /** * Double click event handler: controls the double click in the corner, cell edition or column re-ordering. */ jexcel.doubleClickControls = function(e) { // Jexcel is selected if (jexcel.current) { // Corner action if (e.target.classList.contains('jexcel_corner')) { // Any selected cells if (jexcel.current.highlighted.length > 0) { // Copy from this var x1 = jexcel.current.highlighted[0].getAttribute('data-x'); var y1 = parseInt(jexcel.current.highlighted[jexcel.current.highlighted.length - 1].getAttribute('data-y')) + 1; // Until this var x2 = jexcel.current.highlighted[jexcel.current.highlighted.length - 1].getAttribute('data-x'); var y2 = jexcel.current.records.length - 1 // Execute copy jexcel.current.copyData(jexcel.current.records[y1][x1], jexcel.current.records[y2][x2]); } } else { // Get table var jexcelTable = jexcel.getElement(e.target); // Double click over header if (jexcelTable[1] == 1 && jexcel.current.options.columnSorting == true) { // Check valid column header coords var columnId = e.target.getAttribute('data-x'); if (columnId) { jexcel.current.orderBy(columnId); } } // Double click over body if (jexcelTable[1] == 2 && jexcel.current.options.editable == true) { if (! jexcel.current.edition) { var getCellCoords = function(element) { if (element.parentNode) { var x = element.getAttribute('data-x'); var y = element.getAttribute('data-y'); if (x && y) { return element; } else { return getCellCoords(element.parentNode); } } } var cell = getCellCoords(e.target); if (cell && cell.classList.contains('highlight')) { jexcel.current.openEditor(cell); } } } } } } jexcel.copyControls = function(e) { if (jexcel.current && jexcel.copyControls.enabled) { if (! jexcel.current.edition) { jexcel.current.copy(true); } } } jexcel.cutControls = function(e) { if (jexcel.current) { if (! jexcel.current.edition) { jexcel.current.copy(true); if (jexcel.current.options.editable == true) { jexcel.current.setValue(jexcel.current.highlighted, ''); } } } } jexcel.pasteControls = function(e) { if (jexcel.current && jexcel.current.selectedCell) { if (! jexcel.current.edition) { if (e.clipboardData) { if (jexcel.current.options.editable == true) { jexcel.current.paste(jexcel.current.selectedCell[0], jexcel.current.selectedCell[1], e.clipboardData.getData('text')); } e.preventDefault(); } } } } jexcel.contextMenuControls = function(e) { e = e || window.event; if ("buttons" in e) { var mouseButton = e.buttons; } else { var mouseButton = e.which || e.button; } if (jexcel.current) { if (jexcel.current.edition) { e.preventDefault(); } else if (jexcel.current.options.contextMenu) { jexcel.current.contextMenu.contextmenu.close(); if (jexcel.current) { var x = e.target.getAttribute('data-x'); var y = e.target.getAttribute('data-y'); if (x || y) { // Table found var items = jexcel.current.options.contextMenu(jexcel.current, x, y, e); // The id is depending on header and body jexcel.current.contextMenu.contextmenu.open(e, items); // Avoid the real one e.preventDefault(); } } } } } jexcel.touchStartControls = function(e) { var jexcelTable = jexcel.getElement(e.target); if (jexcelTable[0]) { if (jexcel.current != jexcelTable[0].jexcel) { if (jexcel.current) { jexcel.current.resetSelection(); } jexcel.current = jexcelTable[0].jexcel; } } else { if (jexcel.current) { jexcel.current.resetSelection(); jexcel.current = null; } } if (jexcel.current) { if (! jexcel.current.edition) { var columnId = e.target.getAttribute('data-x'); var rowId = e.target.getAttribute('data-y'); if (columnId && rowId) { jexcel.current.updateSelectionFromCoords(columnId, rowId); jexcel.timeControl = setTimeout(function() { jexcel.current.openEditor(e.target, false, e); }, 500); } } } } jexcel.touchEndControls = function(e) { // Clear any time control if (jexcel.timeControl) { clearTimeout(jexcel.timeControl); jexcel.timeControl = null; } } jexcel.copyControls.enabled = true; /** * Jquery Support */ if (typeof(jQuery) != 'undefined') { (function($){ var methods = { init: function(init) { methods = jexcel($(this).get(0), init) } }; $.fn.jexcel = function(method) { if (methods[method]) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); } }; })(jQuery); } /** * Jexcel extensions */ jexcel.createTabs = function(tabs, result) { // Create tab container tabs.innerHTML = ''; tabs.classList.add('jexcel_tabs'); var spreadsheet = [] var link = []; for (var i = 0; i < result.length; i++) { // Spreadsheet container spreadsheet[i] = document.createElement('div'); spreadsheet[i].classList.add('jexcel_tab'); // Tab link link[i] = document.createElement('div'); link[i].classList.add('jexcel_tab_link'); link[i].setAttribute('data-spreadsheet', i); link[i].innerHTML = result[i].sheetName; link[i].onclick = function() { for (var j = 0; j < spreadsheet.length; j++) { spreadsheet[j].style.display = 'none'; link[j].classList.remove('selected'); } var i = this.getAttribute('data-spreadsheet'); spreadsheet[i].style.display = 'block'; link[i].classList.add('selected') } tabs.appendChild(link[i]); } // Append spreadsheet for (var i = 0; i < spreadsheet.length - 1; i++) { tabs.appendChild(spreadsheet[i]); jexcel(spreadsheet[i], result[i]); } // First tab spreadsheet[0].style.display = 'block'; link[0].classList.add('selected') } jexcel.fromSpreadsheet = function(file, __callback) { var convert = function(workbook) { var spreadsheets = []; workbook.SheetNames.forEach(function(sheetName) { var spreadsheet = {}; spreadsheet.rows = []; spreadsheet.columns = []; spreadsheet.data = []; spreadsheet.style = {}; spreadsheet.sheetName = sheetName; // Column widths var temp = workbook.Sheets[sheetName]['!cols']; if (temp && temp.length) { for (var i = 0; i < temp.length; i++) { spreadsheet.columns[i] = {}; spreadsheet.columns[i].width = temp[i].wpx + 'px'; } } // Rows heights var temp = workbook.Sheets[sheetName]['!rows']; if (temp && temp.length) { for (var i = 0; i < temp.length; i++) { if (temp[i] && temp[i].hpx) { spreadsheet.rows[i] = {}; spreadsheet.rows[i].height = temp[i].hpx + 'px'; } } } // Merge cells var temp = workbook.Sheets[sheetName]['!merges']; if (temp && temp.length > 0) { spreadsheet.mergeCells = []; for (var i = 0; i < temp.length; i++) { var x1 = temp[i].s.c; var y1 = temp[i].s.r; var x2 = temp[i].e.c; var y2 = temp[i].e.r; var key = jexcel.getColumnNameFromId([x1,y1]); spreadsheet.mergeCells[key] = [ x2-x1+1, y2-y1+1 ]; } } // Data container var max_x = 0; var max_y = 0; var temp = Object.keys(workbook.Sheets[sheetName]); for (var i = 0; i < temp.length; i++) { if (temp[i].substr(0,1) != '!') { var cell = workbook.Sheets[sheetName][temp[i]]; var info = jexcel.getIdFromColumnName(temp[i], true); if (! spreadsheet.data[info[1]]) { spreadsheet.data[info[1]] = []; } spreadsheet.data[info[1]][info[0]] = cell.f ? '=' + cell.f : cell.w; if (max_x < info[0]) { max_x = info[0]; } if (max_y < info[1]) { max_y = info[1]; } // Style if (cell.style && Object.keys(cell.style).length > 0) { spreadsheet.style[temp[i]] = cell.style; } if (cell.s && cell.s.fgColor) { if (spreadsheet.style[temp[i]]) { spreadsheet.style[temp[i]] += ';'; } spreadsheet.style[temp[i]] += 'background-color:#' + cell.s.fgColor.rgb; } } } var numColumns = spreadsheet.columns; for (var j = 0; j <= max_y; j++) { for (var i = 0; i <= max_x; i++) { if (! spreadsheet.data[j]) { spreadsheet.data[j] = []; } if (! spreadsheet.data[j][i]) { if (numColumns < i) { spreadsheet.data[j][i] = ''; } } } } spreadsheets.push(spreadsheet); }); return spreadsheets; } var oReq; oReq = new XMLHttpRequest(); oReq.open("GET", file, true); if(typeof Uint8Array !== 'undefined') { oReq.responseType = "arraybuffer"; oReq.onload = function(e) { var arraybuffer = oReq.response; var data = new Uint8Array(arraybuffer); var wb = XLSX.read(data, {type:"array", cellFormula:true, cellStyles:true }); __callback(convert(wb)) }; } else { oReq.setRequestHeader("Accept-Charset", "x-user-defined"); oReq.onreadystatechange = function() { if(oReq.readyState == 4 && oReq.status == 200) { var ff = convertResponseBodyToText(oReq.responseBody); var wb = XLSX.read(ff, {type:"binary", cellFormula:true, cellStyles:true }); __callback(convert(wb)) }}; } oReq.send(); } // Based on sutoiku work (https://github.com/sutoiku) var error = (function() { var exports = {}; exports.nil = new Error('#NULL!'); exports.div0 = new Error('#DIV/0!'); exports.value = new Error('#VALUE!'); exports.ref = new Error('#REF!'); exports.name = new Error('#NAME?'); exports.num = new Error('#NUM!'); exports.na = new Error('#N/A'); exports.error = new Error('#ERROR!'); exports.data = new Error('#GETTING_DATA'); return exports; })(); var utils = (function() { var exports = {}; exports.flattenShallow = function(array) { if (!array || !array.reduce) { return array; } return array.reduce(function(a, b) { var aIsArray = Array.isArray(a); var bIsArray = Array.isArray(b); if (aIsArray && bIsArray) { return a.concat(b); } if (aIsArray) { a.push(b); return a; } if (bIsArray) { return [ a ].concat(b); } return [ a, b ]; }); }; exports.isFlat = function(array) { if (!array) { return false; } for (var i = 0; i < array.length; ++i) { if (Array.isArray(array[i])) { return false; } } return true; }; exports.flatten = function() { var result = exports.argsToArray.apply(null, arguments); while (!exports.isFlat(result)) { result = exports.flattenShallow(result); } return result; }; exports.argsToArray = function(args) { var result = []; exports.arrayEach(args, function(value) { result.push(value); }); return result; }; exports.numbers = function() { var possibleNumbers = this.flatten.apply(null, arguments); return possibleNumbers.filter(function(el) { return typeof el === 'number'; }); }; exports.cleanFloat = function(number) { var power = 1e14; return Math.round(number * power) / power; }; exports.parseBool = function(bool) { if (typeof bool === 'boolean') { return bool; } if (bool instanceof Error) { return bool; } if (typeof bool === 'number') { return bool !== 0; } if (typeof bool === 'string') { var up = bool.toUpperCase(); if (up === 'TRUE') { return true; } if (up === 'FALSE') { return false; } } if (bool instanceof Date && !isNaN(bool)) { return true; } return error.value; }; exports.parseNumber = function(string) { if (string === undefined || string === '') { return error.value; } if (!isNaN(string)) { return parseFloat(string); } return error.value; }; exports.parseNumberArray = function(arr) { var len; if (!arr || (len = arr.length) === 0) { return error.value; } var parsed; while (len--) { parsed = exports.parseNumber(arr[len]); if (parsed === error.value) { return parsed; } arr[len] = parsed; } return arr; }; exports.parseMatrix = function(matrix) { var n; if (!matrix || (n = matrix.length) === 0) { return error.value; } var pnarr; for (var i = 0; i < matrix.length; i++) { pnarr = exports.parseNumberArray(matrix[i]); matrix[i] = pnarr; if (pnarr instanceof Error) { return pnarr; } } return matrix; }; var d1900 = new Date(Date.UTC(1900, 0, 1)); exports.parseDate = function(date) { if (!isNaN(date)) { if (date instanceof Date) { return new Date(date); } var d = parseInt(date, 10); if (d < 0) { return error.num; } if (d <= 60) { return new Date(d1900.getTime() + (d - 1) * 86400000); } return new Date(d1900.getTime() + (d - 2) * 86400000); } if (typeof date === 'string') { date = new Date(date); if (!isNaN(date)) { return date; } } return error.value; }; exports.parseDateArray = function(arr) { var len = arr.length; var parsed; while (len--) { parsed = this.parseDate(arr[len]); if (parsed === error.value) { return parsed; } arr[len] = parsed; } return arr; }; exports.anyIsError = function() { var n = arguments.length; while (n--) { if (arguments[n] instanceof Error) { return true; } } return false; }; exports.arrayValuesToNumbers = function(arr) { var n = arr.length; var el; while (n--) { el = arr[n]; if (typeof el === 'number') { continue; } if (el === true) { arr[n] = 1; continue; } if (el === false) { arr[n] = 0; continue; } if (typeof el === 'string') { var number = this.parseNumber(el); if (number instanceof Error) { arr[n] = 0; } else { arr[n] = number; } } } return arr; }; exports.rest = function(array, idx) { idx = idx || 1; if (!array || typeof array.slice !== 'function') { return array; } return array.slice(idx); }; exports.initial = function(array, idx) { idx = idx || 1; if (!array || typeof array.slice !== 'function') { return array; } return array.slice(0, array.length - idx); }; exports.arrayEach = function(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; }; exports.transpose = function(matrix) { if (!matrix) { return error.value; } return matrix[0].map(function(col, i) { return matrix.map(function(row) { return row[i]; }); }); }; return exports; })(); jexcel.methods = {}; jexcel.methods.datetime = (function() { var exports = {}; var d1900 = new Date(1900, 0, 1); var WEEK_STARTS = [ undefined, 0, 1, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1, 2, 3, 4, 5, 6, 0 ]; var WEEK_TYPES = [ [], [1, 2, 3, 4, 5, 6, 7], [7, 1, 2, 3, 4, 5, 6], [6, 0, 1, 2, 3, 4, 5], [], [], [], [], [], [], [], [7, 1, 2, 3, 4, 5, 6], [6, 7, 1, 2, 3, 4, 5], [5, 6, 7, 1, 2, 3, 4], [4, 5, 6, 7, 1, 2, 3], [3, 4, 5, 6, 7, 1, 2], [2, 3, 4, 5, 6, 7, 1], [1, 2, 3, 4, 5, 6, 7] ]; var WEEKEND_TYPES = [ [], [6, 0], [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], undefined, undefined, undefined, [0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6] ]; exports.DATE = function(year, month, day) { year = utils.parseNumber(year); month = utils.parseNumber(month); day = utils.parseNumber(day); if (utils.anyIsError(year, month, day)) { return error.value; } if (year < 0 || month < 0 || day < 0) { return error.num; } var date = new Date(year, month - 1, day); return date; }; exports.DATEVALUE = function(date_text) { if (typeof date_text !== 'string') { return error.value; } var date = Date.parse(date_text); if (isNaN(date)) { return error.value; } if (date <= -2203891200000) { return (date - d1900) / 86400000 + 1; } return (date - d1900) / 86400000 + 2; }; exports.DAY = function(serial_number) { var date = utils.parseDate(serial_number); if (date instanceof Error) { return date; } return date.getDate(); }; exports.DAYS = function(end_date, start_date) { end_date = utils.parseDate(end_date); start_date = utils.parseDate(start_date); if (end_date instanceof Error) { return end_date; } if (start_date instanceof Error) { return start_date; } return serial(end_date) - serial(start_date); }; exports.DAYS360 = function(start_date, end_date, method) { }; exports.EDATE = function(start_date, months) { start_date = utils.parseDate(start_date); if (start_date instanceof Error) { return start_date; } if (isNaN(months)) { return error.value; } months = parseInt(months, 10); start_date.setMonth(start_date.getMonth() + months); return serial(start_date); }; exports.EOMONTH = function(start_date, months) { start_date = utils.parseDate(start_date); if (start_date instanceof Error) { return start_date; } if (isNaN(months)) { return error.value; } months = parseInt(months, 10); return serial(new Date(start_date.getFullYear(), start_date.getMonth() + months + 1, 0)); }; exports.HOUR = function(serial_number) { serial_number = utils.parseDate(serial_number); if (serial_number instanceof Error) { return serial_number; } return serial_number.getHours(); }; exports.INTERVAL = function(second) { if (typeof second !== 'number' && typeof second !== 'string') { return error.value; } else { second = parseInt(second, 10); } var year = Math.floor(second/946080000); second = second%946080000; var month = Math.floor(second/2592000); second = second%2592000; var day = Math.floor(second/86400); second = second%86400; var hour = Math.floor(second/3600); second = second%3600; var min = Math.floor(second/60); second = second%60; var sec = second; year = (year > 0) ? year + 'Y' : ''; month = (month > 0) ? month + 'M' : ''; day = (day > 0) ? day + 'D' : ''; hour = (hour > 0) ? hour + 'H' : ''; min = (min > 0) ? min + 'M' : ''; sec = (sec > 0) ? sec + 'S' : ''; return 'P' + year + month + day + 'T' + hour + min + sec; }; exports.ISOWEEKNUM = function(date) { date = utils.parseDate(date); if (date instanceof Error) { return date; } date.setHours(0, 0, 0); date.setDate(date.getDate() + 4 - (date.getDay() || 7)); var yearStart = new Date(date.getFullYear(), 0, 1); return Math.ceil((((date - yearStart) / 86400000) + 1) / 7); }; exports.MINUTE = function(serial_number) { serial_number = utils.parseDate(serial_number); if (serial_number instanceof Error) { return serial_number; } return serial_number.getMinutes(); }; exports.MONTH = function(serial_number) { serial_number = utils.parseDate(serial_number); if (serial_number instanceof Error) { return serial_number; } return serial_number.getMonth() + 1; }; exports.NETWORKDAYS = function(start_date, end_date, holidays) { }; exports.NETWORKDAYS.INTL = function(start_date, end_date, weekend, holidays) { }; exports.NOW = function() { return new Date(); }; exports.SECOND = function(serial_number) { serial_number = utils.parseDate(serial_number); if (serial_number instanceof Error) { return serial_number; } return serial_number.getSeconds(); }; exports.TIME = function(hour, minute, second) { hour = utils.parseNumber(hour); minute = utils.parseNumber(minute); second = utils.parseNumber(second); if (utils.anyIsError(hour, minute, second)) { return error.value; } if (hour < 0 || minute < 0 || second < 0) { return error.num; } return (3600 * hour + 60 * minute + second) / 86400; }; exports.TIMEVALUE = function(time_text) { time_text = utils.parseDate(time_text); if (time_text instanceof Error) { return time_text; } return (3600 * time_text.getHours() + 60 * time_text.getMinutes() + time_text.getSeconds()) / 86400; }; exports.TODAY = function() { return new Date(); }; exports.WEEKDAY = function(serial_number, return_type) { serial_number = utils.parseDate(serial_number); if (serial_number instanceof Error) { return serial_number; } if (return_type === undefined) { return_type = 1; } var day = serial_number.getDay(); return WEEK_TYPES[return_type][day]; }; exports.WEEKNUM = function(serial_number, return_type) { }; exports.WORKDAY = function(start_date, days, holidays) { }; exports.WORKDAY.INTL = function(start_date, days, weekend, holidays) { }; exports.YEAR = function(serial_number) { serial_number = utils.parseDate(serial_number); if (serial_number instanceof Error) { return serial_number; } return serial_number.getFullYear(); }; function isLeapYear(year) { return new Date(year, 1, 29).getMonth() === 1; } exports.YEARFRAC = function(start_date, end_date, basis) { }; function serial(date) { var addOn = (date > -2203891200000)?2:1; return (date - d1900) / 86400000 + addOn; } return exports; })(); jexcel.methods.database = (function() { var exports = {}; function compact(array) { if (!array) { return array; } var result = []; for (var i = 0; i < array.length; ++i) { if (!array[i]) { continue; } result.push(array[i]); } return result; } exports.FINDFIELD = function(database, title) { var index = null; for (var i = 0; i < database.length; i++) { if (database[i][0] === title) { index = i; break; } } // Return error if the input field title is incorrect if (index == null) { return error.value; } return index; }; function findResultIndex(database, criterias) { var matches = {}; for (var i = 1; i < database[0].length; ++i) { matches[i] = true; } var maxCriteriaLength = criterias[0].length; for (i = 1; i < criterias.length; ++i) { if (criterias[i].length > maxCriteriaLength) { maxCriteriaLength = criterias[i].length; } } for (var k = 1; k < database.length; ++k) { for (var l = 1; l < database[k].length; ++l) { var currentCriteriaResult = false; var hasMatchingCriteria = false; for (var j = 0; j < criterias.length; ++j) { var criteria = criterias[j]; if (criteria.length < maxCriteriaLength) { continue; } var criteriaField = criteria[0]; if (database[k][0] !== criteriaField) { continue; } hasMatchingCriteria = true; for (var p = 1; p < criteria.length; ++p) { currentCriteriaResult = currentCriteriaResult || eval(database[k][l] + criteria[p]); // jshint // ignore:line } } if (hasMatchingCriteria) { matches[l] = matches[l] && currentCriteriaResult; } } } var result = []; for (var n = 0; n < database[0].length; ++n) { if (matches[n]) { result.push(n - 1); } } return result; } // Database functions exports.DAVERAGE = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return error.value; } var resultIndexes = findResultIndex(database, criteria); var targetFields = []; if (typeof field === "string") { var index = exports.FINDFIELD(database, field); targetFields = utils.rest(database[index]); } else { targetFields = utils.rest(database[field]); } var sum = 0; for (var i = 0; i < resultIndexes.length; i++) { sum += targetFields[resultIndexes[i]]; } return resultIndexes.length === 0 ? error.div0 : sum / resultIndexes.length; }; exports.DCOUNT = function(database, field, criteria) { }; exports.DCOUNTA = function(database, field, criteria) { }; exports.DGET = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return error.value; } var resultIndexes = findResultIndex(database, criteria); var targetFields = []; if (typeof field === "string") { var index = exports.FINDFIELD(database, field); targetFields = utils.rest(database[index]); } else { targetFields = utils.rest(database[field]); } // Return error if no record meets the criteria if (resultIndexes.length === 0) { return error.value; } // Returns the #NUM! error value because more than one record meets the // criteria if (resultIndexes.length > 1) { return error.num; } return targetFields[resultIndexes[0]]; }; exports.DMAX = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return error.value; } var resultIndexes = findResultIndex(database, criteria); var targetFields = []; if (typeof field === "string") { var index = exports.FINDFIELD(database, field); targetFields = utils.rest(database[index]); } else { targetFields = utils.rest(database[field]); } var maxValue = targetFields[resultIndexes[0]]; for (var i = 1; i < resultIndexes.length; i++) { if (maxValue < targetFields[resultIndexes[i]]) { maxValue = targetFields[resultIndexes[i]]; } } return maxValue; }; exports.DMIN = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return error.value; } var resultIndexes = findResultIndex(database, criteria); var targetFields = []; if (typeof field === "string") { var index = exports.FINDFIELD(database, field); targetFields = utils.rest(database[index]); } else { targetFields = utils.rest(database[field]); } var minValue = targetFields[resultIndexes[0]]; for (var i = 1; i < resultIndexes.length; i++) { if (minValue > targetFields[resultIndexes[i]]) { minValue = targetFields[resultIndexes[i]]; } } return minValue; }; exports.DPRODUCT = function(database, field, criteria) { // Return error if field is not a number and not a string if (isNaN(field) && (typeof field !== "string")) { return error.value; } var resultIndexes = findResultIndex(database, criteria); var targetFields = []; if (typeof field === "string") { var index = exports.FINDFIELD(database, field); targetFields = utils.rest(database[index]); } else { targetFields = utils.rest(database[field]); } var targetValues = []; for (var i = 0; i < resultIndexes.length; i++) { targetValues[i] = targetFields[resultIndexes[i]]; } targetValues = compact(targetValues); var result = 1; for (i = 0; i < targetValues.length; i++) { result *= targetValues[i]; } return result; }; exports.DSTDEV = function(database, field, criteria) { }; exports.DSTDEVP = function(database, field, criteria) { }; exports.DSUM = function(database, field, criteria) { }; exports.DVAR = function(database, field, criteria) { }; exports.DVARP = function(database, field, criteria) { }; exports.MATCH = function(lookupValue, lookupArray, matchType) { if (!lookupValue && !lookupArray) { return error.na; } if (arguments.length === 2) { matchType = 1; } if (!(lookupArray instanceof Array)) { return error.na; } if (matchType !== -1 && matchType !== 0 && matchType !== 1) { return error.na; } var index; var indexValue; for (var idx = 0; idx < lookupArray.length; idx++) { if (matchType === 1) { if (lookupArray[idx] === lookupValue) { return idx + 1; } else if (lookupArray[idx] < lookupValue) { if (!indexValue) { index = idx + 1; indexValue = lookupArray[idx]; } else if (lookupArray[idx] > indexValue) { index = idx + 1; indexValue = lookupArray[idx]; } } } else if (matchType === 0) { if (typeof lookupValue === 'string') { lookupValue = lookupValue.replace(/\?/g, '.'); if (lookupArray[idx].toLowerCase().match(lookupValue.toLowerCase())) { return idx + 1; } } else { if (lookupArray[idx] === lookupValue) { return idx + 1; } } } else if (matchType === -1) { if (lookupArray[idx] === lookupValue) { return idx + 1; } else if (lookupArray[idx] > lookupValue) { if (!indexValue) { index = idx + 1; indexValue = lookupArray[idx]; } else if (lookupArray[idx] < indexValue) { index = idx + 1; indexValue = lookupArray[idx]; } } } } return index ? index : error.na; }; return exports; })(); jexcel.methods.engineering = (function() { var exports = {}; function isValidBinaryNumber(number) { return (/^[01]{1,10}$/).test(number); } exports.BESSELI = function(x, n) { }; exports.BESSELJ = function(x, n) { }; exports.BESSELK = function(x, n) { }; exports.BESSELY = function(x, n) { }; exports.BIN2DEC = function(number) { // Return error if number is not binary or contains more than 10 // characters (10 digits) if (!isValidBinaryNumber(number)) { return error.num; } // Convert binary number to decimal var result = parseInt(number, 2); // Handle negative numbers var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return parseInt(stringified.substring(1), 2) - 512; } else { return result; } }; exports.BIN2HEX = function(number, places) { // Return error if number is not binary or contains more than 10 // characters (10 digits) if (!isValidBinaryNumber(number)) { return error.num; } // Ignore places and return a 10-character hexadecimal number if number // is negative var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16); } // Convert binary number to hexadecimal var result = parseInt(number, 2).toString(16); // Return hexadecimal number using the minimum number of characters // necessary if places is undefined if (places === undefined) { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.BIN2OCT = function(number, places) { // Return error if number is not binary or contains more than 10 // characters (10 digits) if (!isValidBinaryNumber(number)) { return error.num; } // Ignore places and return a 10-character octal number if number is // negative var stringified = number.toString(); if (stringified.length === 10 && stringified.substring(0, 1) === '1') { return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8); } // Convert binary number to octal var result = parseInt(number, 2).toString(8); // Return octal number using the minimum number of characters necessary // if places is undefined if (places === undefined) { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.BITAND = function(number1, number2) { // Return error if either number is a non-numeric value number1 = utils.parseNumber(number1); number2 = utils.parseNumber(number2); if (utils.anyIsError(number1, number2)) { return error.value; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return error.num; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return error.num; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return error.num; } // Return bitwise AND of two numbers return number1 & number2; }; exports.BITLSHIFT = function(number, shift) { number = utils.parseNumber(number); shift = utils.parseNumber(shift); if (utils.anyIsError(number, shift)) { return error.value; } // Return error if number is less than 0 if (number < 0) { return error.num; } // Return error if number is a non-integer if (Math.floor(number) !== number) { return error.num; } // Return error if number is greater than (2^48)-1 if (number > 281474976710655) { return error.num; } // Return error if the absolute value of shift is greater than 53 if (Math.abs(shift) > 53) { return error.num; } // Return number shifted by shift bits to the left or to the right if // shift is negative return (shift >= 0) ? number << shift : number >> -shift; }; exports.BITOR = function(number1, number2) { number1 = utils.parseNumber(number1); number2 = utils.parseNumber(number2); if (utils.anyIsError(number1, number2)) { return error.value; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return error.num; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return error.num; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return error.num; } // Return bitwise OR of two numbers return number1 | number2; }; exports.BITRSHIFT = function(number, shift) { number = utils.parseNumber(number); shift = utils.parseNumber(shift); if (utils.anyIsError(number, shift)) { return error.value; } // Return error if number is less than 0 if (number < 0) { return error.num; } // Return error if number is a non-integer if (Math.floor(number) !== number) { return error.num; } // Return error if number is greater than (2^48)-1 if (number > 281474976710655) { return error.num; } // Return error if the absolute value of shift is greater than 53 if (Math.abs(shift) > 53) { return error.num; } // Return number shifted by shift bits to the right or to the left if // shift is negative return (shift >= 0) ? number >> shift : number << -shift; }; exports.BITXOR = function(number1, number2) { number1 = utils.parseNumber(number1); number2 = utils.parseNumber(number2); if (utils.anyIsError(number1, number2)) { return error.value; } // Return error if either number is less than 0 if (number1 < 0 || number2 < 0) { return error.num; } // Return error if either number is a non-integer if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { return error.num; } // Return error if either number is greater than (2^48)-1 if (number1 > 281474976710655 || number2 > 281474976710655) { return error.num; } // Return bitwise XOR of two numbers return number1 ^ number2; }; exports.COMPLEX = function(real, imaginary, suffix) { real = utils.parseNumber(real); imaginary = utils.parseNumber(imaginary); if (utils.anyIsError(real, imaginary)) { return real; } // Set suffix suffix = (suffix === undefined) ? 'i' : suffix; // Return error if suffix is neither "i" nor "j" if (suffix !== 'i' && suffix !== 'j') { return error.value; } // Return complex number if (real === 0 && imaginary === 0) { return 0; } else if (real === 0) { return (imaginary === 1) ? suffix : imaginary.toString() + suffix; } else if (imaginary === 0) { return real.toString(); } else { var sign = (imaginary > 0) ? '+' : ''; return real.toString() + sign + ((imaginary === 1) ? suffix : imaginary.toString() + suffix); } }; exports.CONVERT = function(number, from_unit, to_unit) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } // List of units supported by CONVERT and units defined by the // International System of Units // [Name, Symbol, Alternate symbols, Quantity, ISU, CONVERT, Conversion // ratio] var units = [ ["a.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], ["a.u. of charge", "e", null, "electric_charge", false, false, 1.60217653141414e-19], ["a.u. of energy", "Eh", null, "energy", false, false, 4.35974417757576e-18], ["a.u. of length", "a?", null, "length", false, false, 5.29177210818182e-11], ["a.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], ["a.u. of time", "?/Eh", null, "time", false, false, 2.41888432650516e-17], ["admiralty knot", "admkn", null, "speed", false, true, 0.514773333], ["ampere", "A", null, "electric_current", true, false, 1], ["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1], ["ångström", "Å", ["ang"], "length", false, true, 1e-10], ["are", "ar", null, "area", false, true, 100], ["astronomical unit", "ua", null, "length", false, false, 1.49597870691667e-11], ["bar", "bar", null, "pressure", false, false, 100000], ["barn", "b", null, "area", false, false, 1e-28], ["becquerel", "Bq", null, "radioactivity", true, false, 1], ["bit", "bit", ["b"], "information", false, true, 1], ["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262], ["byte", "byte", null, "information", false, true, 8], ["candela", "cd", null, "luminous_intensity", true, false, 1], ["candela per square metre", "cd/m?", null, "luminance", true, false, 1], ["coulomb", "C", null, "electric_charge", true, false, 1], ["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 1e-30], ["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592], ["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064], ["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 8.46786664623715e-47], ["cubic metre", "m?", null, "volume", true, true, 1], ["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058], ["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208], ["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 7.58660370370369e-8], ["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984], ["cup", "cup", null, "volume", false, true, 0.0002365882365], ["dalton", "Da", ["u"], "mass", false, false, 1.66053886282828e-27], ["day", "d", ["day"], "time", false, true, 86400], ["degree", "°", null, "angle", false, false, 0.0174532925199433], ["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556], ["dyne", "dyn", ["dy"], "force", false, true, 0.00001], ["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141], ["ell", "ell", null, "length", false, true, 1.143], ["erg", "erg", ["e"], "energy", false, true, 1e-7], ["farad", "F", null, "electric_capacitance", true, false, 1], ["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625], ["foot", "ft", null, "length", false, true, 0.3048], ["foot-pound", "flb", null, "energy", false, true, 1.3558179483314], ["gal", "Gal", null, "acceleration", false, false, 0.01], ["gallon", "gal", null, "volume", false, true, 0.003785411784], ["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1], ["grain", "grain", null, "mass", false, true, 0.0000647989], ["gram", "g", null, "mass", false, true, 0.001], ["gray", "Gy", null, "absorbed_dose", true, false, 1], ["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592], ["hectare", "ha", null, "area", false, true, 10000], ["henry", "H", null, "inductance", true, false, 1], ["hertz", "Hz", null, "frequency", true, false, 1], ["horsepower", "HP", ["h"], "power", false, true, 745.69987158227], ["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538], ["hour", "h", ["hr"], "time", false, true, 3600], ["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609], ["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345], ["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225], ["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909], ["inch", "in", null, "length", false, true, 0.0254], ["international acre", "uk_acre", null, "area", false, true, 4046.8564224], ["IT calorie", "cal", null, "energy", false, true, 4.1868], ["joule", "J", null, "energy", true, true, 1], ["katal", "kat", null, "catalytic_activity", true, false, 1], ["kelvin", "K", ["kel"], "temperature", true, true, 1], ["kilogram", "kg", null, "mass", true, true, 1], ["knot", "kn", null, "speed", false, true, 0.514444444444444], ["light-year", "ly", null, "length", false, true, 9460730472580800], ["litre", "L", ["l", "lt"], "volume", false, true, 0.001], ["lumen", "lm", null, "luminous_flux", true, false, 1], ["lux", "lx", null, "illuminance", true, false, 1], ["maxwell", "Mx", null, "magnetic_flux", false, false, 1e-18], ["measurement ton", "MTON", null, "volume", false, true, 1.13267386368], ["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778], ["meter per second", "m/s", ["m/sec"], "speed", true, true, 1], ["meter per second squared", "m?s??", null, "acceleration", true, false, 1], ["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900], ["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1], ["metre", "m", null, "length", true, true, 1], ["miles per hour", "mph", null, "speed", false, true, 0.44704], ["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322], ["minute", "?", null, "angle", false, false, 0.000290888208665722], ["minute", "min", ["mn"], "time", false, true, 60], ["modern teaspoon", "tspm", null, "volume", false, true, 0.000005], ["mole", "mol", null, "amount_of_substance", true, false, 1], ["morgen", "Morgen", null, "area", false, true, 2500], ["n.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], ["n.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], ["n.u. of speed", "c?", null, "speed", false, false, 299792458], ["n.u. of time", "?/(me?c??)", null, "time", false, false, 1.28808866778687e-21], ["nautical mile", "M", ["Nmi"], "length", false, true, 1852], ["newton", "N", null, "force", true, true, 1], ["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477], ["ohm", "Ω", null, "electric_resistance", true, false, 1], ["ounce mass", "ozm", null, "mass", false, true, 0.028349523125], ["pascal", "Pa", null, "pressure", true, false, 1], ["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1], ["pferdestärke", "PS", null, "power", false, true, 735.49875], ["phot", "ph", null, "illuminance", false, false, 0.0001], ["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778], ["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333], ["poise", "P", null, "dynamic_viscosity", false, false, 0.1], ["pond", "pond", null, "force", false, true, 0.00980665], ["pound force", "lbf", null, "force", false, true, 4.4482216152605], ["pound mass", "lbm", null, "mass", false, true, 0.45359237], ["quart", "qt", null, "volume", false, true, 0.000946352946], ["radian", "rad", null, "angle", true, false, 1], ["second", "?", null, "angle", false, false, 0.00000484813681109536], ["second", "s", ["sec"], "time", true, true, 1], ["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237], ["siemens", "S", null, "electrical_conductance", true, false, 1], ["sievert", "Sv", null, "equivalent_dose", true, false, 1], ["slug", "sg", null, "mass", false, true, 14.59390294], ["square ångström", "ang2", ["ang^2"], "area", false, true, 1e-20], ["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304], ["square inch", "in2", ["in^2"], "area", false, true, 0.00064516], ["square light-year", "ly2", ["ly^2"], "area", false, true, 8.95054210748189e+31], ["square meter", "m?", null, "area", true, true, 1], ["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336], ["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904], ["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111], ["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736], ["statute mile", "mi", null, "length", false, true, 1609.344], ["steradian", "sr", null, "solid_angle", true, false, 1], ["stilb", "sb", null, "luminance", false, false, 0.0001], ["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001], ["stone", "stone", null, "mass", false, true, 6.35029318], ["tablespoon", "tbs", null, "volume", false, true, 0.0000147868], ["teaspoon", "tsp", null, "volume", false, true, 0.00000492892], ["tesla", "T", null, "magnetic_flux_density", true, true, 1], ["thermodynamic calorie", "c", null, "energy", false, true, 4.184], ["ton", "ton", null, "mass", false, true, 907.18474], ["tonne", "t", null, "mass", false, false, 1000], ["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125], ["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907], ["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295], ["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473], ["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219], ["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261], ["volt", "V", null, "voltage", true, false, 1], ["watt", "W", null, "power", true, true, 1], ["watt-hour", "Wh", ["wh"], "energy", false, true, 3600], ["weber", "Wb", null, "magnetic_flux", true, false, 1], ["yard", "yd", null, "length", false, true, 0.9144], ["year", "yr", null, "time", false, true, 31557600] ]; // Binary prefixes // [Name, Prefix power of 2 value, Previx value, Abbreviation, Derived // from] var binary_prefixes = { Yi: ["yobi", 80, 1208925819614629174706176, "Yi", "yotta"], Zi: ["zebi", 70, 1180591620717411303424, "Zi", "zetta"], Ei: ["exbi", 60, 1152921504606846976, "Ei", "exa"], Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"], Ti: ["tebi", 40, 1099511627776, "Ti", "tera"], Gi: ["gibi", 30, 1073741824, "Gi", "giga"], Mi: ["mebi", 20, 1048576, "Mi", "mega"], ki: ["kibi", 10, 1024, "ki", "kilo"] }; // Unit prefixes // [Name, Multiplier, Abbreviation] var unit_prefixes = { Y: ["yotta", 1e+24, "Y"], Z: ["zetta", 1e+21, "Z"], E: ["exa", 1e+18, "E"], P: ["peta", 1e+15, "P"], T: ["tera", 1e+12, "T"], G: ["giga", 1e+09, "G"], M: ["mega", 1e+06, "M"], k: ["kilo", 1e+03, "k"], h: ["hecto", 1e+02, "h"], e: ["dekao", 1e+01, "e"], d: ["deci", 1e-01, "d"], c: ["centi", 1e-02, "c"], m: ["milli", 1e-03, "m"], u: ["micro", 1e-06, "u"], n: ["nano", 1e-09, "n"], p: ["pico", 1e-12, "p"], f: ["femto", 1e-15, "f"], a: ["atto", 1e-18, "a"], z: ["zepto", 1e-21, "z"], y: ["yocto", 1e-24, "y"] }; // Initialize units and multipliers var from = null; var to = null; var base_from_unit = from_unit; var base_to_unit = to_unit; var from_multiplier = 1; var to_multiplier = 1; var alt; // Lookup from and to units for (var i = 0; i < units.length; i++) { alt = (units[i][2] === null) ? [] : units[i][2]; if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { from = units[i]; } if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { to = units[i]; } } // Lookup from prefix if (from === null) { var from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)]; var from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)]; // Handle dekao unit prefix (only unit prefix with two characters) if (from_unit.substring(0, 2) === 'da') { from_unit_prefix = ["dekao", 1e+01, "da"]; } // Handle binary prefixes first (so that 'Yi' is processed before // 'Y') if (from_binary_prefix) { from_multiplier = from_binary_prefix[2]; base_from_unit = from_unit.substring(2); } else if (from_unit_prefix) { from_multiplier = from_unit_prefix[1]; base_from_unit = from_unit.substring(from_unit_prefix[2].length); } // Lookup from unit for (var j = 0; j < units.length; j++) { alt = (units[j][2] === null) ? [] : units[j][2]; if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { from = units[j]; } } } // Lookup to prefix if (to === null) { var to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)]; var to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)]; // Handle dekao unit prefix (only unit prefix with two characters) if (to_unit.substring(0, 2) === 'da') { to_unit_prefix = ["dekao", 1e+01, "da"]; } // Handle binary prefixes first (so that 'Yi' is processed before // 'Y') if (to_binary_prefix) { to_multiplier = to_binary_prefix[2]; base_to_unit = to_unit.substring(2); } else if (to_unit_prefix) { to_multiplier = to_unit_prefix[1]; base_to_unit = to_unit.substring(to_unit_prefix[2].length); } // Lookup to unit for (var k = 0; k < units.length; k++) { alt = (units[k][2] === null) ? [] : units[k][2]; if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { to = units[k]; } } } // Return error if a unit does not exist if (from === null || to === null) { return error.na; } // Return error if units represent different quantities if (from[3] !== to[3]) { return error.na; } // Return converted number return number * from[6] * from_multiplier / (to[6] * to_multiplier); }; exports.DEC2BIN = function(number, places) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } // Return error if number is not decimal, is lower than -512, or is // greater than 511 if (!/^-?[0-9]{1,3}$/.test(number) || number < -512 || number > 511) { return error.num; } // Ignore places and return a 10-character binary number if number is // negative if (number < 0) { return '1' + REPT('0', 9 - (512 + number).toString(2).length) + (512 + number).toString(2); } // Convert decimal number to binary var result = parseInt(number, 10).toString(2); // Return binary number using the minimum number of characters necessary // if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.DEC2HEX = function(number, places) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } // Return error if number is not decimal, is lower than -549755813888, // or is greater than 549755813887 if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) { return error.num; } // Ignore places and return a 10-character hexadecimal number if number // is negative if (number < 0) { return (1099511627776 + number).toString(16); } // Convert decimal number to hexadecimal var result = parseInt(number, 10).toString(16); // Return hexadecimal number using the minimum number of characters // necessary if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.DEC2OCT = function(number, places) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } // Return error if number is not decimal, is lower than -549755813888, // or is greater than 549755813887 if (!/^-?[0-9]{1,9}$/.test(number) || number < -536870912 || number > 536870911) { return error.num; } // Ignore places and return a 10-character octal number if number is // negative if (number < 0) { return (1073741824 + number).toString(8); } // Convert decimal number to octal var result = parseInt(number, 10).toString(8); // Return octal number using the minimum number of characters necessary // if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.DELTA = function(number1, number2) { // Set number2 to zero if undefined number2 = (number2 === undefined) ? 0 : number2; number1 = utils.parseNumber(number1); number2 = utils.parseNumber(number2); if (utils.anyIsError(number1, number2)) { return error.value; } // Return delta return (number1 === number2) ? 1 : 0; }; exports.ERF = function(lower_bound, upper_bound) { }; exports.ERF.PRECISE = function() { }; exports.ERFC = function(x) { }; exports.ERFC.PRECISE = function() { }; exports.GESTEP = function(number, step) { step = step || 0; number = utils.parseNumber(number); if (utils.anyIsError(step, number)) { return number; } // Return delta return (number >= step) ? 1 : 0; }; exports.HEX2BIN = function(number, places) { // Return error if number is not hexadecimal or contains more than ten // characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return error.num; } // Check if number is negative var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false; // Convert hexadecimal number to decimal var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16); // Return error if number is lower than -512 or greater than 511 if (decimal < -512 || decimal > 511) { return error.num; } // Ignore places and return a 10-character binary number if number is // negative if (negative) { return '1' + REPT('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); } // Convert decimal number to binary var result = decimal.toString(2); // Return binary number using the minimum number of characters necessary // if places is undefined if (places === undefined) { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.HEX2DEC = function(number) { // Return error if number is not hexadecimal or contains more than ten // characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return error.num; } // Convert hexadecimal number to decimal var decimal = parseInt(number, 16); // Return decimal number return (decimal >= 549755813888) ? decimal - 1099511627776 : decimal; }; exports.HEX2OCT = function(number, places) { // Return error if number is not hexadecimal or contains more than ten // characters (10 digits) if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { return error.num; } // Convert hexadecimal number to decimal var decimal = parseInt(number, 16); // Return error if number is positive and greater than 0x1fffffff // (536870911) if (decimal > 536870911 && decimal < 1098974756864) { return error.num; } // Ignore places and return a 10-character octal number if number is // negative if (decimal >= 1098974756864) { return (decimal - 1098437885952).toString(8); } // Convert decimal number to octal var result = decimal.toString(8); // Return octal number using the minimum number of characters necessary // if places is undefined if (places === undefined) { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.IMABS = function(inumber) { // Lookup real and imaginary coefficients using exports.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); // Return error if either coefficient is not a number if (utils.anyIsError(x, y)) { return error.value; } // Return absolute value of complex number return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); }; exports.IMAGINARY = function(inumber) { if (inumber === undefined || inumber === true || inumber === false) { return error.value; } // Return 0 if inumber is equal to 0 if (inumber === 0 || inumber === '0') { return 0; } // Handle special cases if (['i', 'j'].indexOf(inumber) >= 0) { return 1; } // Normalize imaginary coefficient inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j'); // Lookup sign var plus = inumber.indexOf('+'); var minus = inumber.indexOf('-'); if (plus === 0) { plus = inumber.indexOf('+', 1); } if (minus === 0) { minus = inumber.indexOf('-', 1); } // Lookup imaginary unit var last = inumber.substring(inumber.length - 1, inumber.length); var unit = (last === 'i' || last === 'j'); if (plus >= 0 || minus >= 0) { // Return error if imaginary unit is neither i nor j if (!unit) { return error.num; } // Return imaginary coefficient of complex number if (plus >= 0) { return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? error.num : Number(inumber.substring(plus + 1, inumber.length - 1)); } else { return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? error.num : -Number(inumber.substring(minus + 1, inumber.length - 1)); } } else { if (unit) { return (isNaN(inumber.substring(0, inumber.length - 1))) ? error.num : inumber.substring(0, inumber.length - 1); } else { return (isNaN(inumber)) ? error.num : 0; } } }; exports.IMARGUMENT = function(inumber) { // Lookup real and imaginary coefficients using exports.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); // Return error if either coefficient is not a number if (utils.anyIsError(x, y)) { return error.value; } // Return error if inumber is equal to zero if (x === 0 && y === 0) { return error.div0; } // Return PI/2 if x is equal to zero and y is positive if (x === 0 && y > 0) { return Math.PI / 2; } // Return -PI/2 if x is equal to zero and y is negative if (x === 0 && y < 0) { return -Math.PI / 2; } // Return zero if x is negative and y is equal to zero if (y === 0 && x > 0) { return 0; } // Return zero if x is negative and y is equal to zero if (y === 0 && x < 0) { return -Math.PI; } // Return argument of complex number if (x > 0) { return Math.atan(y / x); } else if (x < 0 && y >= 0) { return Math.atan(y / x) + Math.PI; } else { return Math.atan(y / x) - Math.PI; } }; exports.IMCONJUGATE = function(inumber) { // Lookup real and imaginary coefficients using exports.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return conjugate of complex number return (y !== 0) ? exports.COMPLEX(x, -y, unit) : inumber; }; exports.IMCOS = function(inumber) { // Lookup real and imaginary coefficients using exports.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return cosine of complex number return exports.COMPLEX(Math.cos(x) * (Math.exp(y) + Math.exp(-y)) / 2, -Math.sin(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); }; exports.IMCOSH = function(inumber) { // Lookup real and imaginary coefficients using exports.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return hyperbolic cosine of complex number return exports.COMPLEX(Math.cos(y) * (Math.exp(x) + Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) - Math.exp(-x)) / 2, unit); }; exports.IMCOT = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Return cotangent of complex number return exports.IMDIV(exports.IMCOS(inumber), exports.IMSIN(inumber)); }; exports.IMDIV = function(inumber1, inumber2) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var a = exports.IMREAL(inumber1); var b = exports.IMAGINARY(inumber1); var c = exports.IMREAL(inumber2); var d = exports.IMAGINARY(inumber2); if (utils.anyIsError(a, b, c, d)) { return error.value; } // Lookup imaginary unit var unit1 = inumber1.substring(inumber1.length - 1); var unit2 = inumber2.substring(inumber2.length - 1); var unit = 'i'; if (unit1 === 'j') { unit = 'j'; } else if (unit2 === 'j') { unit = 'j'; } // Return error if inumber2 is null if (c === 0 && d === 0) { return error.num; } // Return exponential of complex number var den = c * c + d * d; return exports.COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit); }; exports.IMEXP = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return exponential of complex number var e = Math.exp(x); return exports.COMPLEX(e * Math.cos(y), e * Math.sin(y), unit); }; exports.IMLN = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return exponential of complex number return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)), Math.atan(y / x), unit); }; exports.IMLOG10 = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return exponential of complex number return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(10), Math.atan(y / x) / Math.log(10), unit); }; exports.IMLOG2 = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return exponential of complex number return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(2), Math.atan(y / x) / Math.log(2), unit); }; exports.IMPOWER = function(inumber, number) { number = utils.parseNumber(number); var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(number, x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Calculate power of modulus var p = Math.pow(exports.IMABS(inumber), number); // Calculate argument var t = exports.IMARGUMENT(inumber); // Return exponential of complex number return exports.COMPLEX(p * Math.cos(number * t), p * Math.sin(number * t), unit); }; exports.IMPRODUCT = function() { // Initialize result var result = arguments[0]; // Loop on all numbers for (var i = 1; i < arguments.length; i++) { // Lookup coefficients of two complex numbers var a = exports.IMREAL(result); var b = exports.IMAGINARY(result); var c = exports.IMREAL(arguments[i]); var d = exports.IMAGINARY(arguments[i]); if (utils.anyIsError(a, b, c, d)) { return error.value; } // Complute product of two complex numbers result = exports.COMPLEX(a * c - b * d, a * d + b * c); } // Return product of complex numbers return result; }; exports.IMREAL = function(inumber) { if (inumber === undefined || inumber === true || inumber === false) { return error.value; } // Return 0 if inumber is equal to 0 if (inumber === 0 || inumber === '0') { return 0; } // Handle special cases if (['i', '+i', '1i', '+1i', '-i', '-1i', 'j', '+j', '1j', '+1j', '-j', '-1j'].indexOf(inumber) >= 0) { return 0; } // Lookup sign var plus = inumber.indexOf('+'); var minus = inumber.indexOf('-'); if (plus === 0) { plus = inumber.indexOf('+', 1); } if (minus === 0) { minus = inumber.indexOf('-', 1); } // Lookup imaginary unit var last = inumber.substring(inumber.length - 1, inumber.length); var unit = (last === 'i' || last === 'j'); if (plus >= 0 || minus >= 0) { // Return error if imaginary unit is neither i nor j if (!unit) { return error.num; } // Return real coefficient of complex number if (plus >= 0) { return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? error.num : Number(inumber.substring(0, plus)); } else { return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? error.num : Number(inumber.substring(0, minus)); } } else { if (unit) { return (isNaN(inumber.substring(0, inumber.length - 1))) ? error.num : 0; } else { return (isNaN(inumber)) ? error.num : inumber; } } }; exports.IMSEC = function(inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return error.value; } // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Return secant of complex number return exports.IMDIV('1', exports.IMCOS(inumber)); }; exports.IMSECH = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Return hyperbolic secant of complex number return exports.IMDIV('1', exports.IMCOSH(inumber)); }; exports.IMSIN = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return sine of complex number return exports.COMPLEX(Math.sin(x) * (Math.exp(y) + Math.exp(-y)) / 2, Math.cos(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); }; exports.IMSINH = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Return hyperbolic sine of complex number return exports.COMPLEX(Math.cos(y) * (Math.exp(x) - Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) + Math.exp(-x)) / 2, unit); }; exports.IMSQRT = function(inumber) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Lookup imaginary unit var unit = inumber.substring(inumber.length - 1); unit = (unit === 'i' || unit === 'j') ? unit : 'i'; // Calculate power of modulus var s = Math.sqrt(exports.IMABS(inumber)); // Calculate argument var t = exports.IMARGUMENT(inumber); // Return exponential of complex number return exports.COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit); }; exports.IMCSC = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return error.value; } // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); // Return error if either coefficient is not a number if (utils.anyIsError(x, y)) { return error.num; } // Return cosecant of complex number return exports.IMDIV('1', exports.IMSIN(inumber)); }; exports.IMCSCH = function (inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return error.value; } // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); // Return error if either coefficient is not a number if (utils.anyIsError(x, y)) { return error.num; } // Return hyperbolic cosecant of complex number return exports.IMDIV('1', exports.IMSINH(inumber)); }; exports.IMSUB = function(inumber1, inumber2) { // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var a = this.IMREAL(inumber1); var b = this.IMAGINARY(inumber1); var c = this.IMREAL(inumber2); var d = this.IMAGINARY(inumber2); if (utils.anyIsError(a, b, c, d)) { return error.value; } // Lookup imaginary unit var unit1 = inumber1.substring(inumber1.length - 1); var unit2 = inumber2.substring(inumber2.length - 1); var unit = 'i'; if (unit1 === 'j') { unit = 'j'; } else if (unit2 === 'j') { unit = 'j'; } // Return _ of two complex numbers return this.COMPLEX(a - c, b - d, unit); }; exports.IMSUM = function() { var args = utils.flatten(arguments); // Initialize result var result = args[0]; // Loop on all numbers for (var i = 1; i < args.length; i++) { // Lookup coefficients of two complex numbers var a = this.IMREAL(result); var b = this.IMAGINARY(result); var c = this.IMREAL(args[i]); var d = this.IMAGINARY(args[i]); if (utils.anyIsError(a, b, c, d)) { return error.value; } // Complute product of two complex numbers result = this.COMPLEX(a + c, b + d); } // Return sum of complex numbers return result; }; exports.IMTAN = function(inumber) { // Return error if inumber is a logical value if (inumber === true || inumber === false) { return error.value; } // Lookup real and imaginary coefficients using Formula.js // [http://formulajs.org] var x = exports.IMREAL(inumber); var y = exports.IMAGINARY(inumber); if (utils.anyIsError(x, y)) { return error.value; } // Return tangent of complex number return this.IMDIV(this.IMSIN(inumber), this.IMCOS(inumber)); }; exports.OCT2BIN = function(number, places) { // Return error if number is not hexadecimal or contains more than ten // characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return error.num; } // Check if number is negative var negative = (number.length === 10 && number.substring(0, 1) === '7') ? true : false; // Convert octal number to decimal var decimal = (negative) ? parseInt(number, 8) - 1073741824 : parseInt(number, 8); // Return error if number is lower than -512 or greater than 511 if (decimal < -512 || decimal > 511) { return error.num; } // Ignore places and return a 10-character binary number if number is // negative if (negative) { return '1' + REPT('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); } // Convert decimal number to binary var result = decimal.toString(2); // Return binary number using the minimum number of characters necessary // if places is undefined if (typeof places === 'undefined') { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; exports.OCT2DEC = function(number) { // Return error if number is not octal or contains more than ten // characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return error.num; } // Convert octal number to decimal var decimal = parseInt(number, 8); // Return decimal number return (decimal >= 536870912) ? decimal - 1073741824 : decimal; }; exports.OCT2HEX = function(number, places) { // Return error if number is not octal or contains more than ten // characters (10 digits) if (!/^[0-7]{1,10}$/.test(number)) { return error.num; } // Convert octal number to decimal var decimal = parseInt(number, 8); // Ignore places and return a 10-character octal number if number is // negative if (decimal >= 536870912) { return 'ff' + (decimal + 3221225472).toString(16); } // Convert decimal number to hexadecimal var result = decimal.toString(16); // Return hexadecimal number using the minimum number of characters // necessary if places is undefined if (places === undefined) { return result; } else { // Return error if places is nonnumeric if (isNaN(places)) { return error.value; } // Return error if places is negative if (places < 0) { return error.num; } // Truncate places in case it is not an integer places = Math.floor(places); // Pad return value with leading 0s (zeros) if necessary (using // Underscore.string) return (places >= result.length) ? REPT('0', places - result.length) + result : error.num; } }; return exports; })(); jexcel.methods.financial = (function() { var exports = {}; function validDate(d) { return d && d.getTime && !isNaN(d.getTime()); } function ensureDate(d) { return (d instanceof Date)?d:new Date(d); } exports.ACCRINT = function(issue, first, settlement, rate, par, frequency, basis) { // Return error if either date is invalid issue = ensureDate(issue); first = ensureDate(first); settlement = ensureDate(settlement); if (!validDate(issue) || !validDate(first) || !validDate(settlement)) { return '#VALUE!'; } // Return error if either rate or par are lower than or equal to zero if (rate <= 0 || par <= 0) { return '#NUM!'; } // Return error if frequency is neither 1, 2, or 4 if ([1, 2, 4].indexOf(frequency) === -1) { return '#NUM!'; } // Return error if basis is neither 0, 1, 2, 3, or 4 if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { return '#NUM!'; } // Return error if settlement is before or equal to issue if (settlement <= issue) { return '#NUM!'; } // Set default values par = par || 0; basis = basis || 0; // Compute accrued interest return par * rate * YEARFRAC(issue, settlement, basis); }; exports.ACCRINTM = null; exports.AMORDEGRC = null; exports.AMORLINC = null; exports.COUPDAYBS = null; exports.COUPDAYS = null; exports.COUPDAYSNC = null; exports.COUPNCD = null; exports.COUPNUM = null; exports.COUPPCD = null; exports.CUMIPMT = function(rate, periods, value, start, end, type) { // Credits: algorithm inspired by Apache OpenOffice // Credits: Hannes Stiebitzhofer for the translations of function and // variable names // Requires exports.FV() and exports.PMT() from exports.js // [http://stoic.com/exports/] rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); value = utils.parseNumber(value); if (utils.anyIsError(rate, periods, value)) { return error.value; } // Return error if either rate, periods, or value are lower than or // equal to zero if (rate <= 0 || periods <= 0 || value <= 0) { return error.num; } // Return error if start < 1, end < 1, or start > end if (start < 1 || end < 1 || start > end) { return error.num; } // Return error if type is neither 0 nor 1 if (type !== 0 && type !== 1) { return error.num; } // Compute cumulative interest var payment = exports.PMT(rate, periods, value, 0, type); var interest = 0; if (start === 1) { if (type === 0) { interest = -value; start++; } } for (var i = start; i <= end; i++) { if (type === 1) { interest += exports.FV(rate, i - 2, payment, value, 1) - payment; } else { interest += exports.FV(rate, i - 1, payment, value, 0); } } interest *= rate; // Return cumulative interest return interest; }; exports.CUMPRINC = function(rate, periods, value, start, end, type) { // Credits: algorithm inspired by Apache OpenOffice // Credits: Hannes Stiebitzhofer for the translations of function and // variable names rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); value = utils.parseNumber(value); if (utils.anyIsError(rate, periods, value)) { return error.value; } // Return error if either rate, periods, or value are lower than or // equal to zero if (rate <= 0 || periods <= 0 || value <= 0) { return error.num; } // Return error if start < 1, end < 1, or start > end if (start < 1 || end < 1 || start > end) { return error.num; } // Return error if type is neither 0 nor 1 if (type !== 0 && type !== 1) { return error.num; } // Compute cumulative principal var payment = exports.PMT(rate, periods, value, 0, type); var principal = 0; if (start === 1) { if (type === 0) { principal = payment + value * rate; } else { principal = payment; } start++; } for (var i = start; i <= end; i++) { if (type > 0) { principal += payment - (exports.FV(rate, i - 2, payment, value, 1) - payment) * rate; } else { principal += payment - exports.FV(rate, i - 1, payment, value, 0) * rate; } } // Return cumulative principal return principal; }; exports.DB = function(cost, salvage, life, period, month) { // Initialize month month = (month === undefined) ? 12 : month; cost = utils.parseNumber(cost); salvage = utils.parseNumber(salvage); life = utils.parseNumber(life); period = utils.parseNumber(period); month = utils.parseNumber(month); if (utils.anyIsError(cost, salvage, life, period, month)) { return error.value; } // Return error if any of the parameters is negative if (cost < 0 || salvage < 0 || life < 0 || period < 0) { return error.num; } // Return error if month is not an integer between 1 and 12 if ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].indexOf(month) === -1) { return error.num; } // Return error if period is greater than life if (period > life) { return error.num; } // Return 0 (zero) if salvage is greater than or equal to cost if (salvage >= cost) { return 0; } // Rate is rounded to three decimals places var rate = (1 - Math.pow(salvage / cost, 1 / life)).toFixed(3); // Compute initial depreciation var initial = cost * rate * month / 12; // Compute total depreciation var total = initial; var current = 0; var ceiling = (period === life) ? life - 1 : period; for (var i = 2; i <= ceiling; i++) { current = (cost - total) * rate; total += current; } // Depreciation for the first and last periods are special cases if (period === 1) { // First period return initial; } else if (period === life) { // Last period return (cost - total) * rate; } else { return current; } }; exports.DDB = function(cost, salvage, life, period, factor) { // Initialize factor factor = (factor === undefined) ? 2 : factor; cost = utils.parseNumber(cost); salvage = utils.parseNumber(salvage); life = utils.parseNumber(life); period = utils.parseNumber(period); factor = utils.parseNumber(factor); if (utils.anyIsError(cost, salvage, life, period, factor)) { return error.value; } // Return error if any of the parameters is negative or if factor is // null if (cost < 0 || salvage < 0 || life < 0 || period < 0 || factor <= 0) { return error.num; } // Return error if period is greater than life if (period > life) { return error.num; } // Return 0 (zero) if salvage is greater than or equal to cost if (salvage >= cost) { return 0; } // Compute depreciation var total = 0; var current = 0; for (var i = 1; i <= period; i++) { current = Math.min((cost - total) * (factor / life), (cost - salvage - total)); total += current; } // Return depreciation return current; }; exports.DISC = null; exports.DOLLARDE = function(dollar, fraction) { // Credits: algorithm inspired by Apache OpenOffice dollar = utils.parseNumber(dollar); fraction = utils.parseNumber(fraction); if (utils.anyIsError(dollar, fraction)) { return error.value; } // Return error if fraction is negative if (fraction < 0) { return error.num; } // Return error if fraction is greater than or equal to 0 and less than // 1 if (fraction >= 0 && fraction < 1) { return error.div0; } // Truncate fraction if it is not an integer fraction = parseInt(fraction, 10); // Compute integer part var result = parseInt(dollar, 10); // Add decimal part result += (dollar % 1) * Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN10)) / fraction; // Round result var power = Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN2) + 1); result = Math.round(result * power) / power; // Return converted dollar price return result; }; exports.DOLLARFR = function(dollar, fraction) { // Credits: algorithm inspired by Apache OpenOffice dollar = utils.parseNumber(dollar); fraction = utils.parseNumber(fraction); if (utils.anyIsError(dollar, fraction)) { return error.value; } // Return error if fraction is negative if (fraction < 0) { return error.num; } // Return error if fraction is greater than or equal to 0 and less than // 1 if (fraction >= 0 && fraction < 1) { return error.div0; } // Truncate fraction if it is not an integer fraction = parseInt(fraction, 10); // Compute integer part var result = parseInt(dollar, 10); // Add decimal part result += (dollar % 1) * Math.pow(10, -Math.ceil(Math.log(fraction) / Math.LN10)) * fraction; // Return converted dollar price return result; }; exports.DURATION = null; exports.EFFECT = function(rate, periods) { rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); if (utils.anyIsError(rate, periods)) { return error.value; } // Return error if rate <=0 or periods < 1 if (rate <= 0 || periods < 1) { return error.num; } // Truncate periods if it is not an integer periods = parseInt(periods, 10); // Return effective annual interest rate return Math.pow(1 + rate / periods, periods) - 1; }; exports.FV = function(rate, periods, payment, value, type) { // Credits: algorithm inspired by Apache OpenOffice value = value || 0; type = type || 0; rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); payment = utils.parseNumber(payment); value = utils.parseNumber(value); type = utils.parseNumber(type); if (utils.anyIsError(rate, periods, payment, value, type)) { return error.value; } // Return future value var result; if (rate === 0) { result = value + payment * periods; } else { var term = Math.pow(1 + rate, periods); if (type === 1) { result = value * term + payment * (1 + rate) * (term - 1) / rate; } else { result = value * term + payment * (term - 1) / rate; } } return -result; }; exports.FVSCHEDULE = function(principal, schedule) { principal = utils.parseNumber(principal); schedule = utils.parseNumberArray(utils.flatten(schedule)); if (utils.anyIsError(principal, schedule)) { return error.value; } var n = schedule.length; var future = principal; // Apply all interests in schedule for (var i = 0; i < n; i++) { // Apply scheduled interest future *= 1 + schedule[i]; } // Return future value return future; }; exports.INTRATE = null; exports.IPMT = function(rate, period, periods, present, future, type) { // Credits: algorithm inspired by Apache OpenOffice future = future || 0; type = type || 0; rate = utils.parseNumber(rate); period = utils.parseNumber(period); periods = utils.parseNumber(periods); present = utils.parseNumber(present); future = utils.parseNumber(future); type = utils.parseNumber(type); if (utils.anyIsError(rate, period, periods, present, future, type)) { return error.value; } // Compute payment var payment = exports.PMT(rate, periods, present, future, type); // Compute interest var interest; if (period === 1) { if (type === 1) { interest = 0; } else { interest = -present; } } else { if (type === 1) { interest = exports.FV(rate, period - 2, payment, present, 1) - payment; } else { interest = exports.FV(rate, period - 1, payment, present, 0); } } // Return interest return interest * rate; }; exports.IRR = function(values, guess) { // Credits: algorithm inspired by Apache OpenOffice guess = guess || 0; values = utils.parseNumberArray(utils.flatten(values)); guess = utils.parseNumber(guess); if (utils.anyIsError(values, guess)) { return error.value; } // Calculates the resulting amount var irrResult = function(values, dates, rate) { var r = rate + 1; var result = values[0]; for (var i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, (dates[i] - dates[0]) / 365); } return result; }; // Calculates the first derivation var irrResultDeriv = function(values, dates, rate) { var r = rate + 1; var result = 0; for (var i = 1; i < values.length; i++) { var frac = (dates[i] - dates[0]) / 365; result -= frac * values[i] / Math.pow(r, frac + 1); } return result; }; // Initialize dates and check that values contains at least one positive // value and one negative value var dates = []; var positive = false; var negative = false; for (var i = 0; i < values.length; i++) { dates[i] = (i === 0) ? 0 : dates[i - 1] + 365; if (values[i] > 0) { positive = true; } if (values[i] < 0) { negative = true; } } // Return error if values does not contain at least one positive value // and one negative value if (!positive || !negative) { return error.num; } // Initialize guess and resultRate guess = (guess === undefined) ? 0.1 : guess; var resultRate = guess; // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Implement Newton's method var newRate, epsRate, resultValue; var contLoop = true; do { resultValue = irrResult(values, dates, resultRate); newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while (contLoop); // Return internal rate of return return resultRate; }; exports.ISPMT = function(rate, period, periods, value) { rate = utils.parseNumber(rate); period = utils.parseNumber(period); periods = utils.parseNumber(periods); value = utils.parseNumber(value); if (utils.anyIsError(rate, period, periods, value)) { return error.value; } // Return interest return value * rate * (period / periods - 1); }; exports.MDURATION = null; exports.MIRR = function(values, finance_rate, reinvest_rate) { values = utils.parseNumberArray(utils.flatten(values)); finance_rate = utils.parseNumber(finance_rate); reinvest_rate = utils.parseNumber(reinvest_rate); if (utils.anyIsError(values, finance_rate, reinvest_rate)) { return error.value; } // Initialize number of values var n = values.length; // Lookup payments (negative values) and incomes (positive values) var payments = []; var incomes = []; for (var i = 0; i < n; i++) { if (values[i] < 0) { payments.push(values[i]); } else { incomes.push(values[i]); } } // Return modified internal rate of return var num = -exports.NPV(reinvest_rate, incomes) * Math.pow(1 + reinvest_rate, n - 1); var den = exports.NPV(finance_rate, payments) * (1 + finance_rate); return Math.pow(num / den, 1 / (n - 1)) - 1; }; exports.NOMINAL = function(rate, periods) { rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); if (utils.anyIsError(rate, periods)) { return error.value; } // Return error if rate <=0 or periods < 1 if (rate <= 0 || periods < 1) { return error.num; } // Truncate periods if it is not an integer periods = parseInt(periods, 10); // Return nominal annual interest rate return (Math.pow(rate + 1, 1 / periods) - 1) * periods; }; exports.NPER = function(rate, payment, present, future, type) { type = (type === undefined) ? 0 : type; future = (future === undefined) ? 0 : future; rate = utils.parseNumber(rate); payment = utils.parseNumber(payment); present = utils.parseNumber(present); future = utils.parseNumber(future); type = utils.parseNumber(type); if (utils.anyIsError(rate, payment, present, future, type)) { return error.value; } // Return number of periods var num = payment * (1 + rate * type) - future * rate; var den = (present * rate + payment * (1 + rate * type)); return Math.log(num / den) / Math.log(1 + rate); }; exports.NPV = function() { var args = utils.parseNumberArray(utils.flatten(arguments)); if (args instanceof Error) { return args; } // Lookup rate var rate = args[0]; // Initialize net present value var value = 0; // Loop on all values for (var j = 1; j < args.length; j++) { value += args[j] / Math.pow(1 + rate, j); } // Return net present value return value; }; exports.ODDFPRICE = null; exports.ODDFYIELD = null; exports.ODDLPRICE = null; exports.ODDLYIELD = null; exports.PDURATION = function(rate, present, future) { rate = utils.parseNumber(rate); present = utils.parseNumber(present); future = utils.parseNumber(future); if (utils.anyIsError(rate, present, future)) { return error.value; } // Return error if rate <=0 if (rate <= 0) { return error.num; } // Return number of periods return (Math.log(future) - Math.log(present)) / Math.log(1 + rate); }; exports.PMT = function(rate, periods, present, future, type) { // Credits: algorithm inspired by Apache OpenOffice future = future || 0; type = type || 0; rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); present = utils.parseNumber(present); future = utils.parseNumber(future); type = utils.parseNumber(type); if (utils.anyIsError(rate, periods, present, future, type)) { return error.value; } // Return payment var result; if (rate === 0) { result = (present + future) / periods; } else { var term = Math.pow(1 + rate, periods); if (type === 1) { result = (future * rate / (term - 1) + present * rate / (1 - 1 / term)) / (1 + rate); } else { result = future * rate / (term - 1) + present * rate / (1 - 1 / term); } } return -result; }; exports.PPMT = function(rate, period, periods, present, future, type) { future = future || 0; type = type || 0; rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); present = utils.parseNumber(present); future = utils.parseNumber(future); type = utils.parseNumber(type); if (utils.anyIsError(rate, periods, present, future, type)) { return error.value; } return exports.PMT(rate, periods, present, future, type) - exports.IPMT(rate, period, periods, present, future, type); }; exports.PRICE = null; exports.PRICEDISC = null; exports.PRICEMAT = null; exports.PV = function(rate, periods, payment, future, type) { future = future || 0; type = type || 0; rate = utils.parseNumber(rate); periods = utils.parseNumber(periods); payment = utils.parseNumber(payment); future = utils.parseNumber(future); type = utils.parseNumber(type); if (utils.anyIsError(rate, periods, payment, future, type)) { return error.value; } // Return present value if (rate === 0) { return -payment * periods - future; } else { return (((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) / Math.pow(1 + rate, periods); } }; exports.RATE = function(periods, payment, present, future, type, guess) { // Credits: rabugento guess = (guess === undefined) ? 0.01 : guess; future = (future === undefined) ? 0 : future; type = (type === undefined) ? 0 : type; periods = utils.parseNumber(periods); payment = utils.parseNumber(payment); present = utils.parseNumber(present); future = utils.parseNumber(future); type = utils.parseNumber(type); guess = utils.parseNumber(guess); if (utils.anyIsError(periods, payment, present, future, type, guess)) { return error.value; } // Set maximum epsilon for end of iteration var epsMax = 1e-6; // Set maximum number of iterations var iterMax = 100; var iter = 0; var close = false; var rate = guess; while (iter < iterMax && !close) { var t1 = Math.pow(rate + 1, periods); var t2 = Math.pow(rate + 1, periods - 1); var f1 = future + t1 * present + payment * (t1 - 1) * (rate * type + 1) / rate; var f2 = periods * t2 * present - payment * (t1 - 1) *(rate * type + 1) / Math.pow(rate,2); var f3 = periods * payment * t2 * (rate * type + 1) / rate + payment * (t1 - 1) * type / rate; var newRate = rate - f1 / (f2 + f3); if (Math.abs(newRate - rate) < epsMax) close = true; iter++ rate = newRate; } if (!close) return Number.NaN + rate; return rate; }; // TODO exports.RECEIVED = null; exports.RRI = function(periods, present, future) { periods = utils.parseNumber(periods); present = utils.parseNumber(present); future = utils.parseNumber(future); if (utils.anyIsError(periods, present, future)) { return error.value; } // Return error if periods or present is equal to 0 (zero) if (periods === 0 || present === 0) { return error.num; } // Return equivalent interest rate return Math.pow(future / present, 1 / periods) - 1; }; exports.SLN = function(cost, salvage, life) { cost = utils.parseNumber(cost); salvage = utils.parseNumber(salvage); life = utils.parseNumber(life); if (utils.anyIsError(cost, salvage, life)) { return error.value; } // Return error if life equal to 0 (zero) if (life === 0) { return error.num; } // Return straight-line depreciation return (cost - salvage) / life; }; exports.SYD = function(cost, salvage, life, period) { // Return error if any of the parameters is not a number cost = utils.parseNumber(cost); salvage = utils.parseNumber(salvage); life = utils.parseNumber(life); period = utils.parseNumber(period); if (utils.anyIsError(cost, salvage, life, period)) { return error.value; } // Return error if life equal to 0 (zero) if (life === 0) { return error.num; } // Return error if period is lower than 1 or greater than life if (period < 1 || period > life) { return error.num; } // Truncate period if it is not an integer period = parseInt(period, 10); // Return straight-line depreciation return ((cost - salvage) * (life - period + 1) * 2) / (life * (life + 1)); }; exports.TBILLEQ = function(settlement, maturity, discount) { settlement = utils.parseDate(settlement); maturity = utils.parseDate(maturity); discount = utils.parseNumber(discount); if (utils.anyIsError(settlement, maturity, discount)) { return error.value; } // Return error if discount is lower than or equal to zero if (discount <= 0) { return error.num; } // Return error if settlement is greater than maturity if (settlement > maturity) { return error.num; } // Return error if maturity is more than one year after settlement if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) { return error.num; } // Return bond-equivalent yield return (365 * discount) / (360 - discount * DAYS360(settlement, maturity, false)); }; exports.TBILLPRICE = function(settlement, maturity, discount) { settlement = utils.parseDate(settlement); maturity = utils.parseDate(maturity); discount = utils.parseNumber(discount); if (utils.anyIsError(settlement, maturity, discount)) { return error.value; } // Return error if discount is lower than or equal to zero if (discount <= 0) { return error.num; } // Return error if settlement is greater than maturity if (settlement > maturity) { return error.num; } // Return error if maturity is more than one year after settlement if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) { return error.num; } // Return bond-equivalent yield return 100 * (1 - discount * DAYS360(settlement, maturity, false) / 360); }; exports.TBILLYIELD = function(settlement, maturity, price) { settlement = utils.parseDate(settlement); maturity = utils.parseDate(maturity); price = utils.parseNumber(price); if (utils.anyIsError(settlement, maturity, price)) { return error.value; } // Return error if price is lower than or equal to zero if (price <= 0) { return error.num; } // Return error if settlement is greater than maturity if (settlement > maturity) { return error.num; } // Return error if maturity is more than one year after settlement if (maturity - settlement > 365 * 24 * 60 * 60 * 1000) { return error.num; } // Return bond-equivalent yield return (100 - price) * 360 / (price * DAYS360(settlement, maturity, false)); }; exports.VDB = null; exports.XIRR = function(values, dates, guess) { // Credits: algorithm inspired by Apache OpenOffice values = utils.parseNumberArray(utils.flatten(values)); dates = utils.parseDateArray(utils.flatten(dates)); guess = utils.parseNumber(guess); if (utils.anyIsError(values, dates, guess)) { return error.value; } // Calculates the resulting amount var irrResult = function(values, dates, rate) { var r = rate + 1; var result = values[0]; for (var i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, DAYS(dates[i], dates[0]) / 365); } return result; }; // Calculates the first derivation var irrResultDeriv = function(values, dates, rate) { var r = rate + 1; var result = 0; for (var i = 1; i < values.length; i++) { var frac = DAYS(dates[i], dates[0]) / 365; result -= frac * values[i] / Math.pow(r, frac + 1); } return result; }; // Check that values contains at least one positive value and one // negative value var positive = false; var negative = false; for (var i = 0; i < values.length; i++) { if (values[i] > 0) { positive = true; } if (values[i] < 0) { negative = true; } } // Return error if values does not contain at least one positive value // and one negative value if (!positive || !negative) { return error.num; } // Initialize guess and resultRate guess = guess || 0.1; var resultRate = guess; // Set maximum epsilon for end of iteration var epsMax = 1e-10; // Implement Newton's method var newRate, epsRate, resultValue; var contLoop = true; do { resultValue = irrResult(values, dates, resultRate); newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); epsRate = Math.abs(newRate - resultRate); resultRate = newRate; contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); } while (contLoop); // Return internal rate of return return resultRate; }; exports.XNPV = function(rate, values, dates) { rate = utils.parseNumber(rate); values = utils.parseNumberArray(utils.flatten(values)); dates = utils.parseDateArray(utils.flatten(dates)); if (utils.anyIsError(rate, values, dates)) { return error.value; } var result = 0; for (var i = 0; i < values.length; i++) { result += values[i] / Math.pow(1 + rate, DAYS(dates[i], dates[0]) / 365); } return result; }; exports.YIELD = null; exports.YIELDDISC = null; exports.YIELDMAT = null; return exports; })(); jexcel.methods.information = (function() { var exports = {}; exports.CELL = null; exports.ERROR = {}; exports.ERROR.TYPE = function(error_val) { switch (error_val) { case error.nil: return 1; case error.div0: return 2; case error.value: return 3; case error.ref: return 4; case error.name: return 5; case error.num: return 6; case error.na: return 7; case error.data: return 8; } return error.na; }; exports.INFO = null; exports.ISBLANK = function(value) { return value === null; }; exports.ISBINARY = function (number) { return (/^[01]{1,10}$/).test(number); }; exports.ISERR = function(value) { return ([error.value, error.ref, error.div0, error.num, error.name, error.nil]).indexOf(value) >= 0 || (typeof value === 'number' && (isNaN(value) || !isFinite(value))); }; exports.ISERROR = function(value) { return exports.ISERR(value) || value === error.na; }; exports.ISEVEN = function(number) { return (Math.floor(Math.abs(number)) & 1) ? false : true; }; // TODO exports.ISFORMULA = null; exports.ISLOGICAL = function(value) { return value === true || value === false; }; exports.ISNA = function(value) { return value === error.na; }; exports.ISNONTEXT = function(value) { return typeof(value) !== 'string'; }; exports.ISNUMBER = function(value) { return typeof(value) === 'number' && !isNaN(value) && isFinite(value); }; exports.ISODD = function(number) { return (Math.floor(Math.abs(number)) & 1) ? true : false; }; exports.ISREF = null; exports.ISTEXT = function(value) { return typeof(value) === 'string'; }; exports.N = function(value) { if (this.ISNUMBER(value)) { return value; } if (value instanceof Date) { return value.getTime(); } if (value === true) { return 1; } if (value === false) { return 0; } if (this.ISERROR(value)) { return value; } return 0; }; exports.NA = function() { return error.na; }; exports.SHEET = null; exports.SHEETS = null; exports.TYPE = function(value) { if (this.ISNUMBER(value)) { return 1; } if (this.ISTEXT(value)) { return 2; } if (this.ISLOGICAL(value)) { return 4; } if (this.ISERROR(value)) { return 16; } if (Array.isArray(value)) { return 64; } }; return exports; })(); jexcel.methods.logical = (function() { var exports = {}; exports.AND = function() { var args = utils.flatten(arguments); var result = true; for (var i = 0; i < args.length; i++) { if (!args[i]) { result = false; } } return result; }; exports.CHOOSE = function() { if (arguments.length < 2) { return error.na; } var index = arguments[0]; if (index < 1 || index > 254) { return error.value; } if (arguments.length < index + 1) { return error.value; } return arguments[index]; }; exports.FALSE = function() { return false; }; exports.IF = function(test, then_value, otherwise_value) { return test ? then_value : otherwise_value; }; exports.IFERROR = function(value, valueIfError) { if (ISERROR(value)) { return valueIfError; } return value; }; exports.IFNA = function(value, value_if_na) { return value === error.na ? value_if_na : value; }; exports.NOT = function(logical) { return !logical; }; exports.OR = function() { var args = utils.flatten(arguments); var result = false; for (var i = 0; i < args.length; i++) { if (args[i]) { result = true; } } return result; }; exports.TRUE = function() { return true; }; exports.XOR = function() { var args = utils.flatten(arguments); var result = 0; for (var i = 0; i < args.length; i++) { if (args[i]) { result++; } } return (Math.floor(Math.abs(result)) & 1) ? true : false; }; exports.SWITCH = function() { var result; if (arguments.length > 0) { var targetValue = arguments[0]; var argc = arguments.length - 1; var switchCount = Math.floor(argc / 2); var switchSatisfied = false; var defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1]; if (switchCount) { for (var index = 0; index < switchCount; index++) { if (targetValue === arguments[index * 2 + 1]) { result = arguments[index * 2 + 2]; switchSatisfied = true; break; } } } if (!switchSatisfied && defaultClause) { result = defaultClause; } } return result; }; return exports; })(); jexcel.methods.math = (function() { var exports = {}; exports.ABS = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.abs(utils.parseNumber(number)); }; exports.ACOS = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.acos(number); }; exports.ACOSH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.log(number + Math.sqrt(number * number - 1)); }; exports.ACOT = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.atan(1 / number); }; exports.ACOTH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return 0.5 * Math.log((number + 1) / (number - 1)); }; exports.AGGREGATE = null exports.ARABIC = function(text) { // Credits: Rafa? Kukawski if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) { return error.value; } var r = 0; text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function(i) { r += { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }[i]; }); return r; }; exports.ASIN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.asin(number); }; exports.ASINH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.log(number + Math.sqrt(number * number + 1)); }; exports.ATAN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.atan(number); }; exports.ATAN2 = function(number_x, number_y) { number_x = utils.parseNumber(number_x); number_y = utils.parseNumber(number_y); if (utils.anyIsError(number_x, number_y)) { return error.value; } return Math.atan2(number_x, number_y); }; exports.ATANH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.log((1 + number) / (1 - number)) / 2; }; exports.BASE = function(number, radix, min_length) { min_length = min_length || 0; number = utils.parseNumber(number); radix = utils.parseNumber(radix); min_length = utils.parseNumber(min_length); if (utils.anyIsError(number, radix, min_length)) { return error.value; } min_length = (min_length === undefined) ? 0 : min_length; var result = number.toString(radix); return new Array(Math.max(min_length + 1 - result.length, 0)).join('0') + result; }; exports.CEILING = function(number, significance, mode) { significance = (significance === undefined) ? 1 : significance; mode = (mode === undefined) ? 0 : mode; number = utils.parseNumber(number); significance = utils.parseNumber(significance); mode = utils.parseNumber(mode); if (utils.anyIsError(number, significance, mode)) { return error.value; } if (significance === 0) { return 0; } significance = Math.abs(significance); if (number >= 0) { return Math.ceil(number / significance) * significance; } else { if (mode === 0) { return -1 * Math.floor(Math.abs(number) / significance) * significance; } else { return -1 * Math.ceil(Math.abs(number) / significance) * significance; } } }; exports.CEILING.MATH = exports.CEILING; exports.CEILING.PRECISE = exports.CEILING; exports.COMBIN = function(number, number_chosen) { number = utils.parseNumber(number); number_chosen = utils.parseNumber(number_chosen); if (utils.anyIsError(number, number_chosen)) { return error.value; } return exports.FACT(number) / (exports.FACT(number_chosen) * exports.FACT(number - number_chosen)); }; exports.COMBINA = function(number, number_chosen) { number = utils.parseNumber(number); number_chosen = utils.parseNumber(number_chosen); if (utils.anyIsError(number, number_chosen)) { return error.value; } return (number === 0 && number_chosen === 0) ? 1 : exports.COMBIN(number + number_chosen - 1, number - 1); }; exports.COS = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.cos(number); }; exports.COSH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return (Math.exp(number) + Math.exp(-number)) / 2; }; exports.COT = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return 1 / Math.tan(number); }; exports.COTH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } var e2 = Math.exp(2 * number); return (e2 + 1) / (e2 - 1); }; exports.CSC = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return 1 / Math.sin(number); }; exports.CSCH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return 2 / (Math.exp(number) - Math.exp(-number)); }; exports.DECIMAL = function(number, radix) { if (arguments.length < 1) { return error.value; } return parseInt(number, radix); }; exports.DEGREES = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return number * 180 / Math.PI; }; exports.EVEN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return exports.CEILING(number, -2, -1); }; exports.EXP = Math.exp; var MEMOIZED_FACT = []; exports.FACT = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } var n = Math.floor(number); if (n === 0 || n === 1) { return 1; } else if (MEMOIZED_FACT[n] > 0) { return MEMOIZED_FACT[n]; } else { MEMOIZED_FACT[n] = exports.FACT(n - 1) * n; return MEMOIZED_FACT[n]; } }; exports.FACTDOUBLE = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } var n = Math.floor(number); if (n <= 0) { return 1; } else { return n * exports.FACTDOUBLE(n - 2); } }; exports.FLOOR = function(number, significance, mode) { significance = (significance === undefined) ? 1 : significance; mode = (mode === undefined) ? 0 : mode; number = utils.parseNumber(number); significance = utils.parseNumber(significance); mode = utils.parseNumber(mode); if (utils.anyIsError(number, significance, mode)) { return error.value; } if (significance === 0) { return 0; } significance = Math.abs(significance); if (number >= 0) { return Math.floor(number / significance) * significance; } else { if (mode === 0) { return -1 * Math.ceil(Math.abs(number) / significance) * significance; } else { return -1 * Math.floor(Math.abs(number) / significance) * significance; } } }; exports.FLOOR.MATH = exports.FLOOR; exports.GCD = null; exports.INT = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.floor(number); }; exports.LCM = function() { // Credits: Jonas Raoni Soares Silva var o = utils.parseNumberArray(utils.flatten(arguments)); if (o instanceof Error) { return o; } for (var i, j, n, d, r = 1; (n = o.pop()) !== undefined;) { while (n > 1) { if (n % 2) { for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2) { //empty } d = (i <= j) ? i : n; } else { d = 2; } for (n /= d, r *= d, i = o.length; i; (o[--i] % d) === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) { //empty } } } return r; }; exports.LN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.log(number); }; exports.LOG = function(number, base) { number = utils.parseNumber(number); base = (base === undefined) ? 10 : utils.parseNumber(base); if (utils.anyIsError(number, base)) { return error.value; } return Math.log(number) / Math.log(base); }; exports.LOG10 = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.log(number) / Math.log(10); }; exports.MDETERM = null; exports.MINVERSE = null; exports.MMULT = null; exports.MOD = function(dividend, divisor) { dividend = utils.parseNumber(dividend); divisor = utils.parseNumber(divisor); if (utils.anyIsError(dividend, divisor)) { return error.value; } if (divisor === 0) { return error.div0; } var modulus = Math.abs(dividend % divisor); return (divisor > 0) ? modulus : -modulus; }; exports.MROUND = function(number, multiple) { number = utils.parseNumber(number); multiple = utils.parseNumber(multiple); if (utils.anyIsError(number, multiple)) { return error.value; } if (number * multiple < 0) { return error.num; } return Math.round(number / multiple) * multiple; }; exports.MULTINOMIAL = function() { var args = utils.parseNumberArray(utils.flatten(arguments)); if (args instanceof Error) { return args; } var sum = 0; var divisor = 1; for (var i = 0; i < args.length; i++) { sum += args[i]; divisor *= exports.FACT(args[i]); } return exports.FACT(sum) / divisor; }; exports.MUNIT = null; exports.ODD = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } var temp = Math.ceil(Math.abs(number)); temp = (temp & 1) ? temp : temp + 1; return (number > 0) ? temp : -temp; }; exports.PI = function() { return Math.PI; }; exports.POWER = function(number, power) { number = utils.parseNumber(number); power = utils.parseNumber(power); if (utils.anyIsError(number, power)) { return error.value; } var result = Math.pow(number, power); if (isNaN(result)) { return error.num; } return result; }; exports.PRODUCT = function() { var args = utils.parseNumberArray(utils.flatten(arguments)); if (args instanceof Error) { return args; } var result = 1; for (var i = 0; i < args.length; i++) { result *= args[i]; } return result; }; exports.QUOTIENT = function(numerator, denominator) { numerator = utils.parseNumber(numerator); denominator = utils.parseNumber(denominator); if (utils.anyIsError(numerator, denominator)) { return error.value; } return parseInt(numerator / denominator, 10); }; exports.RADIANS = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return number * Math.PI / 180; }; exports.RAND = function() { return Math.random(); }; exports.RANDBETWEEN = function(bottom, top) { bottom = utils.parseNumber(bottom); top = utils.parseNumber(top); if (utils.anyIsError(bottom, top)) { return error.value; } // Creative Commons Attribution 3.0 License // Copyright (c) 2012 eqcode return bottom + Math.ceil((top - bottom + 1) * Math.random()) - 1; }; exports.ROMAN = null; exports.ROUND = function(number, digits) { number = utils.parseNumber(number); digits = utils.parseNumber(digits); if (utils.anyIsError(number, digits)) { return error.value; } return Math.round(number * Math.pow(10, digits)) / Math.pow(10, digits); }; exports.ROUNDDOWN = function(number, digits) { number = utils.parseNumber(number); digits = utils.parseNumber(digits); if (utils.anyIsError(number, digits)) { return error.value; } var sign = (number > 0) ? 1 : -1; return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; exports.ROUNDUP = function(number, digits) { number = utils.parseNumber(number); digits = utils.parseNumber(digits); if (utils.anyIsError(number, digits)) { return error.value; } var sign = (number > 0) ? 1 : -1; return sign * (Math.ceil(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; exports.SEC = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return 1 / Math.cos(number); }; exports.SECH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return 2 / (Math.exp(number) + Math.exp(-number)); }; exports.SERIESSUM = function(x, n, m, coefficients) { x = utils.parseNumber(x); n = utils.parseNumber(n); m = utils.parseNumber(m); coefficients = utils.parseNumberArray(coefficients); if (utils.anyIsError(x, n, m, coefficients)) { return error.value; } var result = coefficients[0] * Math.pow(x, n); for (var i = 1; i < coefficients.length; i++) { result += coefficients[i] * Math.pow(x, n + i * m); } return result; }; exports.SIGN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } if (number < 0) { return -1; } else if (number === 0) { return 0; } else { return 1; } }; exports.SIN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.sin(number); }; exports.SINH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return (Math.exp(number) - Math.exp(-number)) / 2; }; exports.SQRT = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } if (number < 0) { return error.num; } return Math.sqrt(number); }; exports.SQRTPI = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.sqrt(number * Math.PI); }; exports.SUBTOTAL = null; exports.ADD = function (num1, num2) { if (arguments.length !== 2) { return error.na; } num1 = utils.parseNumber(num1); num2 = utils.parseNumber(num2); if (utils.anyIsError(num1, num2)) { return error.value; } return num1 + num2; }; exports.MINUS = function (num1, num2) { if (arguments.length !== 2) { return error.na; } num1 = utils.parseNumber(num1); num2 = utils.parseNumber(num2); if (utils.anyIsError(num1, num2)) { return error.value; } return num1 - num2; }; exports.DIVIDE = function (dividend, divisor) { if (arguments.length !== 2) { return error.na; } dividend = utils.parseNumber(dividend); divisor = utils.parseNumber(divisor); if (utils.anyIsError(dividend, divisor)) { return error.value; } if (divisor === 0) { return error.div0; } return dividend / divisor; }; exports.MULTIPLY = function (factor1, factor2) { if (arguments.length !== 2) { return error.na; } factor1 = utils.parseNumber(factor1); factor2 = utils.parseNumber(factor2); if (utils.anyIsError(factor1, factor2)) { return error.value; } return factor1 * factor2; }; exports.GTE = function (num1, num2) { if (arguments.length !== 2) { return error.na; } num1 = utils.parseNumber(num1); num2 = utils.parseNumber(num2); if (utils.anyIsError(num1, num2)) { return error.error; } return num1 >= num2; }; exports.LT = function (num1, num2) { if (arguments.length !== 2) { return error.na; } num1 = utils.parseNumber(num1); num2 = utils.parseNumber(num2); if (utils.anyIsError(num1, num2)) { return error.error; } return num1 < num2; }; exports.LTE = function (num1, num2) { if (arguments.length !== 2) { return error.na; } num1 = utils.parseNumber(num1); num2 = utils.parseNumber(num2); if (utils.anyIsError(num1, num2)) { return error.error; } return num1 <= num2; }; exports.EQ = function (value1, value2) { if (arguments.length !== 2) { return error.na; } return value1 === value2; }; exports.NE = function (value1, value2) { if (arguments.length !== 2) { return error.na; } return value1 !== value2; }; exports.POW = function (base, exponent) { if (arguments.length !== 2) { return error.na; } base = utils.parseNumber(base); exponent = utils.parseNumber(exponent); if (utils.anyIsError(base, exponent)) { return error.error; } return exports.POWER(base, exponent); }; exports.SUM = function() { var result = 0; var argsKeys = Object.keys(arguments); for (var i = 0; i < argsKeys.length; ++i) { var elt = arguments[argsKeys[i]]; if (typeof elt === 'number') { result += elt; } else if (typeof elt === 'string') { var parsed = parseFloat(elt); !isNaN(parsed) && (result += parsed); } else if (Array.isArray(elt)) { result += exports.SUM.apply(null, elt); } } return result; }; exports.SUMIF = function(range, criteria) { range = utils.parseNumberArray(utils.flatten(range)); if (range instanceof Error) { return range; } var result = 0; for (var i = 0; i < range.length; i++) { result += (eval(range[i] + criteria)) ? range[i] : 0; // jshint ignore:line } return result; }; exports.SUMIFS = function() { var args = utils.argsToArray(arguments); var range = utils.parseNumberArray(utils.flatten(args.shift())); if (range instanceof Error) { return range; } var criteria = args; var n_range_elements = range.length; var n_criterias = criteria.length; var result = 0; for (var i = 0; i < n_range_elements; i++) { var el = range[i]; var condition = ''; for (var c = 0; c < n_criterias; c++) { condition += el + criteria[c]; if (c !== n_criterias - 1) { condition += '&&'; } } if (eval(condition)) { // jshint ignore:line result += el; } } return result; }; exports.SUMPRODUCT = null; exports.SUMSQ = function() { var numbers = utils.parseNumberArray(utils.flatten(arguments)); if (numbers instanceof Error) { return numbers; } var result = 0; var length = numbers.length; for (var i = 0; i < length; i++) { result += (ISNUMBER(numbers[i])) ? numbers[i] * numbers[i] : 0; } return result; }; exports.SUMX2MY2 = function(array_x, array_y) { array_x = utils.parseNumberArray(utils.flatten(array_x)); array_y = utils.parseNumberArray(utils.flatten(array_y)); if (utils.anyIsError(array_x, array_y)) { return error.value; } var result = 0; for (var i = 0; i < array_x.length; i++) { result += array_x[i] * array_x[i] - array_y[i] * array_y[i]; } return result; }; exports.SUMX2PY2 = function(array_x, array_y) { array_x = utils.parseNumberArray(utils.flatten(array_x)); array_y = utils.parseNumberArray(utils.flatten(array_y)); if (utils.anyIsError(array_x, array_y)) { return error.value; } var result = 0; array_x = utils.parseNumberArray(utils.flatten(array_x)); array_y = utils.parseNumberArray(utils.flatten(array_y)); for (var i = 0; i < array_x.length; i++) { result += array_x[i] * array_x[i] + array_y[i] * array_y[i]; } return result; }; exports.SUMXMY2 = function(array_x, array_y) { array_x = utils.parseNumberArray(utils.flatten(array_x)); array_y = utils.parseNumberArray(utils.flatten(array_y)); if (utils.anyIsError(array_x, array_y)) { return error.value; } var result = 0; array_x = utils.flatten(array_x); array_y = utils.flatten(array_y); for (var i = 0; i < array_x.length; i++) { result += Math.pow(array_x[i] - array_y[i], 2); } return result; }; exports.TAN = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return Math.tan(number); }; exports.TANH = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } var e2 = Math.exp(2 * number); return (e2 - 1) / (e2 + 1); }; exports.TRUNC = function(number, digits) { digits = (digits === undefined) ? 0 : digits; number = utils.parseNumber(number); digits = utils.parseNumber(digits); if (utils.anyIsError(number, digits)) { return error.value; } var sign = (number > 0) ? 1 : -1; return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); }; return exports; })(); jexcel.methods.misc = (function() { var exports = {}; exports.UNIQUE = function () { var result = []; for (var i = 0; i < arguments.length; ++i) { var hasElement = false; var element = arguments[i]; // Check if we've already seen this element. for (var j = 0; j < result.length; ++j) { hasElement = result[j] === element; if (hasElement) { break; } } // If we did not find it, add it to the result. if (!hasElement) { result.push(element); } } return result; }; exports.FLATTEN = utils.flatten; exports.ARGS2ARRAY = function () { return Array.prototype.slice.call(arguments, 0); }; exports.REFERENCE = function (context, reference) { try { var path = reference.split('.'); var result = context; for (var i = 0; i < path.length; ++i) { var step = path[i]; if (step[step.length - 1] === ']') { var opening = step.indexOf('['); var index = step.substring(opening + 1, step.length - 1); result = result[step.substring(0, opening)][index]; } else { result = result[step]; } } return result; } catch (error) {} }; exports.JOIN = function (array, separator) { return array.join(separator); }; exports.NUMBERS = function () { var possibleNumbers = utils.flatten(arguments); return possibleNumbers.filter(function (el) { return typeof el === 'number'; }); }; exports.NUMERAL = null; return exports; })(); jexcel.methods.text = (function() { var exports = {}; exports.ASC = null; exports.BAHTTEXT = null; exports.CHAR = function(number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return String.fromCharCode(number); }; exports.CLEAN = function(text) { text = text || ''; var re = /[\0-\x1F]/g; return text.replace(re, ""); }; exports.CODE = function(text) { text = text || ''; return text.charCodeAt(0); }; exports.CONCATENATE = function() { var args = utils.flatten(arguments); var trueFound = 0; while ((trueFound = args.indexOf(true)) > -1) { args[trueFound] = 'TRUE'; } var falseFound = 0; while ((falseFound = args.indexOf(false)) > -1) { args[falseFound] = 'FALSE'; } return args.join(''); }; exports.DBCS = null; exports.DOLLAR = null; exports.EXACT = function(text1, text2) { return text1 === text2; }; exports.FIND = function(find_text, within_text, position) { position = (position === undefined) ? 0 : position; return within_text ? within_text.indexOf(find_text, position - 1) + 1 : null; }; exports.FIXED = null; exports.HTML2TEXT = function (value) { var result = ''; if (value) { if (value instanceof Array) { value.forEach(function (line) { if (result !== '') { result += '\n'; } result += (line.replace(/<(?:.|\n)*?>/gm, '')); }); } else { result = value.replace(/<(?:.|\n)*?>/gm, ''); } } return result; }; exports.LEFT = function(text, number) { number = (number === undefined) ? 1 : number; number = utils.parseNumber(number); if (number instanceof Error || typeof text !== 'string') { return error.value; } return text ? text.substring(0, number) : null; }; exports.LEN = function(text) { if (arguments.length === 0) { return error.error; } if (typeof text === 'string') { return text ? text.length : 0; } if (text.length) { return text.length; } return error.value; }; exports.LOWER = function(text) { if (typeof text !== 'string') { return error.value; } return text ? text.toLowerCase() : text; }; exports.MID = function(text, start, number) { start = utils.parseNumber(start); number = utils.parseNumber(number); if (utils.anyIsError(start, number) || typeof text !== 'string') { return number; } var begin = start - 1; var end = begin + number; return text.substring(begin, end); }; exports.NUMBERVALUE = null; exports.PRONETIC = null; exports.PROPER = function(text) { if (text === undefined || text.length === 0) { return error.value; } if (text === true) { text = 'TRUE'; } if (text === false) { text = 'FALSE'; } if (isNaN(text) && typeof text === 'number') { return error.value; } if (typeof text === 'number') { text = '' + text; } return text.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; exports.REGEXEXTRACT = function (text, regular_expression) { var match = text.match(new RegExp(regular_expression)); return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null; }; exports.REGEXMATCH = function (text, regular_expression, full) { var match = text.match(new RegExp(regular_expression)); return full ? match : !!match; }; exports.REGEXREPLACE = function (text, regular_expression, replacement) { return text.replace(new RegExp(regular_expression), replacement); }; exports.REPLACE = function(text, position, length, new_text) { position = utils.parseNumber(position); length = utils.parseNumber(length); if (utils.anyIsError(position, length) || typeof text !== 'string' || typeof new_text !== 'string') { return error.value; } return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length); }; exports.REPT = function(text, number) { number = utils.parseNumber(number); if (number instanceof Error) { return number; } return new Array(number + 1).join(text); }; exports.RIGHT = function(text, number) { number = (number === undefined) ? 1 : number; number = utils.parseNumber(number); if (number instanceof Error) { return number; } return text ? text.substring(text.length - number) : null; }; exports.SEARCH = function(find_text, within_text, position) { var foundAt; if (typeof find_text !== 'string' || typeof within_text !== 'string') { return error.value; } position = (position === undefined) ? 0 : position; foundAt = within_text.toLowerCase().indexOf(find_text.toLowerCase(), position - 1)+1; return (foundAt === 0)?error.value:foundAt; }; exports.SPLIT = function (text, separator) { return text.split(separator); }; exports.SUBSTITUTE = function(text, old_text, new_text, occurrence) { if (!text || !old_text || !new_text) { return text; } else if (occurrence === undefined) { return text.replace(new RegExp(old_text, 'g'), new_text); } else { var index = 0; var i = 0; while (text.indexOf(old_text, index) > 0) { index = text.indexOf(old_text, index + 1); i++; if (i === occurrence) { return text.substring(0, index) + new_text + text.substring(index + old_text.length); } } } }; exports.T = function(value) { return (typeof value === "string") ? value : ''; }; exports.TEXT = null; exports.TRIM = function(text) { if (typeof text !== 'string') { return error.value; } return text.replace(/ +/g, ' ').trim(); }; exports.UNICHAR = exports.CHAR; exports.UNICODE = exports.CODE; exports.UPPER = function(text) { if (typeof text !== 'string') { return error.value; } return text.toUpperCase(); }; exports.VALUE = null; return exports; })(); jexcel.methods.stats = (function() { var exports = {}; var SQRT2PI = 2.5066282746310002; exports.AVEDEV = null; exports.AVERAGE = function() { var range = utils.numbers(utils.flatten(arguments)); var n = range.length; var sum = 0; var count = 0; for (var i = 0; i < n; i++) { sum += range[i]; count += 1; } return sum / count; }; exports.AVERAGEA = function() { var range = utils.flatten(arguments); var n = range.length; var sum = 0; var count = 0; for (var i = 0; i < n; i++) { var el = range[i]; if (typeof el === 'number') { sum += el; } if (el === true) { sum++; } if (el !== null) { count++; } } return sum / count; }; exports.AVERAGEIF = function(range, criteria, average_range) { average_range = average_range || range; range = utils.flatten(range); average_range = utils.parseNumberArray(utils.flatten(average_range)); if (average_range instanceof Error) { return average_range; } var average_count = 0; var result = 0; for (var i = 0; i < range.length; i++) { if (eval(range[i] + criteria)) { // jshint ignore:line result += average_range[i]; average_count++; } } return result / average_count; }; exports.AVERAGEIFS = null; exports.COUNT = function() { return utils.numbers(utils.flatten(arguments)).length; }; exports.COUNTA = function() { var range = utils.flatten(arguments); return range.length - exports.COUNTBLANK(range); }; exports.COUNTIN = function (range, value) { var result = 0; for (var i = 0; i < range.length; i++) { if (range[i] === value) { result++; } } return result; }; exports.COUNTBLANK = function() { var range = utils.flatten(arguments); var blanks = 0; var element; for (var i = 0; i < range.length; i++) { element = range[i]; if (element === null || element === '') { blanks++; } } return blanks; }; exports.COUNTIF = function(range, criteria) { range = utils.flatten(range); if (!/[<>=!]/.test(criteria)) { criteria = '=="' + criteria + '"'; } var matches = 0; for (var i = 0; i < range.length; i++) { if (typeof range[i] !== 'string') { if (eval(range[i] + criteria)) { // jshint ignore:line matches++; } } else { if (eval('"' + range[i] + '"' + criteria)) { // jshint ignore:line matches++; } } } return matches; }; exports.COUNTIFS = function() { var args = utils.argsToArray(arguments); var results = new Array(utils.flatten(args[0]).length); for (var i = 0; i < results.length; i++) { results[i] = true; } for (i = 0; i < args.length; i += 2) { var range = utils.flatten(args[i]); var criteria = args[i + 1]; if (!/[<>=!]/.test(criteria)) { criteria = '=="' + criteria + '"'; } for (var j = 0; j < range.length; j++) { if (typeof range[j] !== 'string') { results[j] = results[j] && eval(range[j] + criteria); // jshint ignore:line } else { results[j] = results[j] && eval('"' + range[j] + '"' + criteria); // jshint ignore:line } } } var result = 0; for (i = 0; i < results.length; i++) { if (results[i]) { result++; } } return result; }; exports.COUNTUNIQUE = function () { return UNIQUE.apply(null, utils.flatten(arguments)).length; }; exports.FISHER = function(x) { x = utils.parseNumber(x); if (x instanceof Error) { return x; } return Math.log((1 + x) / (1 - x)) / 2; }; exports.FISHERINV = function(y) { y = utils.parseNumber(y); if (y instanceof Error) { return y; } var e2y = Math.exp(2 * y); return (e2y - 1) / (e2y + 1); }; exports.FREQUENCY = function(data, bins) { data = utils.parseNumberArray(utils.flatten(data)); bins = utils.parseNumberArray(utils.flatten(bins)); if (utils.anyIsError(data, bins)) { return error.value; } var n = data.length; var b = bins.length; var r = []; for (var i = 0; i <= b; i++) { r[i] = 0; for (var j = 0; j < n; j++) { if (i === 0) { if (data[j] <= bins[0]) { r[0] += 1; } } else if (i < b) { if (data[j] > bins[i - 1] && data[j] <= bins[i]) { r[i] += 1; } } else if (i === b) { if (data[j] > bins[b - 1]) { r[b] += 1; } } } } return r; }; exports.LARGE = function(range, k) { range = utils.parseNumberArray(utils.flatten(range)); k = utils.parseNumber(k); if (utils.anyIsError(range, k)) { return range; } return range.sort(function(a, b) { return b - a; })[k - 1]; }; exports.MAX = function() { var range = utils.numbers(utils.flatten(arguments)); return (range.length === 0) ? 0 : Math.max.apply(Math, range); }; exports.MAXA = function() { var range = utils.arrayValuesToNumbers(utils.flatten(arguments)); return (range.length === 0) ? 0 : Math.max.apply(Math, range); }; exports.MIN = function() { var range = utils.numbers(utils.flatten(arguments)); return (range.length === 0) ? 0 : Math.min.apply(Math, range); }; exports.MINA = function() { var range = utils.arrayValuesToNumbers(utils.flatten(arguments)); return (range.length === 0) ? 0 : Math.min.apply(Math, range); }; exports.MODE = {}; exports.MODE.MULT = function() { // Credits: Roönaän var range = utils.parseNumberArray(utils.flatten(arguments)); if (range instanceof Error) { return range; } var n = range.length; var count = {}; var maxItems = []; var max = 0; var currentItem; for (var i = 0; i < n; i++) { currentItem = range[i]; count[currentItem] = count[currentItem] ? count[currentItem] + 1 : 1; if (count[currentItem] > max) { max = count[currentItem]; maxItems = []; } if (count[currentItem] === max) { maxItems[maxItems.length] = currentItem; } } return maxItems; }; exports.MODE.SNGL = function() { var range = utils.parseNumberArray(utils.flatten(arguments)); if (range instanceof Error) { return range; } return exports.MODE.MULT(range).sort(function(a, b) { return a - b; })[0]; }; exports.PERCENTILE = {}; exports.PERCENTILE.EXC = function(array, k) { array = utils.parseNumberArray(utils.flatten(array)); k = utils.parseNumber(k); if (utils.anyIsError(array, k)) { return error.value; } array = array.sort(function(a, b) { { return a - b; } }); var n = array.length; if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) { return error.num; } var l = k * (n + 1) - 1; var fl = Math.floor(l); return utils.cleanFloat((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); }; exports.PERCENTILE.INC = function(array, k) { array = utils.parseNumberArray(utils.flatten(array)); k = utils.parseNumber(k); if (utils.anyIsError(array, k)) { return error.value; } array = array.sort(function(a, b) { return a - b; }); var n = array.length; var l = k * (n - 1); var fl = Math.floor(l); return utils.cleanFloat((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); }; exports.PERCENTRANK = {}; exports.PERCENTRANK.EXC = function(array, x, significance) { significance = (significance === undefined) ? 3 : significance; array = utils.parseNumberArray(utils.flatten(array)); x = utils.parseNumber(x); significance = utils.parseNumber(significance); if (utils.anyIsError(array, x, significance)) { return error.value; } array = array.sort(function(a, b) { return a - b; }); var uniques = UNIQUE.apply(null, array); var n = array.length; var m = uniques.length; var power = Math.pow(10, significance); var result = 0; var match = false; var i = 0; while (!match && i < m) { if (x === uniques[i]) { result = (array.indexOf(uniques[i]) + 1) / (n + 1); match = true; } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { result = (array.indexOf(uniques[i]) + 1 + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1); match = true; } i++; } return Math.floor(result * power) / power; }; exports.PERCENTRANK.INC = function(array, x, significance) { significance = (significance === undefined) ? 3 : significance; array = utils.parseNumberArray(utils.flatten(array)); x = utils.parseNumber(x); significance = utils.parseNumber(significance); if (utils.anyIsError(array, x, significance)) { return error.value; } array = array.sort(function(a, b) { return a - b; }); var uniques = UNIQUE.apply(null, array); var n = array.length; var m = uniques.length; var power = Math.pow(10, significance); var result = 0; var match = false; var i = 0; while (!match && i < m) { if (x === uniques[i]) { result = array.indexOf(uniques[i]) / (n - 1); match = true; } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { result = (array.indexOf(uniques[i]) + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1); match = true; } i++; } return Math.floor(result * power) / power; }; exports.PERMUT = function(number, number_chosen) { number = utils.parseNumber(number); number_chosen = utils.parseNumber(number_chosen); if (utils.anyIsError(number, number_chosen)) { return error.value; } return FACT(number) / FACT(number - number_chosen); }; exports.PERMUTATIONA = function(number, number_chosen) { number = utils.parseNumber(number); number_chosen = utils.parseNumber(number_chosen); if (utils.anyIsError(number, number_chosen)) { return error.value; } return Math.pow(number, number_chosen); }; exports.PHI = function(x) { x = utils.parseNumber(x); if (x instanceof Error) { return error.value; } return Math.exp(-0.5 * x * x) / SQRT2PI; }; exports.PROB = function(range, probability, lower, upper) { if (lower === undefined) { return 0; } upper = (upper === undefined) ? lower : upper; range = utils.parseNumberArray(utils.flatten(range)); probability = utils.parseNumberArray(utils.flatten(probability)); lower = utils.parseNumber(lower); upper = utils.parseNumber(upper); if (utils.anyIsError(range, probability, lower, upper)) { return error.value; } if (lower === upper) { return (range.indexOf(lower) >= 0) ? probability[range.indexOf(lower)] : 0; } var sorted = range.sort(function(a, b) { return a - b; }); var n = sorted.length; var result = 0; for (var i = 0; i < n; i++) { if (sorted[i] >= lower && sorted[i] <= upper) { result += probability[range.indexOf(sorted[i])]; } } return result; }; exports.QUARTILE = {}; exports.QUARTILE.EXC = function(range, quart) { range = utils.parseNumberArray(utils.flatten(range)); quart = utils.parseNumber(quart); if (utils.anyIsError(range, quart)) { return error.value; } switch (quart) { case 1: return exports.PERCENTILE.EXC(range, 0.25); case 2: return exports.PERCENTILE.EXC(range, 0.5); case 3: return exports.PERCENTILE.EXC(range, 0.75); default: return error.num; } }; exports.QUARTILE.INC = function(range, quart) { range = utils.parseNumberArray(utils.flatten(range)); quart = utils.parseNumber(quart); if (utils.anyIsError(range, quart)) { return error.value; } switch (quart) { case 1: return exports.PERCENTILE.INC(range, 0.25); case 2: return exports.PERCENTILE.INC(range, 0.5); case 3: return exports.PERCENTILE.INC(range, 0.75); default: return error.num; } }; exports.RANK = {}; exports.RANK.AVG = function(number, range, order) { number = utils.parseNumber(number); range = utils.parseNumberArray(utils.flatten(range)); if (utils.anyIsError(number, range)) { return error.value; } range = utils.flatten(range); order = order || false; var sort = (order) ? function(a, b) { return a - b; } : function(a, b) { return b - a; }; range = range.sort(sort); var length = range.length; var count = 0; for (var i = 0; i < length; i++) { if (range[i] === number) { count++; } } return (count > 1) ? (2 * range.indexOf(number) + count + 1) / 2 : range.indexOf(number) + 1; }; exports.RANK.EQ = function(number, range, order) { number = utils.parseNumber(number); range = utils.parseNumberArray(utils.flatten(range)); if (utils.anyIsError(number, range)) { return error.value; } order = order || false; var sort = (order) ? function(a, b) { return a - b; } : function(a, b) { return b - a; }; range = range.sort(sort); return range.indexOf(number) + 1; }; exports.RSQ = function(data_x, data_y) { // no need to flatten here, PEARSON will take care of that data_x = utils.parseNumberArray(utils.flatten(data_x)); data_y = utils.parseNumberArray(utils.flatten(data_y)); if (utils.anyIsError(data_x, data_y)) { return error.value; } return Math.pow(exports.PEARSON(data_x, data_y), 2); }; exports.SMALL = function(range, k) { range = utils.parseNumberArray(utils.flatten(range)); k = utils.parseNumber(k); if (utils.anyIsError(range, k)) { return range; } return range.sort(function(a, b) { return a - b; })[k - 1]; }; exports.STANDARDIZE = function(x, mean, sd) { x = utils.parseNumber(x); mean = utils.parseNumber(mean); sd = utils.parseNumber(sd); if (utils.anyIsError(x, mean, sd)) { return error.value; } return (x - mean) / sd; }; exports.STDEV = {}; exports.STDEV.P = function() { var v = exports.VAR.P.apply(this, arguments); return Math.sqrt(v); }; exports.STDEV.S = function() { var v = exports.VAR.S.apply(this, arguments); return Math.sqrt(v); }; exports.STDEVA = function() { var v = exports.VARA.apply(this, arguments); return Math.sqrt(v); }; exports.STDEVPA = function() { var v = exports.VARPA.apply(this, arguments); return Math.sqrt(v); }; exports.VAR = {}; exports.VAR.P = function() { var range = utils.numbers(utils.flatten(arguments)); var n = range.length; var sigma = 0; var mean = exports.AVERAGE(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return sigma / n; }; exports.VAR.S = function() { var range = utils.numbers(utils.flatten(arguments)); var n = range.length; var sigma = 0; var mean = exports.AVERAGE(range); for (var i = 0; i < n; i++) { sigma += Math.pow(range[i] - mean, 2); } return sigma / (n - 1); }; exports.VARA = function() { var range = utils.flatten(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = exports.AVERAGEA(range); for (var i = 0; i < n; i++) { var el = range[i]; if (typeof el === 'number') { sigma += Math.pow(el - mean, 2); } else if (el === true) { sigma += Math.pow(1 - mean, 2); } else { sigma += Math.pow(0 - mean, 2); } if (el !== null) { count++; } } return sigma / (count - 1); }; exports.VARPA = function() { var range = utils.flatten(arguments); var n = range.length; var sigma = 0; var count = 0; var mean = exports.AVERAGEA(range); for (var i = 0; i < n; i++) { var el = range[i]; if (typeof el === 'number') { sigma += Math.pow(el - mean, 2); } else if (el === true) { sigma += Math.pow(1 - mean, 2); } else { sigma += Math.pow(0 - mean, 2); } if (el !== null) { count++; } } return sigma / count; }; exports.WEIBULL = {}; exports.WEIBULL.DIST = function(x, alpha, beta, cumulative) { x = utils.parseNumber(x); alpha = utils.parseNumber(alpha); beta = utils.parseNumber(beta); if (utils.anyIsError(x, alpha, beta)) { return error.value; } return (cumulative) ? 1 - Math.exp(-Math.pow(x / beta, alpha)) : Math.pow(x, alpha - 1) * Math.exp(-Math.pow(x / beta, alpha)) * alpha / Math.pow(beta, alpha); }; exports.Z = {}; exports.Z.TEST = function(range, x, sd) { range = utils.parseNumberArray(utils.flatten(range)); x = utils.parseNumber(x); if (utils.anyIsError(range, x)) { return error.value; } sd = sd || exports.STDEV.S(range); var n = range.length; return 1 - exports.NORM.S.DIST((exports.AVERAGE(range) - x) / (sd / Math.sqrt(n)), true); }; return exports; })(); for (var i = 0; i < Object.keys(jexcel.methods).length; i++) { var methods = jexcel.methods[Object.keys(jexcel.methods)[i]]; for (var j = 0; j < Object.keys(methods).length; j++) { if (typeof(methods[Object.keys(methods)[j]]) == 'function') { window[Object.keys(methods)[j]] = methods[Object.keys(methods)[j]]; } else { window[Object.keys(methods)[j]] = function() { return Object.keys(methods)[j] + 'Not implemented'; } } } } if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = jexcel; }
require('./hello.sass'); const $inject = ['HelloService']; const Hello = function (helloService) { const link = $scope => { $scope.hello = helloService.hello(); }; return { template: require('./hello.html'), restrict: 'E', link, scope: {} }; }; Hello.$inject = $inject; export default Hello;
'use strict' var path = require('path') , fs = require('fs') , spawn = require('child_process').spawn , chai = require('chai') , expect = chai.expect , should = chai.should() , environment = require('../../lib/environment') function find(settings, name) { var items = settings.filter(function cb_filter(candidate) { return candidate[0] === name }) expect(items.length).equal(1) return items[0][1] } describe("the environment scraper", function () { var settings before(function () { settings = environment.toJSON() }) it("should allow clearing of the dispatcher", function () { environment.setDispatcher('custom') environment.setDispatcher('another') var dispatchers = environment.get('Dispatcher') expect(dispatchers).include.members(['custom', 'another']) expect(function () { environment.clearDispatcher(); }).not.throws() }) it("should allow clearing of the framework", function () { environment.setFramework('custom') environment.setFramework('another') var frameworks = environment.get('Framework') expect(frameworks).include.members(['custom', 'another']) expect(function () { environment.clearFramework(); }).not.throws() }) it("should persist dispatcher between toJSON()s", function () { environment.setDispatcher('test') expect(environment.get('Dispatcher')).include.members(['test']) environment.refresh() expect(environment.get('Dispatcher')).include.members(['test']) }) it("should have some settings", function () { expect(settings.length).above(1) }) it("should find at least one CPU", function () { expect(find(settings, 'Processors')).above(0) }) it("should have found an operating system", function () { should.exist(find(settings, 'OS')) }) it("should have found an operating system version", function () { should.exist(find(settings, 'OS version')) }) it("should have found the system architecture", function () { should.exist(find(settings, 'Architecture')) }) it("should know the Node.js version", function () { should.exist(find(settings, 'Node.js version')) }) //expected to be run when NODE_ENV is unset it("should not find a value for NODE_ENV", function () { expect(environment.get('NODE_ENV')).to.be.empty }) if (process.config) { describe("for versions of Node with process.config", function () { it("should know whether npm was installed with Node.js", function () { should.exist(find(settings, 'npm installed?')) }) it("should know whether WAF was installed with Node.js", function () { // 0.10 drops node-waf support // FIXME: break this out into a Node-version-specific test var waf = process.config.variables.node_install_waf if (waf === true || waf === false) { should.exist(find(settings, 'WAF build system installed?')) } }) it("should know whether OpenSSL support was compiled into Node.js", function () { should.exist(find(settings, 'OpenSSL support?')) }) it("should know whether OpenSSL was dynamically linked in", function () { should.exist(find(settings, 'Dynamically linked to OpenSSL?')) }) it("should know whether V8 was dynamically linked in", function () { should.exist(find(settings, 'Dynamically linked to V8?')) }) it("should know whether Zlib was dynamically linked in", function () { should.exist(find(settings, 'Dynamically linked to Zlib?')) }) it("should know whether DTrace support was configured", function () { should.exist(find(settings, 'DTrace support?')) }) it("should know whether Event Tracing for Windows was configured", function () { should.exist(find(settings, 'Event Tracing for Windows (ETW) support?')) }) }) } it("should have built a flattened package list", function () { var packages = find(settings, 'Packages') expect(packages.length).above(5) packages.forEach(function cb_forEach(pair) { expect(JSON.parse(pair).length).equal(2) }) }) it("should have built a flattened dependency list", function () { var dependencies = find(settings, 'Dependencies') expect(dependencies.length).above(5) dependencies.forEach(function cb_forEach(pair) { expect(JSON.parse(pair).length).equal(2) }) }) it("should get correct version for dependencies", function () { var root = path.join(__dirname, '../lib/example-packages') var versions = environment.listPackages(root).reduce(function(map, pkg) { map[pkg[0]] = pkg[1] return map }, {}) expect(versions).deep.equal({ 'invalid-json': '<unknown>', 'valid-json': '1.2.3' }) }) it("should not crash when given a file in NODE_PATH", function (done) { var env = { NODE_PATH : path.join(__dirname, "environment.test.js"), PATH : process.env.PATH } var opt = { env : env, stdio : 'inherit', cwd : path.join(__dirname, '..') } var exec = process.argv[0] , args = [path.join(__dirname, '../helpers/environment.child.js')] , proc = spawn(exec, args, opt) proc.on('exit', function (code) { expect(code).equal(0) done() }) }) it("should not crash when encountering a dangling symlink", function (done) { var opt = { stdio : 'pipe', env : process.env, cwd : path.join(__dirname, '../helpers'), } var nmod = path.join(__dirname, '../helpers/node_modules') var into = path.join(nmod, 'a') var dest = path.join(nmod, 'b') // cleanup in case dest is dirty try {fs.unlinkSync(dest);} catch(e) {} if (!fs.existsSync(nmod)) fs.mkdirSync(nmod) fs.writeFileSync(into, 'hello world') fs.symlinkSync(into, dest) fs.unlinkSync(into) var exec = process.argv[0] , args = [path.join(__dirname, '../helpers/environment.child.js')] , proc = spawn(exec, args, opt) proc.stdout.pipe(process.stderr) proc.stderr.pipe(process.stderr) proc.on('exit', function (code) { expect(code).equal(0) fs.unlinkSync(dest) done() }) }) describe("when NODE_ENV is 'production'", function () { var nSettings before(function () { process.env.NODE_ENV = 'production' nSettings = environment.toJSON() }) after(function () { delete process.env.NODE_ENV }) it("should save the NODE_ENV value in the environment settings", function () { (find(nSettings, 'NODE_ENV')).should.equal('production') }) }) })
module.exports = { 'route-matching': function (browser) { browser .url('http://localhost:8080/route-matching/') .waitForElementVisible('#app', 1000) .assert.count('li a', 10) .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '' && route.fullPath === '/' && JSON.stringify(route.params) === JSON.stringify({}) ) }, null, '/') .click('li:nth-child(2) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/params/:foo/:bar' && route.fullPath === '/params/foo/bar' && JSON.stringify(route.params) === JSON.stringify({ foo: 'foo', bar: 'bar' }) ) }, null, '/params/foo/bar') .click('li:nth-child(3) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/optional-params/:foo?' && route.fullPath === '/optional-params' && JSON.stringify(route.params) === JSON.stringify({}) ) }, null, '/optional-params') .click('li:nth-child(4) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/optional-params/:foo?' && route.fullPath === '/optional-params/foo' && JSON.stringify(route.params) === JSON.stringify({ foo: 'foo' }) ) }, null, '/optional-params/foo') .click('li:nth-child(5) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/params-with-regex/:id(\\d+)' && route.fullPath === '/params-with-regex/123' && JSON.stringify(route.params) === JSON.stringify({ id: '123' }) ) }, null, '/params-with-regex/123') .click('li:nth-child(6) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 0 && route.fullPath === '/params-with-regex/abc' && JSON.stringify(route.params) === JSON.stringify({}) ) }, null, '/params-with-regex/abc') .click('li:nth-child(7) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/asterisk/*' && route.fullPath === '/asterisk/foo' && JSON.stringify(route.params) === JSON.stringify({ 0: 'foo' }) ) }, null, '/asterisk/foo') .click('li:nth-child(8) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/asterisk/*' && route.fullPath === '/asterisk/foo/bar' && JSON.stringify(route.params) === JSON.stringify({ 0: 'foo/bar' }) ) }, null, '/asterisk/foo/bar') .click('li:nth-child(9) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/optional-group/(foo/)?bar' && route.fullPath === '/optional-group/bar' && JSON.stringify(route.params) === JSON.stringify({}) ) }, null, '/optional-group/bar') .click('li:nth-child(10) a') .assert.evaluate(function () { var route = JSON.parse(document.querySelector('pre').textContent) return ( route.matched.length === 1 && route.matched[0].path === '/optional-group/(foo/)?bar' && route.fullPath === '/optional-group/foo/bar' && JSON.stringify(route.params) === JSON.stringify({ 0: 'foo/' }) ) }, null, '/optional-group/foo/bar') .end() } }
import {observer as emberObserver} from 'ember-metal/mixin'; import run from "ember-metal/run_loop"; import {Binding} from "ember-metal/binding"; import Observable from "ember-runtime/mixins/observable"; import EmberObject from 'ember-runtime/system/object'; /* NOTE: This test is adapted from the 1.x series of unit tests. The tests are the same except for places where we intend to break the API we instead validate that we warn the developer appropriately. CHANGES FROM 1.6: * Updated the API usage for setting up and syncing Binding since these are not the APIs this file is testing. * Disabled a call to invokeOnce() around line 127 because it appeared to be broken anyway. I don't think it ever even worked. */ var MyApp, binding1, binding2; QUnit.module("System:run_loop() - chained binding", { setup: function() { MyApp = {}; MyApp.first = EmberObject.createWithMixins(Observable, { output: 'MyApp.first' }); MyApp.second = EmberObject.createWithMixins(Observable, { input: 'MyApp.second', output: 'MyApp.second', inputDidChange: emberObserver("input", function() { this.set("output", this.get("input")); }) }); MyApp.third = EmberObject.createWithMixins(Observable, { input: "MyApp.third" }); } }); QUnit.test("Should propagate bindings after the RunLoop completes (using Ember.RunLoop)", function() { run(function () { //Binding of output of MyApp.first object to input of MyApp.second object binding1 = Binding.from("first.output") .to("second.input").connect(MyApp); //Binding of output of MyApp.second object to input of MyApp.third object binding2 = Binding.from("second.output") .to("third.input").connect(MyApp); }); run(function () { // Based on the above binding if you change the output of MyApp.first // object it should change the all the variable of // MyApp.first,MyApp.second and MyApp.third object MyApp.first.set("output", "change"); //Changes the output of the MyApp.first object equal(MyApp.first.get("output"), "change"); //since binding has not taken into effect the value still remains as change. equal(MyApp.second.get("output"), "MyApp.first"); }); // allows bindings to trigger... //Value of the output variable changed to 'change' equal(MyApp.first.get("output"), "change"); //Since binding triggered after the end loop the value changed to 'change'. equal(MyApp.second.get("output"), "change"); }); QUnit.test("Should propagate bindings after the RunLoop completes", function() { run(function () { //Binding of output of MyApp.first object to input of MyApp.second object binding1 = Binding.from("first.output") .to("second.input").connect(MyApp); //Binding of output of MyApp.second object to input of MyApp.third object binding2 = Binding.from("second.output") .to("third.input").connect(MyApp); }); run(function () { //Based on the above binding if you change the output of MyApp.first object it should //change the all the variable of MyApp.first,MyApp.second and MyApp.third object MyApp.first.set("output", "change"); //Changes the output of the MyApp.first object equal(MyApp.first.get("output"), "change"); //since binding has not taken into effect the value still remains as change. equal(MyApp.second.get("output"), "MyApp.first"); }); //Value of the output variable changed to 'change' equal(MyApp.first.get("output"), "change"); //Since binding triggered after the end loop the value changed to 'change'. equal(MyApp.second.get("output"), "change"); });
import SpeechRecognizer from './SpeechRecognizer'; import playPlaylist from './utils/playPlaylist'; window.wait(() => { const speech = new SpeechRecognizer( ['ok player', 'okayplayer', 'hey music', 'yo music'], // Hot Words ['Let\'s', 'can you', 'can you please', 'please'] // Command prefix ); Emitter.on('speech:toggle', (event, details) => { if (details.state) { speech.enable(); } else { speech.disable(); } }); if (Settings.get('speechRecognition', false)) speech.enable(); // Play Playlist Handlers speech.registerHandler(['play playlist', 'play the playlist'], playPlaylist); // Play / Pause Handlers let playing = false; GPM.on('change:playback', (mode) => playing = (mode === 2)); speech.registerHandler(['pause', 'pours', 'paws', 'Paul\'s'], () => new Promise((resolve) => { if (playing) GPM.playback.playPause(); resolve(); }) ); speech.registerHandler('play', () => new Promise((resolve) => { if (!playing) GPM.playback.playPause(); resolve(); }) ); // Track Navigation Handlers speech.registerHandler(['next', 'next track', 'forward', 'fast forward'], () => new Promise((resolve) => { GPM.playback.forward(); resolve(); }) ); speech.registerHandler(['back', 'previous', 'rewind', 'start again'], () => new Promise((resolve) => { GPM.playback.rewind(); resolve(); }) ); speech.registerHandler(['this song sucks', 'the song sucks'], () => new Promise((resolve) => { GPM.rating.setRating(1); resolve(); }) ); speech.registerHandler(['this song is great', 'this song rules', 'this song is epic', 'this song is awesome', 'this song rocks', 'the song is great', 'the song rules', 'the song is epic', 'the song is awesome', 'the song rocks'], () => new Promise((resolve) => { GPM.rating.setRating(5); resolve(); }) ); // Shuffle Handlers speech.registerHandler(['mixitup', 'mix it up', 'shuffle', 'shake', 'random'], () => new Promise((resolve) => { if (GPM.playback.getShuffle() === window.GMusic.Playback.ALL_SHUFFLE) { GPM.playback.toggleShuffle(); } GPM.playback.toggleShuffle(); GPM.playback.forward(); resolve(); }) ); speech.registerHandler(['turn shuffle on', 'shuffle on'], () => new Promise((resolve) => { if (GPM.playback.getShuffle() === window.GMusic.Playback.NO_SHUFFLE) { GPM.playback.toggleShuffle(); } resolve(); }) ); speech.registerHandler(['turn shuffle off', 'shuffle off'], () => new Promise((resolve) => { if (GPM.playback.getShuffle() === window.GMusic.Playback.ALL_SHUFFLE) { GPM.playback.toggleShuffle(); } resolve(); }) ); // Album Navigation Handlers speech.registerHandler(['goto artist', 'go to artist', 'load artist', 'navigate to artist'], (artistName) => new Promise((resolve) => { if (!artistName) { resolve(); return; } window.location = `/music/listen#/artist//${artistName}`; resolve(''); }) ); // Desktop Settings Trigger speech.registerHandler(['settings', 'open settings', 'show settings', 'load settings'], () => new Promise((resolve) => { Emitter.fire('window:settings'); resolve(); }) ); // Volume Controls speech.registerHandler(['turn it up', 'bring it up', 'turn the volume up', 'make it louder', 'i can\'t here it', 'i can\'t hear it'], () => new Promise((resolve) => { GPM.volume.increaseVolume(); resolve(); }) ); speech.registerHandler(['turn it down', 'take it down', 'turn the volume down', 'make it quieter', 'make it more quiet'], () => new Promise((resolve) => { GPM.volume.decreaseVolume(); resolve(); }) ); speech.registerHandler(['set volume to', 'set the volume to', 'make the volume', 'set the volume 2', 'set volume 2', 'set volume'], (num) => new Promise((resolve) => { const targetVol = parseInt(num, 10); if (targetVol) { GPM.volume.setVolume(Math.min(Math.max(0, targetVol), 100)); } resolve(num.replace(new RegExp(targetVol.toString() + '%', 'g'), '').trim()); }) ); let origVolume; speech.registerHandler(['make it boom', 'make it burn', 'sing it out', 'pump it', 'get this party started'], () => new Promise((resolve) => { origVolume = origVolume || GPM.volume.getVolume(); GPM.volume.setVolume(100); resolve(); }) ); speech.registerHandler(['shut up', 'mute', 'silence', 'turn this right down', 'party is over', 'party\'s over'], () => new Promise((resolve) => { origVolume = origVolume || GPM.volume.getVolume(); GPM.volume.setVolume(0); resolve(); }) ); speech.registerHandler(['reset the volume', 'normalize', 'normalise'], () => new Promise((resolve) => { GPM.volume.setVolume(origVolume); origVolume = null; resolve(); }) ); });
version https://git-lfs.github.com/spec/v1 oid sha256:04f1e059e7983c5cedf505f9bd7d4543153f5b0003ee86660fc4fa09cc8c55ae size 5711
(function( // Reliable reference to the global object (i.e. window in browsers). global, // Dummy constructor that we use as the .constructor property for // functions that return Generator objects. GeneratorFunction, // Undefined value, more compressible than void 0. undefined ) { var hasOwn = Object.prototype.hasOwnProperty; if (global.wrapGenerator) { return; } function wrapGenerator(innerFn, self, tryList) { return new Generator(innerFn, self || null, tryList || []); } global.wrapGenerator = wrapGenerator; if (typeof exports !== "undefined") { exports.wrapGenerator = wrapGenerator; } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; wrapGenerator.mark = function(genFun) { genFun.constructor = GeneratorFunction; return genFun; }; // Ensure isGeneratorFunction works when Function#name not supported. if (GeneratorFunction.name !== "GeneratorFunction") { GeneratorFunction.name = "GeneratorFunction"; } wrapGenerator.isGeneratorFunction = function(genFun) { var ctor = genFun && genFun.constructor; return ctor ? GeneratorFunction.name === ctor.name : false; }; function Generator(innerFn, self, tryList) { var generator = this; var context = new Context(tryList); var state = GenStateSuspendedStart; function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { throw new Error("Generator has already finished"); } while (true) { var delegate = context.delegate; if (delegate) { try { var info = delegate.generator[method](arg); // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; } catch (uncaught) { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = uncaught; continue; } if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { if (state === GenStateSuspendedStart && typeof arg !== "undefined") { // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume throw new TypeError( "attempt to send " + JSON.stringify(arg) + " to newborn generator" ); } if (state === GenStateSuspendedYield) { context.sent = arg; } else { delete context.sent; } } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } state = GenStateExecuting; try { var value = innerFn.call(self, context); // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: value, done: context.done }; if (value === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } catch (thrown) { state = GenStateCompleted; if (method === "next") { context.dispatchException(thrown); } else { arg = thrown; } } } } generator.next = invoke.bind(generator, "next"); generator.throw = invoke.bind(generator, "throw"); } Generator.prototype.toString = function() { return "[object Generator]"; }; function pushTryEntry(triple) { var entry = { tryLoc: triple[0] }; if (1 in triple) { entry.catchLoc = triple[1]; } if (2 in triple) { entry.finallyLoc = triple[2]; } this.tryEntries.push(entry); } function resetTryEntry(entry, i) { var record = entry.completion || {}; record.type = i === 0 ? "normal" : "return"; delete record.arg; entry.completion = record; } function Context(tryList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryList.forEach(pushTryEntry, this); this.reset(); } Context.prototype = { constructor: Context, reset: function() { this.prev = 0; this.next = 0; this.sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); // Pre-initialize at least 20 temporary variables to enable hidden // class optimizations for simple generators. for (var tempIndex = 0, tempName; hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20; ++tempIndex) { this[tempName] = null; } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, keys: function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, _findFinallyEntry: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && ( entry.finallyLoc === finallyLoc || this.prev < entry.finallyLoc)) { return entry; } } }, abrupt: function(type, arg) { var entry = this._findFinallyEntry(); var record = entry ? entry.completion : {}; record.type = type; record.arg = arg; if (entry) { this.next = entry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function(record) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } return ContinueSentinel; }, finish: function(finallyLoc) { var entry = this._findFinallyEntry(finallyLoc); return this.complete(entry.completion); }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry, i); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(generator, resultName, nextLoc) { this.delegate = { generator: generator, resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; }).apply(this, Function("return [this, function GeneratorFunction(){}]")()); var url = require('url'); var util = require('util'); var zlib = require('zlib'); var http = require('http'); var https = require('https'); var Netrc = require('netrc'); var write = require('write-to'); var status = require('statuses'); var rawBody = require('raw-body'); var proxyAgent = require('proxy-agent'); var debug = require('debug')('cogent'); var inspect = util.inspect; exports = module.exports = extend(); exports.extend = extend; function extend(defaults) { wrapGenerator.mark(cogent); defaults = defaults || {} defaults.retries = defaults.retries || 0; defaults.redirects = 'redirects' in defaults ? defaults.redirects : 3; defaults.timeout = defaults.timeout || 5000; defaults.method = defaults.method || 'GET'; defaults.gunzip = defaults.gunzip === false ? false : true; defaults.netrc = Netrc(defaults.netrc); return cogent; function cogent(uri, options) { var redirects, timeout, netrc, headers, urls, o, req, res, code, stream, securrrr, retries, auth, agent, gunzip, request; return wrapGenerator(function cogent$($ctx0) { while (1) switch ($ctx0.prev = $ctx0.next) { case 0: request = function request(done) { var called = false // timeout // note: timeout is only for the response, // not the entire request var id = setTimeout(function () { debug('timeout exceeded for %s %s', o.method, o.href) var err = new Error('timeout of ' + timeout + 'ms exceeded for "' + o.href + '"') err.url = o next(err) }, timeout) req = (securrrr ? https : http).request(o) req.once('response', next.bind(null, null)) req.once('error', next) req.end() function next(err, res) { if (called) { // dump the stream in case there are any // to avoid any possible leaks if (res) res.resume() return } called = true clearTimeout(id) // kill the request, specifically for timeouts // to do: tests for this #7 if (err) req.abort() if (retries && (err || (res && status.retry[res.statusCode]) )) { debug('retrying %s %s', o.method, o.href) retries-- request(done) } else if (err) { debug('received error "%s" with "%s"', err.message, o.href) done(err) } else { done(null, res) } } }; // options type checking stuff if (options === true) options = { json: true } else if (typeof options === 'string') options = { destination: options } else if (!options) options = {} // setup defaults; redirects = options.redirects || defaults.redirects; timeout = options.timeout || defaults.timeout; netrc = options.netrc ? Netrc(options.netrc) : defaults.netrc; headers = options.headers = options.headers || {}; headers['accept-encoding'] = headers['accept-encoding'] || 'gzip'; headers['user-agent'] = headers['user-agent'] || 'https://github.com/cojs/cogent'; if (options.json) headers.accept = 'application/json' // keep a history of redirect urls; urls = []; case 10: if (!true) { $ctx0.next = 60; break; } // create the request options object urls.push(o = url.parse(uri)); securrrr = o.protocol === 'https:'; o.headers = options.headers; o.method = options.method || defaults.method // auth, either by .auth or by .netrc; // auth, either by .auth or by .netrc if (options.auth || defaults.auth) { o.auth = options.auth || defaults.auth } else { auth = netrc[o.hostname]; if (auth) o.auth = (auth.login || auth.user || auth.username) + ':' + (auth.pass || auth.password); } // setup agent or proxy agent if ('agent' in options) { o.agent = options.agent } else if (options.proxy || defaults.proxy) { agent = proxyAgent(options.proxy || defaults.proxy, securrrr); if (agent) o.agent = agent; } else if (defaults.agent != null) { o.agent = defaults.agent } // retries is on a per-URL-request basis retries = options.retries || defaults.retries; debug('options: %s', inspect(o)); $ctx0.next = 21; return request; case 21: res = $ctx0.sent; code = res.statusCode // redirect; if (!(redirects-- && status.redirect[code])) { $ctx0.next = 28; break; } debug('redirecting from %s to %s', uri, res.headers.location); uri = url.resolve(uri, res.headers.location); // dump this stream res.resume() // dump this stream; return $ctx0.abrupt("continue", 10); case 28: if (!(o.method.toUpperCase() === 'HEAD')) { $ctx0.next = 32; break; } res.req = req; res.resume(); return $ctx0.abrupt("return", res); case 32: gunzip = typeof options.gunzip === 'boolean' ? options.gunzip : defaults.gunzip; if (!(!gunzip && (options.buffer || options.string || options.json))) { $ctx0.next = 35; break; } throw new Error('must gunzip if buffering the response'); case 35: if (res.headers['content-encoding'] === 'gzip' && gunzip) { stream = res.pipe(zlib.createGunzip()) stream.res = res // pass useful response stuff stream.statusCode = code stream.headers = res.headers // forward errors res.on('error', stream.emit.bind(stream, 'error')) // forward close // creates the following error: // Assertion failed: (!write_in_progress_ && "write in progress"), function Close, file ../src/node_zlib.cc, line 99. // make: *** [test] Abort trap: 6 // res.on('close', stream.close.bind(stream)) // forward destroy // note: if zlib adds a .destroy method, we have to change this stream.destroy = res.destroy.bind(res) res = stream } else { res.res = res } res.req = req; res.urls = urls // save the file; if (!(code === 200 && options.destination)) { $ctx0.next = 43; break; } $ctx0.next = 41; return write(res, options.destination); case 41: res.destination = options.destination; return $ctx0.abrupt("return", res); case 43: if (!options.buffer) { $ctx0.next = 47; break; } $ctx0.next = 46; return rawBody(res); case 46: res.buffer = $ctx0.sent; case 47: if (!(options.string || options.json)) { $ctx0.next = 56; break; } if (!res.buffer) { $ctx0.next = 52; break; } $ctx0.t0 = res.buffer.toString('utf8'); $ctx0.next = 55; break; case 52: $ctx0.next = 54; return rawBody(res, { encoding: options.string || true }); case 54: $ctx0.t0 = $ctx0.sent; case 55: res.text = $ctx0.t0; case 56: // buffer the response as JSON if (options.json) try { res.body = JSON.parse(res.text) } catch (err) { debug('"%s" is not valid JSON', uri) } return $ctx0.abrupt("return", res); case 60: case "end": return $ctx0.stop(); } }, this); } }
IntlRelativeFormat.__addLocaleData({"locale":"swc","pluralRuleFunction":function (n,ord){if(ord)return"other";return"other"},"fields":{"year":{"displayName":"Mwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"Mwezi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"Siku","relative":{"0":"Leo","1":"Kesho","-1":"Jana"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"Saa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"Dakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"Sekunde","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}}); IntlRelativeFormat.__addLocaleData({"locale":"swc-CD","parentLocale":"swc"});
/** * @author mrdoob / http://mrdoob.com/ */ THREE.RenderableFace4 = function () { this.v1 = new THREE.RenderableVertex(); this.v2 = new THREE.RenderableVertex(); this.v3 = new THREE.RenderableVertex(); this.v4 = new THREE.RenderableVertex(); this.centroidWorld = new THREE.Vector3(); this.centroidScreen = new THREE.Vector3(); this.normalWorld = new THREE.Vector3(); this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ]; this.vertexNormalsLength = 0; this.material = null; this.uvs = [[]]; this.z = null; };
version https://git-lfs.github.com/spec/v1 oid sha256:e20d962c73974dc59ddf950f145c2bc8e5a5863ccd92936a5cc755c73a3492ec size 2368
/*! * jQuery UI Button @VERSION * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/button/ * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var lastActive, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", formResetHandler = function() { var form = $( this ); setTimeout(function() { form.find( ":ui-button" ).button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { name = name.replace( /'/g, "\\'" ); if ( form ) { radios = $( form ).find( "[name='" + name + "']" ); } else { radios = $( "[name='" + name + "']", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "@VERSION", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : ""; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); // Can't use _focusable() because the element that receives focus // and the element that gets the ui-state-focus class are different this._on({ focus: function() { this.buttonElement.addClass( "ui-state-focus" ); }, blur: function() { this.buttonElement.removeClass( "ui-state-focus" ); } }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { that.refresh(); }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) // see #8559, we bind to blur here in case the button element loses // focus between keydown and keyup, it would be left in an "active" state .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } // TODO: pull out $.Widget's handling for the disabled option into // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can // be overridden by individual plugins this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " ui-state-active " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { this.element.prop( "disabled", !!value ); if ( value ) { this.buttonElement.removeClass( "ui-state-focus" ); } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( this ).button( "widget" ) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } }); } else if ( this.type === "checkbox" ) { if ( this.element.is( ":checked" ) ) { this.buttonElement .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { this.buttonElement .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } } }, _resetButton: function() { if ( this.type === "input" ) { if ( this.options.label ) { this.element.val( this.options.label ); } return; } var buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "@VERSION", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = this.element.css( "direction" ) === "rtl"; this.buttons = this.element.find( this.options.items ) .filter( ":ui-button" ) .button( "refresh" ) .end() .not( ":ui-button" ) .button() .end() .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); }( jQuery ) );
/** * @fileoverview Tests for no-unexpected-multiline rule. * @author Glen Mailer */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require("../../../lib/rules/no-unexpected-multiline"), RuleTester = require("../../../lib/testers/rule-tester"); var ruleTester = new RuleTester(); ruleTester.run("no-unexpected-multiline", rule, { valid: [ "(x || y).aFunction()", "[a, b, c].forEach(doSomething)", "var a = b;\n(x || y).doSomething()", "var a = b\n;(x || y).doSomething()", "var a = b\nvoid (x || y).doSomething()", "var a = b;\n[1, 2, 3].forEach(console.log)", "var a = b\nvoid [1, 2, 3].forEach(console.log)", "\"abc\\\n(123)\"", "var a = (\n(123)\n)", "f(\n(x)\n)", { code: "let x = function() {};\n `hello`", parserOptions: { ecmaVersion: 6 } }, { code: "let x = function() {}\nx `hello`", parserOptions: { ecmaVersion: 6 } }, { code: "String.raw `Hi\n${2+3}!`;", parserOptions: { ecmaVersion: 6 } }, { code: "x\n.y\nz `Valid Test Case`", parserOptions: { ecmaVersion: 6 } } ], invalid: [ { code: "var a = b\n(x || y).doSomething()", line: 2, column: 1, errors: [{ message: "Unexpected newline between function and ( of function call." }] }, { code: "var a = (a || b)\n(x || y).doSomething()", line: 2, column: 1, errors: [{ message: "Unexpected newline between function and ( of function call." }] }, { code: "var a = (a || b)\n(x).doSomething()", line: 2, column: 1, errors: [{ message: "Unexpected newline between function and ( of function call." }] }, { code: "var a = b\n[a, b, c].forEach(doSomething)", line: 2, column: 1, errors: [{ message: "Unexpected newline between object and [ of property access." }] }, { code: "var a = b\n (x || y).doSomething()", line: 2, column: 5, errors: [{ message: "Unexpected newline between function and ( of function call." }] }, { code: "var a = b\n [a, b, c].forEach(doSomething)", line: 2, column: 3, errors: [{ message: "Unexpected newline between object and [ of property access." }] }, { code: "let x = function() {}\n `hello`", parserOptions: { ecmaVersion: 6 }, line: 1, column: 9, errors: [{ message: "Unexpected newline between template tag and template literal." }] }, { code: "let x = function() {}\nx\n`hello`", parserOptions: { ecmaVersion: 6 }, line: 2, column: 1, errors: [{ message: "Unexpected newline between template tag and template literal." }] }, { code: "x\n.y\nz\n`Invalid Test Case`", parserOptions: { ecmaVersion: 6 }, line: 3, column: 1, errors: [{ message: "Unexpected newline between template tag and template literal." }] } ] });
var http = require('http'); var https = require('https'); /* Rpc Client Object * * new Client (options) * - options: json options object * * Define: json options object: { * port: int port of rpc server, default 5080 for http or 5433 for https * host: string domain name or ip of rpc server, default '127.0.0.1' * path: string with default path, default '/' * * login: string rpc login name, default null * hash: string rpc password (hash), default null * * ssl: json ssl object, default null * * Define: 'json ssl object: { * ca: array of string with ca's to use, default null * key: string with private key to use, default null * pfx: string with key, cert and ca info in PFX format, default null * cert: string with the public x509 certificate to use, default null * strict: boolean false to disable remote cert verification, default true * passphrase: string passphrase to be used to acces key or pfx, default null * protocol: string ssl protocol to use, default 'SSLv3_client_method' * sniName: string name for Server Name Indication, default 'RPC-Server' * } * } */ var Client = function (options) { var serv, agent; var self = this; options = options || {}; var conf = { host: options.host || '127.0.0.1', path: options.path || '/', hash: options.hash || null, login: options.login || null, }; if (options.ssl) { conf.ssl = { sniName: options.ssl.sniName || 'RPC-Server', protocol: options.ssl.protocol || 'SSLv3_client_method' }; if (options.ssl.pfx) { conf.ssl.pfx = options.ssl.pfx; conf.ssl.strict = options.ssl.strict || true; } else { if (options.ssl.ca) { conf.ssl.ca = options.ssl.ca; conf.ssl.strict = options.ssl.strict || true; } if (options.ssl.key && options.ssl.cert) { conf.ssl.key = options.ssl.key; conf.ssl.cert = options.ssl.certs; } } if (options.ssl.passphrase) { conf.ssl.passphrase = options.ssl.passphrase; } } if (conf.ssl) { serv = https; agent = new https.Agent(); conf.port = options.port || 5433; } else { serv = http; agent = new http.Agent(); conf.port = options.port || 5080; } /* Private: Returns options object for http request */ var buildOptions = function (opts) { var options = { agent: agent, method: opts.method, host: conf.host, port: conf.port, path: opts.path, headers: { 'host': conf.host + ':' + conf.port, 'content-type': 'application/json', 'content-length': opts.length, } }; if (opts.login && opts.hash) options.auth = opts.login + ':' + opts.hash; if (conf.ssl) { options.servername = conf.ssl.sniName || 'RPC-Server'; options.secureProtocol = conf.ssl.protocol || 'SSLv3_client_method'; if (conf.ssl.pfx) { options.pfx = conf.ssl.pfx; options.rejectUnauthorized = conf.ssl.strict || true; } else { if (conf.ssl.key && conf.ssl.cert) { options.key = conf.ssl.key; options.cert = conf.ssl.cert; } if (conf.ssl.ca) { options.ca = conf.ssl.ca; options.rejectUnauthorized = conf.ssl.strict || true; } } if (conf.ssl.passphrase) options.passphrase = conf.ssl.passphrase; } return options; }; /* Public: Call a function on remote server. * - data: json request object, required * - callback: function (error, result) -> null, required * - opts: json options object, default {} * * Define: '' { * path: string request path, defaul '/' * method: string request method, default 'POST' * * hash: string user password, default null * login: string user login name, default null * } */ this.call = function (data, callback, opts) { opts = opts || {} var body = JSON.stringify(data); var options = buildOptions({ length: body.length, method: opts.method || 'POST', path: opts.path || conf.path, login: opts.login || conf.login, hash: opts.hash || conf.hash }); var request = serv.request(options); request.on('error', function (error) { //TODO Proccess Request Error console.error(error); }); request.on('response', function (response) { var data = ''; response.on('data', function(bytes) { data += bytes; }); response.on('end', function() { var error, result; //TODO Deal with 401 and other codes if (response.statusCode === 200 || response.statusCode === 304) { if (data.length > 0) { try { result = JSON.parse(data); } catch (err) { error = err; console.error("Client error: failed to parse response from server."); } } } else console.log("Client: TODO Status Code: " + response.statusCode); callback(error, result); }); }); request.end(body); }; options = null; }; module.exports = Client;
var bezier = require('./'); var Benchmark = require('benchmark'); var fs = require('fs'); var line = JSON.parse(fs.readFileSync(__dirname+'/fixture/bezierIn.geojson')); var suite = new Benchmark.Suite('turf-bezier'); suite .add('turf-bezier',function () { bezier(line, 5000, .85); }) .on('cycle', function (event) { console.log(String(event.target)); }) .on('complete', function () { }) .run();
import { expect } from 'chai'; import { getCredentials, api, request, credentials, } from '../../data/api-data.js'; import { updatePermission } from '../../data/permissions.helper.js'; describe('[Statistics]', function() { this.retries(0); before((done) => getCredentials(done)); describe('[/statistics]', () => { let lastUptime; it('should return an error when the user does not have the necessary permission', (done) => { updatePermission('view-statistics', []).then(() => { request.get(api('statistics')) .set(credentials) .expect(400) .expect((res) => { expect(res.body).to.have.property('success', false); expect(res.body.error).to.be.equal('error-not-allowed'); }) .end(done); }); }); it('should return an object with the statistics', (done) => { updatePermission('view-statistics', ['admin']).then(() => { request.get(api('statistics')) .set(credentials) .expect(200) .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.property('process'); expect(res.body.process).to.have.property('uptime'); lastUptime = res.body.process.uptime; }) .end(done); }); }); it('should update the statistics when is provided the "refresh:true" query parameter', (done) => { request.get(api('statistics?refresh=true')) .set(credentials) .expect(200) .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.property('process'); expect(res.body.process).to.have.property('uptime'); expect(lastUptime).to.not.be.equal(res.body.process.uptime); }) .end(done); }); }); describe('[/statistics.list]', () => { it('should return an error when the user does not have the necessary permission', (done) => { updatePermission('view-statistics', []).then(() => { request.get(api('statistics.list')) .set(credentials) .expect(400) .expect((res) => { expect(res.body).to.have.property('success', false); expect(res.body.error).to.be.equal('error-not-allowed'); }) .end(done); }); }); it('should return an array with the statistics', (done) => { updatePermission('view-statistics', ['admin']).then(() => { request.get(api('statistics.list')) .set(credentials) .expect(200) .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.property('statistics').and.to.be.an('array'); expect(res.body).to.have.property('offset'); expect(res.body).to.have.property('total'); expect(res.body).to.have.property('count'); }) .end(done); }); }); }); });
/************************************************************* * * MathJax/localization/qqq/HelpDialog.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("qqq","HelpDialog",{ version: "2.7.0", isLoaded: true, strings: { Help: "This is the title displayed at the top of the MathJax Help dialog.", MathJax: "First paragraph of the MathJax Help dialog.\n\nStars around 'MathJax' is the Markdown syntax to put it in emphasis.", Browsers: "Second paragraph of the MathJax Help dialog.\n\nStars around 'Browsers' is the Markdown syntax to put it in emphasis.", Menu: "Third paragraph of the MathJax Help dialog.\n\nStars around 'Math Menu' the Markdown syntax to put it in emphasis.\n\n\"CTRL\" refers to \"Ctrl key\" (\"Control key\").", ShowMath: "First item of the the 'Math Menu' paragraph.\n\nStars around 'Show math as' is the Markdown syntax to put it in emphasis.\n\n'Show Math as' should be consistent with {{msg-mathjax|Mathmenu-Show}}.", Settings: "Second item of the the 'Math Menu' paragraph.\n\nStars around 'Settings' is the Markdown syntax to put it in emphasis.\n\n'Settings' should be consistent with {{msg-mathjax|Mathmenu-Settings}}.", Language: "Third item of the the 'Math Menu' paragraph.\n\nStars around 'Language' is the Markdown syntax to put it in emphasis.\n\n'Language' should be consistent with {{msg-mathjax|Mathmenu-Locale}}.", Zoom: "Fourth paragraph of the MathJax Help dialog.\n\nStars around 'Math Zoom' is the Markdown syntax to put it in emphasis.\n\n'Math Zoom' should be consistent with {{msg-mathjax|Mathmenu-ZoomTrigger}} and {{msg-mathjax|Mathmenu-ZoomFactor}}.", Accessibilty: "Fifth paragraph of the MathJax Help dialog.\n\nStars around 'Accessibility' is the Markdown syntax to put it in emphasis.", Fonts: "{{doc-markdown}}\nSixth paragraph of the MathJax Help dialog.\n\nStars around 'Fonts' is the Markdown syntax to put it in emphasis.\n\n\u003Ccode\u003E[STIX fonts](%1)\u003C/code\u003E is the Markdown syntax for links.\n\nParameters:\n* %1 - a URL the STIX fonts" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/qqq/HelpDialog.js");
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.5.4.11_A8; * @section: 15.5.4.11; * @assertion: The String.prototype.replace.length property has the attribute DontEnum; * @description: Checking if enumerating the String.prototype.replace.length property fails; */ ////////////////////////////////////////////////////////////////////////////// //CHECK#0 if (!(String.prototype.replace.hasOwnProperty('length'))) { $FAIL('#0: String.prototype.replace.hasOwnProperty(\'length\') return true. Actual: '+String.prototype.replace.hasOwnProperty('length')); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // CHECK#1 if (String.prototype.replace.propertyIsEnumerable('length')) { $ERROR('#1: String.prototype.replace.propertyIsEnumerable(\'length\') return false'); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // CHECK#2 count=0; for (p in String.prototype.replace){ if (p==="length") count++; } if (count !== 0) { $ERROR('#2: count=0; for (p in String.prototype.replace){if (p==="length") count++;} count === 0. Actual: '+count ); } // //////////////////////////////////////////////////////////////////////////////
import publicDirectives from '../directives/public/index' import internalDirectives from '../directives/internal/index' import { compileProps } from './compile-props' import { parseText, tokensToExp } from '../parsers/text' import { parseDirective } from '../parsers/directive' import { parseTemplate } from '../parsers/template' import { resolveAsset, toArray, warn, remove, replace, commonTagRE, checkComponentAttr, findRef, defineReactive, getAttr } from '../util/index' // special binding prefixes const bindRE = /^v-bind:|^:/ const onRE = /^v-on:|^@/ const dirAttrRE = /^v-([^:]+)(?:$|:(.*)$)/ const modifierRE = /\.[^\.]+/g const transitionRE = /^(v-bind:|:)?transition$/ // default directive priority const DEFAULT_PRIORITY = 1000 const DEFAULT_TERMINAL_PRIORITY = 2000 /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @return {Function} */ export function compile (el, options, partial) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && !isScript(el) && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @param {Vue} [host] - host vm of transcluded content * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - link context fragment * @return {Function|undefined} */ return function compositeLinkFn (vm, el, host, scope, frag) { // cache childNodes before linking parent, fix #657 var childNodes = toArray(el.childNodes) // link var dirs = linkAndCapture(function compositeLinkCapturer () { if (nodeLinkFn) nodeLinkFn(vm, el, host, scope, frag) if (childLinkFn) childLinkFn(vm, childNodes, host, scope, frag) }, vm) return makeUnlinkFn(vm, dirs) } } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture (linker, vm) { /* istanbul ignore if */ if (process.env.NODE_ENV === 'production') { // reset directives before every capture in production // mode, so that when unlinking we don't need to splice // them out (which turns out to be a perf hit). // they are kept in development mode because they are // useful for Vue's own tests. vm._directives = [] } var originalDirCount = vm._directives.length linker() var dirs = vm._directives.slice(originalDirCount) dirs.sort(directiveComparator) for (var i = 0, l = dirs.length; i < l; i++) { dirs[i]._bind() } return dirs } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator (a, b) { a = a.descriptor.def.priority || DEFAULT_PRIORITY b = b.descriptor.def.priority || DEFAULT_PRIORITY return a > b ? -1 : a === b ? 0 : 1 } /** * Linker functions return an unlink function that * tearsdown all directives instances generated during * the process. * * We create unlink functions with only the necessary * information to avoid retaining additional closures. * * @param {Vue} vm * @param {Array} dirs * @param {Vue} [context] * @param {Array} [contextDirs] * @return {Function} */ function makeUnlinkFn (vm, dirs, context, contextDirs) { function unlink (destroying) { teardownDirs(vm, dirs, destroying) if (context && contextDirs) { teardownDirs(context, contextDirs) } } // expose linked directives unlink.dirs = dirs return unlink } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs (vm, dirs, destroying) { var i = dirs.length while (i--) { dirs[i]._teardown() if (process.env.NODE_ENV !== 'production' && !destroying) { vm._directives.$remove(dirs[i]) } } } /** * Compile link props on an instance. * * @param {Vue} vm * @param {Element} el * @param {Object} props * @param {Object} [scope] * @return {Function} */ export function compileAndLinkProps (vm, el, props, scope) { var propsLinkFn = compileProps(el, props, vm) var propDirs = linkAndCapture(function () { propsLinkFn(vm, scope) }, vm) return makeUnlinkFn(vm, propDirs) } /** * Compile the root element of an instance. * * 1. attrs on context container (context scope) * 2. attrs on the component template root node, if * replace:true (child scope) * * If this is a fragment instance, we only need to compile 1. * * @param {Element} el * @param {Object} options * @param {Object} contextOptions * @return {Function} */ export function compileRoot (el, options, contextOptions) { var containerAttrs = options._containerAttrs var replacerAttrs = options._replacerAttrs var contextLinkFn, replacerLinkFn // only need to compile other attributes for // non-fragment instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs && contextOptions) { contextLinkFn = compileDirectives(containerAttrs, contextOptions) } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options) } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el.attributes, options) } } else if (process.env.NODE_ENV !== 'production' && containerAttrs) { // warn container directives for fragment instances var names = containerAttrs .filter(function (attr) { // allow vue-loader/vueify scoped css attributes return attr.name.indexOf('_v-') < 0 && // allow event listeners !onRE.test(attr.name) && // allow slots attr.name !== 'slot' }) .map(function (attr) { return '"' + attr.name + '"' }) if (names.length) { var plural = names.length > 1 warn( 'Attribute' + (plural ? 's ' : ' ') + names.join(', ') + (plural ? ' are' : ' is') + ' ignored on component ' + '<' + options.el.tagName.toLowerCase() + '> because ' + 'the component is a fragment instance: ' + 'http://vuejs.org/guide/components.html#Fragment-Instance' ) } } options._containerAttrs = options._replacerAttrs = null return function rootLinkFn (vm, el, scope) { // link context scope dirs var context = vm._context var contextDirs if (context && contextLinkFn) { contextDirs = linkAndCapture(function () { contextLinkFn(context, el, null, scope) }, context) } // link self var selfDirs = linkAndCapture(function () { if (replacerLinkFn) replacerLinkFn(vm, el) }, vm) // return the unlink function that tearsdown context // container directives. return makeUnlinkFn(vm, selfDirs, context, contextDirs) } } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode (node, options) { var type = node.nodeType if (type === 1 && !isScript(node)) { return compileElement(node, options) } else if (type === 3 && node.data.trim()) { return compileTextNode(node, options) } else { return null } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement (el, options) { // preprocess textareas. // textarea treats its text content as the initial value. // just bind it as an attr directive for value. if (el.tagName === 'TEXTAREA') { var tokens = parseText(el.value) if (tokens) { el.setAttribute(':value', tokensToExp(tokens)) el.value = '' } } var linkFn var hasAttrs = el.hasAttributes() var attrs = hasAttrs && toArray(el.attributes) // check terminal directives (for & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, attrs, options) } // check element directives if (!linkFn) { linkFn = checkElementDirectives(el, options) } // check component if (!linkFn) { linkFn = checkComponent(el, options) } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(attrs, options) } return linkFn } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode (node, options) { // skip marked text nodes if (node._skip) { return removeText } var tokens = parseText(node.wholeText) if (!tokens) { return null } // mark adjacent text nodes as skipped, // because we are using node.wholeText to compile // all adjacent text nodes together. This fixes // issues in IE where sometimes it splits up a single // text node into multiple ones. var next = node.nextSibling while (next && next.nodeType === 3) { next._skip = true next = next.nextSibling } var frag = document.createDocumentFragment() var el, token for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i] el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value) frag.appendChild(el) } return makeTextNodeLinkFn(tokens, frag, options) } /** * Linker for an skipped text node. * * @param {Vue} vm * @param {Text} node */ function removeText (vm, node) { remove(node) } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken (token, options) { var el if (token.oneTime) { el = document.createTextNode(token.value) } else { if (token.html) { el = document.createComment('v-html') setTokenType('html') } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' ') setTokenType('text') } } function setTokenType (type) { if (token.descriptor) return var parsed = parseDirective(token.value) token.descriptor = { name: type, def: publicDirectives[type], expression: parsed.expression, filters: parsed.filters } } return el } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn (tokens, frag) { return function textNodeLinkFn (vm, el, host, scope) { var fragClone = frag.cloneNode(true) var childNodes = toArray(fragClone.childNodes) var token, value, node for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i] value = token.value if (token.tag) { node = childNodes[i] if (token.oneTime) { value = (scope || vm).$eval(value) if (token.html) { replace(node, parseTemplate(value, true)) } else { node.data = value } } else { vm._bindDir(token.descriptor, node, host, scope) } } } replace(el, fragClone) } } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList (nodeList, options) { var linkFns = [] var nodeLinkFn, childLinkFn, node for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i] nodeLinkFn = compileNode(node, options) childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null linkFns.push(nodeLinkFn, childLinkFn) } return linkFns.length ? makeChildLinkFn(linkFns) : null } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn (linkFns) { return function childLinkFn (vm, nodes, host, scope, frag) { var node, nodeLinkFn, childrenLinkFn for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n] nodeLinkFn = linkFns[i++] childrenLinkFn = linkFns[i++] // cache childNodes before linking parent, fix #657 var childNodes = toArray(node.childNodes) if (nodeLinkFn) { nodeLinkFn(vm, node, host, scope, frag) } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host, scope, frag) } } } } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives (el, options) { var tag = el.tagName.toLowerCase() if (commonTagRE.test(tag)) { return } var def = resolveAsset(options, 'elementDirectives', tag) if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def) } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @return {Function|undefined} */ function checkComponent (el, options) { var component = checkComponentAttr(el, options) if (component) { var ref = findRef(el) var descriptor = { name: 'component', ref: ref, expression: component.id, def: internalDirectives.component, modifiers: { literal: !component.dynamic } } var componentLinkFn = function (vm, el, host, scope, frag) { if (ref) { defineReactive((scope || vm).$refs, ref, null) } vm._bindDir(descriptor, el, host, scope, frag) } componentLinkFn.terminal = true return componentLinkFn } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Array} attrs * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives (el, attrs, options) { // skip v-pre if (getAttr(el, 'v-pre') !== null) { return skip } // skip v-else block, but only if following v-if if (el.hasAttribute('v-else')) { var prev = el.previousElementSibling if (prev && prev.hasAttribute('v-if')) { return skip } } var attr, name, value, modifiers, matched, dirName, rawName, arg, def, termDef for (var i = 0, j = attrs.length; i < j; i++) { attr = attrs[i] name = attr.name.replace(modifierRE, '') if ((matched = name.match(dirAttrRE))) { def = resolveAsset(options, 'directives', matched[1]) if (def && def.terminal) { if (!termDef || ((def.priority || DEFAULT_TERMINAL_PRIORITY) > termDef.priority)) { termDef = def rawName = attr.name modifiers = parseModifiers(attr.name) value = attr.value dirName = matched[1] arg = matched[2] } } } } if (termDef) { return makeTerminalNodeLinkFn(el, dirName, value, options, termDef, rawName, arg, modifiers) } } function skip () {} skip.terminal = true /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} def * @param {String} [rawName] * @param {String} [arg] * @param {Object} [modifiers] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn (el, dirName, value, options, def, rawName, arg, modifiers) { var parsed = parseDirective(value) var descriptor = { name: dirName, arg: arg, expression: parsed.expression, filters: parsed.filters, raw: value, attr: rawName, modifiers: modifiers, def: def } // check ref for v-for and router-view if (dirName === 'for' || dirName === 'router-view') { descriptor.ref = findRef(el) } var fn = function terminalNodeLinkFn (vm, el, host, scope, frag) { if (descriptor.ref) { defineReactive((scope || vm).$refs, descriptor.ref, null) } vm._bindDir(descriptor, el, host, scope, frag) } fn.terminal = true return fn } /** * Compile the directives on an element and return a linker. * * @param {Array|NamedNodeMap} attrs * @param {Object} options * @return {Function} */ function compileDirectives (attrs, options) { var i = attrs.length var dirs = [] var attr, name, value, rawName, rawValue, dirName, arg, modifiers, dirDef, tokens, matched while (i--) { attr = attrs[i] name = rawName = attr.name value = rawValue = attr.value tokens = parseText(value) // reset arg arg = null // check modifiers modifiers = parseModifiers(name) name = name.replace(modifierRE, '') // attribute interpolations if (tokens) { value = tokensToExp(tokens) arg = name pushDir('bind', publicDirectives.bind, tokens) // warn against mixing mustaches with v-bind if (process.env.NODE_ENV !== 'production') { if (name === 'class' && Array.prototype.some.call(attrs, function (attr) { return attr.name === ':class' || attr.name === 'v-bind:class' })) { warn( 'class="' + rawValue + '": Do not mix mustache interpolation ' + 'and v-bind for "class" on the same element. Use one or the other.', options ) } } } else // special attribute: transition if (transitionRE.test(name)) { modifiers.literal = !bindRE.test(name) pushDir('transition', internalDirectives.transition) } else // event handlers if (onRE.test(name)) { arg = name.replace(onRE, '') pushDir('on', publicDirectives.on) } else // attribute bindings if (bindRE.test(name)) { dirName = name.replace(bindRE, '') if (dirName === 'style' || dirName === 'class') { pushDir(dirName, internalDirectives[dirName]) } else { arg = dirName pushDir('bind', publicDirectives.bind) } } else // normal directives if ((matched = name.match(dirAttrRE))) { dirName = matched[1] arg = matched[2] // skip v-else (when used with v-show) if (dirName === 'else') { continue } dirDef = resolveAsset(options, 'directives', dirName, true) if (dirDef) { pushDir(dirName, dirDef) } } } /** * Push a directive. * * @param {String} dirName * @param {Object|Function} def * @param {Array} [interpTokens] */ function pushDir (dirName, def, interpTokens) { var hasOneTimeToken = interpTokens && hasOneTime(interpTokens) var parsed = !hasOneTimeToken && parseDirective(value) dirs.push({ name: dirName, attr: rawName, raw: rawValue, def: def, arg: arg, modifiers: modifiers, // conversion from interpolation strings with one-time token // to expression is differed until directive bind time so that we // have access to the actual vm context for one-time bindings. expression: parsed && parsed.expression, filters: parsed && parsed.filters, interp: interpTokens, hasOneTime: hasOneTimeToken }) } if (dirs.length) { return makeNodeLinkFn(dirs) } } /** * Parse modifiers from directive attribute name. * * @param {String} name * @return {Object} */ function parseModifiers (name) { var res = Object.create(null) var match = name.match(modifierRE) if (match) { var i = match.length while (i--) { res[match[i].slice(1)] = true } } return res } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn (directives) { return function nodeLinkFn (vm, el, host, scope, frag) { // reverse apply because it's sorted low to high var i = directives.length while (i--) { vm._bindDir(directives[i], el, host, scope, frag) } } } /** * Check if an interpolation string contains one-time tokens. * * @param {Array} tokens * @return {Boolean} */ function hasOneTime (tokens) { var i = tokens.length while (i--) { if (tokens[i].oneTime) return true } } function isScript (el) { return el.tagName === 'SCRIPT' && ( !el.hasAttribute('type') || el.getAttribute('type') === 'text/javascript' ) }
/** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup Timeline Timeline * @ingroup UnaModules * * @{ */ function BxTimelinePost(oOptions) { this._sActionsUri = oOptions.sActionUri; this._sActionsUrl = oOptions.sActionUrl; this._sObjName = oOptions.sObjName == undefined ? 'oTimelinePost' : oOptions.sObjName; this._iOwnerId = oOptions.iOwnerId == undefined ? 0 : parseInt(oOptions.iOwnerId); this._sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'slide' : oOptions.sAnimationEffect; this._iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed; this._aHtmlIds = oOptions.aHtmlIds == undefined ? {} : oOptions.aHtmlIds; this._sVideosAutoplay = oOptions.sVideosAutoplay == undefined ? 'off' : oOptions.sVideosAutoplay; this._oRequestParams = { timeline: null, outline: null, general: oOptions.oRequestParams == undefined ? {} : oOptions.oRequestParams }; this._sPregTag = "(<([^>]+bx-tag[^>]+)>)"; this._sPregMention = "(<([^>]+bx-mention[^>]+)>)"; this._sPregUrl = "\\b((https?://)|(www\\.))(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\\@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\\@&=+$,%#-]+)*/?)"; this._oAttachedLinks = {}; if (typeof window.glOnInitEditor === 'undefined') window.glOnInitEditor = []; window.glOnInitEditor.push(function (sEditorSelector) { var oLink = $(sEditorSelector).parents('form:first').find('a.add-emoji'); var oEmojiConf = { emojiable_selector: bx_editor_get_htmleditable(sEditorSelector), menu_icon: oLink /* emoji popup menu icon */ }; new EmojiPicker(oEmojiConf ).discover(); /* call init emoji function */ }); var $this = this; $(document).ready(function () { $($this.sIdPost + ' form').each(function() { var sId = $(this).attr('id'); $this.initFormPost(sId); }); }); } BxTimelinePost.prototype = new BxTimelineMain(); BxTimelinePost.prototype.initFormPost = function(sFormId) { var $this = this; var oForm = $('#' + sFormId); var oTextarea = oForm.find('textarea'); autosize(oTextarea); oForm.ajaxForm({ dataType: "json", beforeSubmit: function (formData, jqForm, options) { window[$this._sObjName].beforeFormPostSubmit(oForm); }, success: function (oData) { window[$this._sObjName].afterFormPostSubmit(oForm, oData); } }); if(typeof window.glOnSpaceEnterInEditor === 'undefined') window.glOnSpaceEnterInEditor = []; window.glOnSpaceEnterInEditor.push(function (sData, sSelector) { if(!oTextarea.is(sSelector)) return; var oExp, aMatch = null; oExp = new RegExp($this._sPregTag , "ig"); sData = sData.replace(oExp, ''); oExp = new RegExp($this._sPregMention , "ig"); sData = sData.replace(oExp, ''); oExp = new RegExp($this._sPregUrl , "ig"); while(aMatch = oExp.exec(sData)) { var sUrl = aMatch[0]; if(!sUrl.length || $this._oAttachedLinks[sUrl] != undefined) continue; //--- Mark that 'attach link' process was started. $this._oAttachedLinks[sUrl] = 0; $this.addAttachLink(oForm, sUrl); } }); }; BxTimelinePost.prototype.beforeFormPostSubmit = function(oForm) { this.loadingInButton($(oForm).children().find(':submit'), true); }; BxTimelinePost.prototype.afterFormPostSubmit = function (oForm, oData) { var $this = this; var fContinue = function() { if(oData && oData.id != undefined) { var iId = parseInt(oData.id); if(iId <= 0) return; if($('#' + $this._aHtmlIds['main_timeline']).length) $this._getPost(oForm, iId, 'timeline', {afps_loading: 1}); if($('#' + $this._aHtmlIds['main_outline']).length) $this._getPost(oForm, iId, 'outline', {afps_loading: 1}); $this._getForm(oForm); return; } if(oData && oData.form != undefined && oData.form_id != undefined) { $('#' + oData.form_id).replaceWith(oData.form); $this.initFormPost(oData.form_id); return; } }; this.loadingInButton($(oForm).children().find(':submit'), false); if(oData && oData.message != undefined) bx_alert(oData.message, fContinue); else fContinue(); }; BxTimelinePost.prototype.initFormAttachLink = function(sFormId) { var $this = this; var oForm = $('#' + sFormId); oForm.ajaxForm({ dataType: "json", clearForm: true, beforeSubmit: function (formData, jqForm, options) { window[$this._sObjName].beforeFormAttachLinkSubmit(oForm); }, success: function (oData) { window[$this._sObjName].afterFormAttachLinkSubmit(oForm, oData); } }); }; BxTimelinePost.prototype.beforeFormAttachLinkSubmit = function(oForm) { this.loadingInButton($(oForm).children().find(':submit'), true); }; BxTimelinePost.prototype.afterFormAttachLinkSubmit = function (oForm, oData) { var $this = this; var fContinue = function() { if(oData && oData.item != undefined) { $('#' + $this._aHtmlIds['attach_link_popup']).dolPopupHide({onHide: function() { $(oForm).find('.bx-form-warn').hide(); }}); if(!$.trim(oData.item).length) return; var oItem = $(oData.item).hide(); $('#' + $this._aHtmlIds['attach_link_form_field']).prepend(oItem).find('#' + oItem.attr('id')).bx_anim('show', $this._sAnimationEffect, $this._sAnimationSpeed, function() { }); return; } if(oData && oData.form != undefined && oData.form_id != undefined) { $('#' + oData.form_id).replaceWith(oData.form); $this.initFormAttachLink(oData.form_id); return; } }; this.loadingInButton($(oForm).find(':submit'), false); if(oData && oData.message != undefined) bx_alert(oData.message, fContinue); else fContinue(); }; BxTimelinePost.prototype.deleteAttachLink = function(oLink, iId) { var $this = this; var oData = this._getDefaultData(); oData['id'] = iId; var oAttachLink = $('#' + this._aHtmlIds['attach_link_item'] + iId); bx_loading(oAttachLink, true); jQuery.post ( this._sActionsUrl + 'delete_attach_link/', oData, function(oData) { var fContinue = function() { if(oData && oData.code != undefined && oData.code == 0) { for(var sUrl in $this._oAttachedLinks) if(parseInt($this._oAttachedLinks[sUrl]) == parseInt(iId)) { delete $this._oAttachedLinks[sUrl]; break; } oAttachLink.bx_anim('hide', $this._sAnimationEffect, $this._sAnimationSpeed, function() { $(this).remove; }); } }; bx_loading(oAttachLink, false); if(oData && oData.message != undefined) bx_alert(oData.message, fContinue); else fContinue(); }, 'json' ); return false; }; BxTimelinePost.prototype.addAttachLink = function(oElement, sUrl) { if(!sUrl) return; var $this = this; var oData = this._getDefaultData(); oData['url'] = sUrl; jQuery.post ( this._sActionsUrl + 'add_attach_link/', oData, function(oData) { if(!oData.id || !oData.item || !$.trim(oData.item).length) return; //--- Mark that 'attach link' process was finished. $this._oAttachedLinks[sUrl] = oData.id; var oItem = $(oData.item).hide(); $('#' + $this._aHtmlIds['attach_link_form_field']).prepend(oItem).find('#' + oItem.attr('id')).bx_anim('show', $this._sAnimationEffect, $this._sAnimationSpeed, function() { }); }, 'json' ); }; BxTimelinePost.prototype.showAttachLink = function(oLink) { var oData = this._getDefaultData(); $(window).dolPopupAjax({ id: {value: this._aHtmlIds['attach_link_popup'], force: true}, url: bx_append_url_params(this._sActionsUri + 'get_attach_link_form/', oData), closeOnOuterClick: false }); return false; }; BxTimelinePost.prototype._getForm = function(oElement) { var $this = this; var oData = this._getDefaultData(); jQuery.post ( this._sActionsUrl + 'get_post_form/', oData, function(oData) { if(oData && oData.form != undefined && oData.form_id != undefined) { $('#' + oData.form_id).replaceWith(oData.form); $this.initFormPost(oData.form_id); } }, 'json' ); }; BxTimelinePost.prototype._onGetPost = function(oData) { var $this = this; var fContinue = function(oData) { if(!$.trim(oData.item).length) return; var oView = $('#' + $this._aHtmlIds['main_' + oData.view]); var oLoadMore = oView.find('.' + $this.sSP + '-load-more'); if(!oLoadMore.is(':visible')) oLoadMore.show(); var oEmpty = oView.find('.' + $this.sSP + '-empty'); if(oEmpty.is(':visible')) oEmpty.hide(); var oContent = $(oData.item).bxProcessHtml(); switch(oData.view) { case 'timeline': var oTimeline = $('#' + $this._aHtmlIds['main_timeline']); var oItems = oTimeline.find('.' + $this.sClassItems); var oDivider = oItems.find('.' + $this.sClassDividerToday); var bDivider = oDivider.length > 0; if(bDivider && !oDivider.is(':visible')) oDivider.show(); oContent.hide(); var oItem = bDivider ? oDivider.after(oContent).next('.' + $this.sClassItem + ':hidden') : oContent.prependTo(oItems); oItem.bx_anim('show', $this._sAnimationEffect, $this._iAnimationSpeed, function() { $(this).find('.bx-tl-item-text .bx-tl-content').checkOverflowHeight($this.sSP + '-overflow', function(oElement) { $this.onFindOverflow(oElement); }); $this.initFlickity(); }); if($this._sVideosAutoplay != 'off') $this.initVideos(oTimeline); break; case 'outline': $this.prependMasonry(oContent, function(oItems) { $(oItems).find('.bx-tl-item-text .bx-tl-content').checkOverflowHeight($this.sSP + '-overflow', function(oElement) { $this.onFindOverflow(oElement); }); $this.initFlickity(); }); break; } }; if(oData && oData.message != undefined && oData.message.length != 0) bx_alert(oData.message, function() { fContinue(oData); }); else fContinue(oData); };
// Copyright 2010 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 This class sends logging messages over a message channel to a * server on the main page that prints them using standard logging mechanisms. * */ goog.provide('goog.messaging.LoggerClient'); goog.require('goog.Disposable'); goog.require('goog.debug'); goog.require('goog.debug.LogManager'); goog.require('goog.debug.Logger'); /** * Creates a logger client that sends messages along a message channel for the * remote end to log. The remote end of the channel should use a * {goog.messaging.LoggerServer} with the same service name. * * @param {!goog.messaging.MessageChannel} channel The channel that on which to * send the log messages. * @param {string} serviceName The name of the logging service to use. * @constructor * @extends {goog.Disposable} * @final */ goog.messaging.LoggerClient = function(channel, serviceName) { if (goog.messaging.LoggerClient.instance_) { return goog.messaging.LoggerClient.instance_; } goog.base(this); /** * The channel on which to send the log messages. * @type {!goog.messaging.MessageChannel} * @private */ this.channel_ = channel; /** * The name of the logging service to use. * @type {string} * @private */ this.serviceName_ = serviceName; /** * The bound handler function for handling log messages. This is kept in a * variable so that it can be deregistered when the logger client is disposed. * @type {Function} * @private */ this.publishHandler_ = goog.bind(this.sendLog_, this); goog.debug.LogManager.getRoot().addHandler(this.publishHandler_); goog.messaging.LoggerClient.instance_ = this; }; goog.inherits(goog.messaging.LoggerClient, goog.Disposable); /** * The singleton instance, if any. * @type {goog.messaging.LoggerClient} * @private */ goog.messaging.LoggerClient.instance_ = null; /** * Sends a log message through the channel. * @param {!goog.debug.LogRecord} logRecord The log message. * @private */ goog.messaging.LoggerClient.prototype.sendLog_ = function(logRecord) { var name = logRecord.getLoggerName(); var level = logRecord.getLevel(); var msg = logRecord.getMessage(); var originalException = logRecord.getException(); var exception; if (originalException) { var normalizedException = goog.debug.normalizeErrorObject(originalException); exception = { 'name': normalizedException.name, 'message': normalizedException.message, 'lineNumber': normalizedException.lineNumber, 'fileName': normalizedException.fileName, // Normalized exceptions without a stack have 'stack' set to 'Not // available', so we check for the existance of 'stack' on the original // exception instead. 'stack': originalException.stack || goog.debug.getStacktrace(goog.debug.Logger.prototype.log) }; if (goog.isObject(originalException)) { // Add messageN to the exception in case it was added using // goog.debug.enhanceError. for (var i = 0; 'message' + i in originalException; i++) { exception['message' + i] = String(originalException['message' + i]); } } } this.channel_.send(this.serviceName_, { 'name': name, 'level': level.value, 'message': msg, 'exception': exception }); }; /** @override */ goog.messaging.LoggerClient.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); goog.debug.LogManager.getRoot().removeHandler(this.publishHandler_); delete this.channel_; goog.messaging.LoggerClient.instance_ = null; };
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.3.2_A1.1_T4; * @section: 11.3.2, 11.6.3, 7.3; * @assertion: Line Terminator between LeftHandSideExpression and "--" is not allowed; * @description: Checking Line separator; * @negative */ //CHECK#1 eval("var x = 1; x\u2029--");
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.13.2_A4.2_T1.2; * @section: 11.13.2, 11.5.2; * @assertion: The production x /= y is the same as x = x / y; * @description: Type(x) and Type(y) vary between primitive number and Number object; */ //CHECK#1 x = 1; x /= 1; if (x !== 1) { $ERROR('#1: x = 1; x /= 1; x === 1. Actual: ' + (x)); } //CHECK#2 x = new Number(1); x /= 1; if (x !== 1) { $ERROR('#2: x = new Number(1); x /= 1; x === 1. Actual: ' + (x)); } //CHECK#3 x = 1; x /= new Number(1); if (x !== 1) { $ERROR('#3: x = 1; x /= new Number(1); x === 1. Actual: ' + (x)); } //CHECK#4 x = new Number(1); x /= new Number(1); if (x !== 1) { $ERROR('#4: x = new Number(1); x /= new Number(1); x === 1. Actual: ' + (x)); }
'use strict'; /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that they form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } }, /** * return the first item without deleting it */ peek: function(key) { var array = this[hashKey(key)]; if (array) { return array[0]; } } };
pw.component.register('mutable', function (view, config) { this.mutation = function (mutation) { // no socket, just submit the form if (!window.socket) { view.node.submit(); return; } var datum = pw.util.dup(mutation); delete datum.__nested; delete datum.scope; delete datum.id; var message = { action: 'call-route' }; if (view.node.tagName === 'FORM') { if (view.node.querySelector('input[type="file"]')) { // file uploads over websocket are not supported view.node.submit(); return; } var method; var $methodOverride = view.node.querySelector('input[name="_method"]'); if ($methodOverride) { method = $methodOverride.value; } else { method = view.node.getAttribute('method'); } message.method = method; message.uri = view.node.getAttribute('action'); message.input = pw.node.serialize(view.node); } else { //TODO deduce uri / method var input = {}; input[mutation.scope] = datum; message.input = input; } var self = this; window.socket.send(message, function (res) { if (res.status === 302) { var dest = res.headers.Location; if (dest == window.location.pathname && (!window.context || window.context.name !== 'default')) { history.pushState({ uri: dest }, dest, dest); } else { //TODO trigger a response:redirect instead and let navigator subscribe history.pushState({ uri: dest }, dest, dest); } } else if (res.status === 400) { // bad request pw.component.broadcast('response:received', { response: res }); return; } else { self.state.rollback(); } pw.component.broadcast('response:received', { response: res }); if (config.revert !== 'false') { self.revert(); } }); } });
define([ 'dojo/_base/declare', 'dojo/on', 'dojo/_base/Deferred', 'dijit/_Templated', 'dojo/dom-class', 'dojo/dom-construct', 'dijit/_WidgetBase', 'dojo/_base/xhr', 'dojo/_base/lang', 'dojo/dom-attr', 'dojo/query', 'dojo/dom-geometry', 'dojo/dom-style', 'dojo/when' ], function ( declare, on, Deferred, Templated, domClass, domConstruct, WidgetBase, xhr, lang, domAttr, Query, domGeometry, domStyle, when ) { return declare([WidgetBase, Templated], { templateString: '<div class="${baseClass}"><div data-dojo-attach-point="categoryNode" class="facetCategory"></div><div style="" class="dataList" data-dojo-attach-point="containerNode"></div></div>', baseClass: 'FacetFilter', category: 'NAME', data: null, selected: null, constructor: function () { this._selected = {}; }, _setCategoryAttr: function (category) { var cat = category.replace(/_/g, ' '); this._set('category', category); if (this._started && this.categoryNode) { this.categoryNode.innerHTML = cat.replace(/_/g, ' '); } }, _setDataAttr: function (data, selected) { // console.log("_setDataAttr", data, selected); if (selected) { this.selected = selected; } // console.log("_setData: ", data, "internal selected: ", this.selected, " Supplied Selection: ", selected, "Type: ", typeof data); if (!data) { return; } if (this.data && this.data instanceof Deferred) { var promise = this.data; } this.data = data; domConstruct.empty(this.containerNode); // console.log("_setDataAttr data.length: ", this.data.length) if (data.length < 1) { domClass.add(this.domNode, 'dijitHidden'); } else { domClass.remove(this.domNode, 'dijitHidden'); } // console.log("selected: ", this.selected) if (data.forEach) { data.forEach(function (obj) { var name = decodeURIComponent(obj.label || obj.val); // console.log("data obj: ", name, obj); var l = name + ((typeof obj.count != 'undefined') ? ('&nbsp;(' + obj.count + ')') : ''); var sel; if ( this._selected[name] || (this.selected.indexOf(name) >= 0) ) { sel = 'selected'; } else { sel = ''; } // console.log("Obj: ", obj.label || obj.value, " Selected: ", sel); // var sel = ((this.selected.indexOf(obj.label || obj.value) >= 0)||(this._selected[obj.label||obj.value]))?"selected":""; var n = this['_value_' + name] = domConstruct.create('div', { rel: name, 'class': 'FacetValue ' + sel, innerHTML: l }); // console.log("*** Created Value Reference: ", "_value_" + (obj.label || obj.value), n) domConstruct.place(n, this.containerNode, sel ? 'first' : 'last'); this.containerNode.scrollTop = 0; }, this); // this._refreshFilter(); if (promise) { promise.resolve(true); } } }, toggle: function (name, value) { name = name.replace(/"/g, ''); // console.log("Toggle: ", name, value, " Data:", this.data); when(this.data, lang.hitch(this, function () { var node = this['_value_' + name]; // console.log("Toggle Node: ", node, " Set to: ", value?"TRUE":"Opposite", domClass.contains(node, "Selected")); if (node) { // console.log(" Found Node") if (typeof value == 'undefined') { var isSelected = domClass.contains(node, 'selected'); // console.log("isSelected: ", isSelected); domClass.toggle(node, 'selected'); this._set('selected', this.selected.filter(function (i) { return (i != name) || ((i == name) && !isSelected); })); } else { if (value) { domClass.add(node, 'selected'); if (this.selected.indexOf(name) < 0) { this.selected.push(name); this._set('selected', this.selected); } } else { domClass.remove(node, 'selected'); this._set('selected', this.selected.filter(function (i) { return i != name; })); } } } // console.log(name, " this.selected: ", this.selected) if (this.selected && this.selected.length > 0) { domClass.add(this.categoryNode, 'selected'); } else { domClass.remove(this.categoryNode, 'selected'); } this.resize(); })); // this._refreshFilter(); }, startup: function () { if (this._started) { return; } this._started = true; this.inherited(arguments); this._refreshFilter(); }, _refreshFilter: function () { // console.log("FacetFilter _refreshFilter() started: ", this._started); var selected = []; Query('.selected', this.containerNode).forEach(function (node) { // console.log(".selected Node: ", node) selected.push(domAttr.get(node, 'rel')); }); // console.log("_refreshFilter selected() : ", selected); // var curFilter = this.filter; // this.filter = "in(" + this.category + ",(" + selected.join(",") + "))"; if (selected.length < 1) { this.filter = ''; } else if (selected.length == 1) { this.filter = 'eq(' + this.category + ',' + encodeURIComponent('"' + selected[0] + '"') + ')'; } else { this.filter = 'or(' + selected.map(function (s) { return 'eq(' + this.category + ',' + encodeURIComponent('"' + s + '"') + ')'; }, this).join(',') + ')'; } // console.log("_refreshFilter selected[]: ", selected) if (selected.length > 0) { domClass.add(this.categoryNode, 'selected'); } else { domClass.remove(this.categoryNode, 'selected'); } this._set('selected', selected); // console.log("selected: ", selected) // console.log("new filter: ", this.filter, " curFilter: ", curFilter); // if (this.filter != curFilter){ // console.log("Emit UpdateFilterCategory: ", this.category, " Filter: ", this.filter, " Selected: ", selected); on.emit(this.domNode, 'UpdateFilterCategory', { category: this.category, filter: this.filter, selected: selected, bubbles: true, cancelable: true }); // } }, toggleItem: function (evt) { // var rel = domAttr.get(evt.target, 'rel'); // console.log("onToggle: ", rel) domClass.toggle(evt.target, 'selected'); this._refreshFilter(); }, clearSelection: function () { // console.log("CLEAR SELECTION") this.set('data', this.data, []); domClass.remove(this.categoryNode, 'selected'); }, postCreate: function () { this.inherited(arguments); on(this.domNode, '.FacetValue:click', lang.hitch(this, 'toggleItem')); if (this.categoryNode && this.category) { this.categoryNode.innerHTML = this.category.replace(/_/g, ' '); } if (!this.data) { this.data = new Deferred(); } }, resize: function (changeSize, resultSize) { var node = this.domNode; // set margin box size, unless it wasn't specified, in which case use current size if (changeSize) { domGeometry.setMarginBox(node, changeSize); } // If either height or width wasn't specified by the user, then query node for it. // But note that setting the margin box and then immediately querying dimensions may return // inaccurate results, so try not to depend on it. var mb = resultSize || {}; lang.mixin(mb, changeSize || {}); // changeSize overrides resultSize if (!('h' in mb) || !('w' in mb)) { mb = lang.mixin(domGeometry.getMarginBox(node), mb); // just use domGeometry.marginBox() to fill in missing values } // Compute and save the size of my border box and content box // (w/out calling domGeometry.getContentBox() since that may fail if size was recently set) var cs = domStyle.getComputedStyle(node); var me = domGeometry.getMarginExtents(node, cs); var be = domGeometry.getBorderExtents(node, cs); var bb = (this._borderBox = { w: mb.w - (me.w + be.w), h: mb.h - (me.h + be.h) }); var pe = domGeometry.getPadExtents(node, cs); this._contentBox = { l: domStyle.toPixelValue(node, cs.paddingLeft), t: domStyle.toPixelValue(node, cs.paddingTop), w: bb.w - pe.w, h: bb.h - pe.h }; var hmb = domGeometry.getMarginBox(this.categoryNode); // console.log("FacetFilter _contentBox: ", this._contentBox, " Header MB: ", hmb); domGeometry.setMarginBox(this.containerNode, { h: this._contentBox.h - hmb.h }); } }); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.5.1_A2.1_T3; * @section: 11.5.1; * @assertion: Operator x * y uses GetValue; * @description: If GetBase(y) is null, throw ReferenceError; */ //CHECK#1 try { 1 * y; $ERROR('#1.1: 1 * y throw ReferenceError. Actual: ' + (1 * y)); } catch (e) { if ((e instanceof ReferenceError) !== true) { $ERROR('#1.2: 1 * y throw ReferenceError. Actual: ' + (e)); } }
/** * @fileoverview Validates JSDoc comments are syntactically correct * @author Nicholas C. Zakas * @copyright 2014 Nicholas C. Zakas. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var doctrine = require("doctrine"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { var options = context.options[0] || {}, prefer = options.prefer || {}, // these both default to true, so you have to explicitly make them false requireReturn = options.requireReturn !== false, requireParamDescription = options.requireParamDescription !== false, requireReturnDescription = options.requireReturnDescription !== false; //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- // Using a stack to store if a function returns or not (handling nested functions) var fns = []; /** * When parsing a new function, store it in our function stack. * @param {ASTNode} node A function node to check. * @returns {void} * @private */ function startFunction(node) { fns.push({ returnPresent: (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") }); } /** * Indicate that return has been found in the current function. * @param {ASTNode} node The return node. * @returns {void} * @private */ function addReturn(node) { var functionState = fns[fns.length - 1]; if (functionState && node.argument !== null) { functionState.returnPresent = true; } } /** * Validate the JSDoc node and output warnings if anything is wrong. * @param {ASTNode} node The AST node to check. * @returns {void} * @private */ function checkJSDoc(node) { var jsdocNode = context.getJSDocComment(node), functionData = fns.pop(), hasReturns = false, hasConstructor = false, params = Object.create(null), jsdoc; // make sure only to validate JSDoc comments if (jsdocNode) { try { jsdoc = doctrine.parse(jsdocNode.value, { strict: true, unwrap: true, sloppy: true }); } catch (ex) { if (/braces/i.test(ex.message)) { context.report(jsdocNode, "JSDoc type missing brace."); } else { context.report(jsdocNode, "JSDoc syntax error."); } return; } jsdoc.tags.forEach(function(tag) { switch (tag.title) { case "param": case "arg": case "argument": if (!tag.type) { context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name }); } if (!tag.description && requireParamDescription) { context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name }); } if (params[tag.name]) { context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name }); } else if (tag.name.indexOf(".") === -1) { params[tag.name] = 1; } break; case "return": case "returns": hasReturns = true; if (!requireReturn && !functionData.returnPresent && tag.type.name !== "void" && tag.type.name !== "undefined") { context.report(jsdocNode, "Unexpected @" + tag.title + " tag; function has no return statement."); } else { if (!tag.type) { context.report(jsdocNode, "Missing JSDoc return type."); } if (tag.type.name !== "void" && !tag.description && requireReturnDescription) { context.report(jsdocNode, "Missing JSDoc return description."); } } break; case "constructor": case "class": hasConstructor = true; break; // no default } // check tag preferences if (prefer.hasOwnProperty(tag.title)) { context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] }); } }); // check for functions missing @returns if (!hasReturns && !hasConstructor && node.parent.kind !== "get") { if (requireReturn || functionData.returnPresent) { context.report(jsdocNode, "Missing JSDoc @returns for function."); } } // check the parameters var jsdocParams = Object.keys(params); node.params.forEach(function(param, i) { var name = param.name; // TODO(nzakas): Figure out logical things to do with destructured, default, rest params if (param.type === "Identifier") { if (jsdocParams[i] && (name !== jsdocParams[i])) { context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", { name: name, jsdocName: jsdocParams[i] }); } else if (!params[name]) { context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", { name: name }); } } }); } } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { "ArrowFunctionExpression": startFunction, "FunctionExpression": startFunction, "FunctionDeclaration": startFunction, "ArrowFunctionExpression:exit": checkJSDoc, "FunctionExpression:exit": checkJSDoc, "FunctionDeclaration:exit": checkJSDoc, "ReturnStatement": addReturn }; }; module.exports.schema = [ { "type": "object", "properties": { "prefer": { "type": "object", "additionalProperties": { "type": "string" } }, "requireReturn": { "type": "boolean" }, "requireParamDescription": { "type": "boolean" }, "requireReturnDescription": { "type": "boolean" } }, "additionalProperties": false } ];
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RuntimeGlobals = require("./RuntimeGlobals"); const CachedConstDependency = require("./dependencies/CachedConstDependency"); const ConstDependency = require("./dependencies/ConstDependency"); const { evaluateToString, expressionIsUnsupported } = require("./javascript/JavascriptParserHelpers"); const { relative } = require("./util/fs"); const { parseResource } = require("./util/identifier"); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ class NodeStuffPlugin { constructor(options) { this.options = options; } /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { const options = this.options; compiler.hooks.compilation.tap( "NodeStuffPlugin", (compilation, { normalModuleFactory }) => { const handler = (parser, parserOptions) => { if (parserOptions.node === false) return; let localOptions = options; if (parserOptions.node) { localOptions = { ...localOptions, ...parserOptions.node }; } if (localOptions.global) { parser.hooks.expression .for("global") .tap("NodeStuffPlugin", expr => { const dep = new ConstDependency( RuntimeGlobals.global, expr.range, [RuntimeGlobals.global] ); dep.loc = expr.loc; parser.state.module.addPresentationalDependency(dep); }); } const setModuleConstant = (expressionName, fn) => { parser.hooks.expression .for(expressionName) .tap("NodeStuffPlugin", expr => { const dep = new CachedConstDependency( JSON.stringify(fn(parser.state.module)), expr.range, expressionName ); dep.loc = expr.loc; parser.state.module.addPresentationalDependency(dep); return true; }); }; const setConstant = (expressionName, value) => setModuleConstant(expressionName, () => value); const context = compiler.context; if (localOptions.__filename) { if (localOptions.__filename === "mock") { setConstant("__filename", "/index.js"); } else if (localOptions.__filename === true) { setModuleConstant("__filename", module => relative(compiler.inputFileSystem, context, module.resource) ); } parser.hooks.evaluateIdentifier .for("__filename") .tap("NodeStuffPlugin", expr => { if (!parser.state.module) return; const resource = parseResource(parser.state.module.resource); return evaluateToString(resource.path)(expr); }); } if (localOptions.__dirname) { if (localOptions.__dirname === "mock") { setConstant("__dirname", "/"); } else if (localOptions.__dirname === true) { setModuleConstant("__dirname", module => relative(compiler.inputFileSystem, context, module.context) ); } parser.hooks.evaluateIdentifier .for("__dirname") .tap("NodeStuffPlugin", expr => { if (!parser.state.module) return; return evaluateToString(parser.state.module.context)(expr); }); } parser.hooks.expression .for("require.extensions") .tap( "NodeStuffPlugin", expressionIsUnsupported( parser, "require.extensions is not supported by webpack. Use a loader instead." ) ); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("NodeStuffPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("NodeStuffPlugin", handler); } ); } } module.exports = NodeStuffPlugin;
//# sourceMappingURL=IOpacityAnimation.js.map
exports.config = { chromeOnly: false, capabilities: { browserName: 'firefox' }, specs: ['src/tests/integration/**/*.js'], baseUrl: 'http://localhost:8001', framework: 'mocha', mochaOpts: { ui: 'bdd', reporter: 'list', enableTimeouts: false } };
'use strict'; const expect = require('chai').expect; const semver = require('semver'); function assertVersionLock(_deps) { let deps = _deps || {}; Object.keys(deps).forEach(function(name) { if (name !== 'ember-cli' && semver.valid(deps[name]) && semver.gtr('1.0.0', deps[name])) { // only valid if the version is fixed expect(semver.valid(deps[name]), `"${name}" has a valid version`).to.be.ok; } }); } describe('dependencies', function() { let pkg; describe('in package.json', function() { before(function() { pkg = require('../../../package.json'); }); it('are locked down for pre-1.0 versions', function() { assertVersionLock(pkg.dependencies); assertVersionLock(pkg.devDependencies); }); }); describe('in blueprints/app/files/package.json', function() { before(function() { pkg = require('../../../blueprints/app/files/package.json'); }); it('are locked down for pre-1.0 versions', function() { assertVersionLock(pkg.dependencies); assertVersionLock(pkg.devDependencies); }); }); });
var http = require('http'); var fs = require('fs'); var mime = require('mime'); var url = require('url'); var queryString = require('querystring'); var userData = []; var maxId = 0; var server = http.createServer(function (request, response) { var objUrl = url.parse(request.url); var query = queryString.parse(objUrl.query); var requestUrl = objUrl.pathname; if (requestUrl == '/favicon.ico') { return response.end('404'); } if (requestUrl == '/') { requestUrl = '/index.html'; } switch (requestUrl) { case '/add': for (var cur = 0, len = userData.length; cur < len; cur++) { if (userData[cur]['id'] === query['id']) { userData[cur]['name'] = query['name']; userData[cur]['sex'] = query['sex']; userData[cur]['age'] = query['age']; return response.end(JSON.stringify([query])); } } query['id'] = maxId.toString(); maxId++; userData.push(query); response.end(JSON.stringify([query])); break; case '/delete': userData.forEach(function (cur, index) { if (cur['id'] === query['id']) { userData.splice(index, 1); } }); response.end(JSON.stringify([query])); break; case '/search': var queryArr = []; var reg = new RegExp(query.searchText); userData.forEach(function (cur) { if (reg.test(cur['name'])) { queryArr.push(cur); } }); response.end(JSON.stringify(queryArr)); break; default: response.setHeader('Content-Type', mime.lookup(requestUrl) + ';charset=utf-8');//设置响应头 fs.exists('.' + requestUrl, function (exists) { if (exists) { fs.readFile('.' + requestUrl, function (err, data) { if (err) { response.statusCode = 404; response.end(); } else { response.statusCode = 200; response.write(data); response.end(); } }) } else { response.statusCode = 404; response.end(); } }) } }); server.listen(8062);
var assert = require('assert'); var Checker = require('../../../lib/checker'); var reportAndFix = require('../../lib/assertHelpers').reportAndFix; describe('rules/require-padding-newlines-after-blocks', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); }); describe('invalid options', function() { it('should throw if false', function() { assert.throws(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: false }); }); }); it('should throw if empty object', function() { assert.throws(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: {} }); }); }); it('should throw if not allExcept object', function() { assert.throws(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allBut: false} }); }); }); it('should throw if array', function() { assert.throws(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: [] }); }); }); it('should throw if allExcept empty array', function() { assert.throws(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: [] } }); }); }); it('should throw if not allExcept unrecognized', function() { assert.throws(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: ['foo']} }); }); }); }); describe('value true', function() { var rules = { requirePaddingNewLinesAfterBlocks: true }; beforeEach(function() { checker.configure(rules); }); reportAndFix({ name: 'missing padding after block', rules: rules, input: 'if(true){}\nvar a = 2;', output: 'if(true){}\n\nvar a = 2;' }); reportAndFix({ name: 'after function definitions', rules: rules, input: 'var a = function() {\n};\nvar b = 2;', output: 'var a = function() {\n};\n\nvar b = 2;' }); reportAndFix({ name: 'missing padding after nested block', rules: rules, input: 'if(true){\nif(true) {}\nvar a = 2;}', output: 'if(true){\nif(true) {}\n\nvar a = 2;}' }); reportAndFix({ name: 'missing padding after obj func definition', rules: rules, input: 'var a = {\nfoo: function() {\n},\nbar: function() {\n}}', output: 'var a = {\nfoo: function() {\n},\n\nbar: function() {\n}}' }); reportAndFix({ name: 'missing padding after immed func', rules: rules, input: '(function(){\n})()\nvar a = 2;', output: '(function(){\n})()\n\nvar a = 2;' }); it('should not report end of file', function() { assert(checker.checkString('if(true){}').isEmpty()); }); it('should not report end of file with empty line', function() { assert(checker.checkString('if(true){}\n').isEmpty()); }); it('should not report padding after block', function() { assert(checker.checkString('if(true){}\n\nvar a = 2;').isEmpty()); }); it('should not report additional padding after block', function() { assert(checker.checkString('if(true){}\n\n\nvar a = 2;').isEmpty()); }); it('should not report padding after nested block', function() { assert(checker.checkString('if(true){\nif(true) {}\n}').isEmpty()); }); it('should not report padding after obj func definition', function() { assert(checker.checkString('var a = {\nfoo: function() {\n},\n\nbar: function() {\n}}').isEmpty()); }); it('should not report padding after immed func', function() { assert(checker.checkString('(function(){\n})()\n\nvar a = 2;').isEmpty()); }); it('should not report missing padding in if else', function() { assert(checker.checkString('if(true) {\n}\nelse\n{\n}').isEmpty()); }); it('should not report content in missing padding if else', function() { assert(checker.checkString('if(true) {\n} else {\n var a = 2; }').isEmpty()); }); it('should not report missing padding in if elseif else', function() { assert(checker.checkString('if(true) {\n}\nelse if(true)\n{\n}\nelse {\n}').isEmpty()); }); it('should not report missing padding in do while', function() { assert(checker.checkString('do{\n}\nwhile(true)').isEmpty()); }); it('should not report missing padding in try catch', function() { assert(checker.checkString('try{\n}\ncatch(e) {}').isEmpty()); }); it('should not report missing padding in try finally', function() { assert(checker.checkString('try{\n}\nfinally {}').isEmpty()); }); it('should not report missing padding in try catch finally', function() { assert(checker.checkString('try{\n}\ncatch(e) {\n}\nfinally {\n}').isEmpty()); }); it('should not report missing padding in function chain', function() { assert(checker.checkString('[].map(function() {})\n.filter(function(){})').isEmpty()); }); it('should report missing padding when function is last arguments', function() { assert(checker.checkString('func(\n2,\n3,\nfunction() {\n}\n)').getErrorCount() === 1); }); it('should report missing padding when function is last in array', function() { assert(checker.checkString('[\n2,\n3,\nfunction() {\n}\n]').getErrorCount() === 1); }); it('should report missing padding when function is middle in array', function() { assert(checker.checkString('[\n3,\nfunction() {\n},\n2\n]').getErrorCount() === 1); }); }); describe('value allExcept: inCallExpressions', function() { beforeEach(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: ['inCallExpressions'] } }); }); it('should not report missing padding when function is last arguments', function() { assert(checker.checkString('func(\n2,\n3,\nfunction() {\n}\n)').isEmpty()); }); it('should not report missing padding when function is middle argument', function() { assert(checker.checkString('func(\n3,\nfunction() {\n},\n2\n)').isEmpty()); }); it('should not report for IIFE', function() { assert(checker.checkString('(function() {})\n(1,2,3)').isEmpty()); }); it('should report missing padding when function is last in array', function() { assert(checker.checkString('[\n2,\n3,\nfunction() {\n}\n]').getErrorCount() === 1); }); it('should report missing padding when function is middle in array', function() { assert(checker.checkString('[\n3,\nfunction() {\n},\n2\n]').getErrorCount() === 1); }); }); describe('value allExcept: inNewExpressions', function() { beforeEach(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: ['inNewExpressions'] } }); }); it('should not report missing padding when function is last argument', function() { assert(checker.checkString('new Obj(\n2,\n3,\nfunction() {\n}\n)').isEmpty()); }); it('should not report missing padding when function is middle argument', function() { assert(checker.checkString('new Obj(\n3,\nfunction() {\n},\n2\n)').isEmpty()); }); }); describe('value allExcept: inArrayExpressions', function() { beforeEach(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: ['inArrayExpressions'] } }); }); it('should not report missing padding when function is last in array', function() { assert(checker.checkString('[\n2,\n3,\nfunction() {\n}\n]').isEmpty()); }); it('should not report missing padding when function is middle in array', function() { assert(checker.checkString('[\n3,\nfunction() {\n},\n2\n]').isEmpty()); }); }); describe('value allExcept: inProperties', function() { beforeEach(function() { checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: ['inProperties'] } }); }); it('should not report missing padding when function is last in object', function() { assert(checker.checkString('var a = {\na: 2,\nb: 3,\nc: function() {\n}\n};').isEmpty()); }); it('should not report missing padding when function is middle in object', function() { assert(checker.checkString('var a = {\na: 3,\nb: function() {\n},\nc: 2\n}').isEmpty()); }); }); describe('changing value', function() { it('should change value (#1343)', function() { var checker = new Checker(); checker.registerDefaultRules(); checker.configure({ requirePaddingNewLinesAfterBlocks: true }); assert(checker.checkString('[\n2,\n3,\nfunction() {\n}\n]').getErrorCount() === 1); checker.configure({ requirePaddingNewLinesAfterBlocks: { allExcept: ['inArrayExpressions'] } }); assert(checker.checkString('[\n2,\n3,\nfunction() {\n}\n]').isEmpty()); }); }); });
const ControlledTabs = React.createClass({ getInitialState() { return { key: 1 }; }, handleSelect(key) { alert('selected ' + key); this.setState({key}); }, render() { return ( <Tabs activeKey={this.state.key} onSelect={this.handleSelect}> <Tab eventKey={1} title='Tab 1'>Tab 1 content</Tab> <Tab eventKey={2} title='Tab 2'>Tab 2 content</Tab> <Tab eventKey={3} title='Tab 3' disabled>Tab 3 content</Tab> </Tabs> ); } }); React.render(<ControlledTabs />, mountNode);
'use strict'; const bestSuggestions = require('./suggest'); const util = require('./util'); const _type = util._type; const _clone = util._clone; const v = {}; const _result = (ok, expType, acType, val, warning) => { if (ok) { return {ok: true, warning}; } return {ok: false, type: 'simple', expType, acType, val}; }; const _collResult = (itemResults, warning) => { const hasErrItems = itemResults.filter(item => { const result = item.result; return !result.ok; }).length > 0; if (hasErrItems) { return {ok: false, type: 'collection', itemResults, warning}; } else { return {ok: true, type: 'collection', itemResults, warning}; } }; const _collItem = (path, result) => { return {path, result}; }; const defType = (human, fn, _props, defaultValue) => { fn.human = human; fn._props = _props; if (defaultValue !== undefined) fn.defaultValue = defaultValue; fn.default = val => { const newFn = fn.bind({}); return defType(human, newFn, _props, val); }; fn.undefault = () => { const newFn = fn.bind({}); return defType(human, newFn, _props); }; return fn; }; const isType = type => { return defType(type, x => { if (_type(x) === type) { return _result(true); } return _result(false, type, _type(x), x); }); }; const compose = (f1, f2) => { return defType(f1.human, x => { const r = f1(x); if (!r.ok) return r; return f2(x); }, f2._props); }; const _arrayOf = (elType) => { return ary => { const rs = ary.map(el => elType(el)); const rs_ = rs.map((r, idx) => { return _collItem(idx, r); }); return _collResult(rs_); }; }; const _objectOf = (schema, suggest) => { if (suggest === undefined) suggest = true; const fn = obj => { const rs = Object.keys(obj).map(key => { const val = obj[key]; if (!(key in schema)) { const r = _result(true); let warning; if (suggest) { const suggestions = bestSuggestions(key, Object.keys(schema)); if (suggestions.length > 0) { warning = `perhaps you meant ${suggestions.join(', ')}`; } } if (warning) { r.warning = warning; } return _collItem(key, r); } const ty = schema[key]; const r = ty(val); return _collItem(key, r); }); Object.keys(schema).forEach(key => { if (key in obj) { return; } const ty = schema[key]; if ('defaultValue' in ty) { obj[key] = _clone(ty.defaultValue); ty(obj[key]); } }); return _collResult(rs); }; fn._props = {schema, suggest}; return fn; }; const _mergeObjectOf = (v1, v2, opts) => { const deepUndefault = val => { if (val.human === 'object' && val._props && val._props.elSchema && val._props.elSchema.human === 'object') { const blank = v.objects({}, v.object({})); return _mergeObjectOf(val, blank, opts); } else if (val.human === 'object' && val._props && val._props.schema) { const blank = v.object({}); return _mergeObjectOf(val, blank, opts); } else { return val.undefault(); } }; const uniq = ary => Array.from(new Set(ary)); if (v1.human === 'object' && v2.human === 'object' && v1._props.schema && v2._props.schema) { const schema1 = v1._props.schema; const schema2 = v2._props.schema; const mergedSchema = {}; const allKeys = uniq(Object.keys(schema1).concat(Object.keys(schema2))); allKeys.forEach(key => { if (key in schema1 && key in schema2) { // present in both const val1 = schema1[key]; const val2 = schema2[key]; try { const val = _mergeObjectOf(val1, val2, opts); mergedSchema[key] = val; } catch (e) { if (val1.human === val2.human) { const val = val2; mergedSchema[key] = val; } else { throw new Error(`can't merge schemas for key '${key}' (${val1.human} and ${val2.human})`); } } if ('defaultValue' in val2) { mergedSchema[key] = mergedSchema[key].default(val2.defaultValue); } else if ('defaultValue' in val1) { mergedSchema[key] = mergedSchema[key].default(val1.defaultValue); } } else { let val = key in schema1 ? schema1[key] : schema2[key]; if (opts && opts.ignoreFirstDefaults && key in schema1) { val = deepUndefault(val); } mergedSchema[key] = val; } }); return v.object(mergedSchema); } else if (v1.human === 'object' && v2.human === 'object' && v1._props.elSchema && v2._props.elSchema) { const elSchema1 = v1._props.elSchema; const elSchema2 = v2._props.elSchema; const mergedElSchema = _mergeObjectOf(elSchema1, elSchema2, opts); return v.objects(v1._props.props, mergedElSchema); } throw new Error("can't merge"); }; const _objectsOf = (props, elSchema) => { const specifics = props && props.specifics || {}; const fn = obj => { const rs = Object.keys(obj).map(key => { const val = obj[key]; let warning; if (props && props.keys && props.keys.indexOf(key) === -1) { const customWarning = props.warner && props.warner(key); if (customWarning) { warning = customWarning; } else { const suggestions = bestSuggestions(key, props.keys); warning = `unrecognized key: ${key}; expected either of ${props.keys.join(', ')}`; if (suggestions.length > 0) { warning = warning + '; perhaps you meant ' + suggestions.join(', '); } } } const itemSchema = key in specifics ? specifics[key] : elSchema; const r = itemSchema(val); if (warning) { r.warning = r.warning ? r.warning + '; ' + warning : warning; } return _collItem(key, r); }); Object.keys(specifics).forEach(key => { if (key in obj) return; const ty = specifics[key]; if ('defaultValue' in ty) { obj[key] = _clone(ty.defaultValue); ty(obj[key]); } }); return _collResult(rs); }; fn._props = {props, elSchema}; return fn; }; v.noop = () => _result(true); v._string = isType('string'); v._bool = isType('boolean'); v._array = isType('array'); v._function = isType('function'); v._regexp = isType('regexp'); v._number = isType('number'); v._object = isType('object'); v.string = v._string; v.bool = v._bool; v.function = v._function; v.regexp = v._regexp; v.int = v._number; v.int.human = 'int'; v.array = elType => compose(v._array, _arrayOf(elType)); v.object = (schema, suggest) => compose(v._object, _objectOf(schema, suggest)); v.objects = (props, elSchema) => compose(v._object, _objectsOf(props, elSchema)); v.merge = _mergeObjectOf; v.either = function() { const types = [].slice.call(arguments); const humanTypes = types.map(type => type.human || '<>'); const human = `either of types ${JSON.stringify(humanTypes)}`; return defType(human, x => { const type = types.find(t => t(x).ok); if (type) { return type(x); } return _result(false, human, _type(x), x); }); }; v.enum = function() { const vals = [].slice.call(arguments); const human = `either of values ${JSON.stringify(vals)}`; return defType(human, x => { const check = vals.indexOf(x) !== -1; if (check) { return _result(true); } return _result(false, human, _type(x), x); }); }; v.deprecated = (elType, message) => { return defType(elType.human, x => { const r = elType(x); const warning = 'deprecated' + (message ? ': ' + message : ''); r.warning = r.warning ? r.warning + '; ' + warning : warning; return r; }); }; v.anymatch_ = v.either(v.string, v.regexp, v.function); v.anymatch = v.either(v.anymatch_, v.array(v.anymatch_)); module.exports = v;
/** * All methods related to the search */ jsBackend.search = { init: function () { var $synonymBox = $('input.synonymBox') // synonyms box if ($synonymBox.length > 0) { $synonymBox.multipleTextbox({ emptyMessage: jsBackend.locale.msg('NoSynonymsBox'), errorMessage: utils.string.ucfirst(jsBackend.locale.err('AddTextBeforeSubmitting')), addLabel: utils.string.ucfirst(jsBackend.locale.lbl('Add')), removeLabel: utils.string.ucfirst(jsBackend.locale.lbl('DeleteSynonym')) }) } // settings enable/disable $('#searchModules').find('input[type=checkbox]').on('change', function () { var $this = $(this) var $weightElement = $('#' + $this.attr('id') + 'Weight') if ($this.is(':checked')) { $weightElement.removeAttr('disabled').removeClass('disabled') return } $weightElement.prop('disabled', true).addClass('disabled') }) } } $(jsBackend.search.init)
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { cardClasses: true }; Object.defineProperty(exports, "default", { enumerable: true, get: function () { return _Card.default; } }); Object.defineProperty(exports, "cardClasses", { enumerable: true, get: function () { return _cardClasses.default; } }); var _Card = _interopRequireDefault(require("./Card")); var _cardClasses = _interopRequireWildcard(require("./cardClasses")); Object.keys(_cardClasses).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === _cardClasses[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _cardClasses[key]; } }); }); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
'use strict'; var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var SvgIcon = require('../../svg-icon'); var NavigationCheck = React.createClass({ displayName: 'NavigationCheck', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z' }) ); } }); module.exports = NavigationCheck;
app.directive('shortTimeAgo', function ($interval) { return { scope: { date: '@shortTimeAgo' }, link: function ($scope, element) { function shortTime() { angular.element(element).html(moment($scope.date).fromNow(true) .replace(/\b([smhdwmy])[a-z]+\b/, '$1') .replace(/an?/, '1') .replace('few', '') .replace(/\s/g, '')); } $interval(shortTime, 30000); // TODO make this slower if really old shortTime(); } }; });
UM.registerUI('link image video map formula',function(name){ var me = this, currentRange, $dialog, opt = { title: (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name), url: me.options.UMEDITOR_HOME_URL + 'dialogs/' + name + '/' + name + '.js' }; var $btn = $.eduibutton({ icon: name, title: this.getLang('labelMap')[name] || '' }); //加载模版数据 utils.loadFile(document,{ src: opt.url, tag: "script", type: "text/javascript", defer: "defer" },function(){ //调整数据 var data = UM.getWidgetData(name); if(!data) return; if(data.buttons){ var ok = data.buttons.ok; if(ok){ opt.oklabel = ok.label || me.getLang('ok'); if(ok.exec){ opt.okFn = function(){ return $.proxy(ok.exec,null,me,$dialog)() } } } var cancel = data.buttons.cancel; if(cancel){ opt.cancellabel = cancel.label || me.getLang('cancel'); if(cancel.exec){ opt.cancelFn = function(){ return $.proxy(cancel.exec,null,me,$dialog)() } } } } data.width && (opt.width = data.width); data.height && (opt.height = data.height); $dialog = $.eduimodal(opt); $dialog.attr('id', 'edui-dialog-' + name).addClass('edui-dialog-' + name) .find('.edui-modal-body').addClass('edui-dialog-' + name + '-body'); $dialog.edui().on('beforehide',function () { var rng = me.selection.getRange(); if (rng.equals(currentRange)) { rng.select() } }).on('beforeshow', function () { var $root = this.root(), win = null, offset = null; currentRange = me.selection.getRange(); if (!$root.parent()[0]) { me.$container.find('.edui-dialog-container').append($root); } //IE6下 特殊处理, 通过计算进行定位 if( $.IE6 ) { win = { width: $( window ).width(), height: $( window ).height() }; offset = $root.parents(".edui-toolbar")[0].getBoundingClientRect(); $root.css({ position: 'absolute', margin: 0, left: ( win.width - $root.width() ) / 2 - offset.left, top: 100 - offset.top }); } UM.setWidgetBody(name,$dialog,me); UM.setTopEditor(me); }).on('afterbackdrop',function(){ this.$backdrop.css('zIndex',me.getOpt('zIndex')+1).appendTo(me.$container.find('.edui-dialog-container')) $dialog.css('zIndex',me.getOpt('zIndex')+2) }).on('beforeok',function(){ try{ currentRange.select() }catch(e){} }).attachTo($btn) }); me.addListener('selectionchange', function () { var state = this.queryCommandState(name); $btn.edui().disabled(state == -1).active(state == 1) }); return $btn; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _utilities = require('./../utilities'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var create = (0, _utilities.iterateFunctionNodes)(function (context) { return function (functionNode) { _lodash2.default.forEach(functionNode.params, function (identifierNode) { var nodeType = _lodash2.default.get(identifierNode, 'type'); var isAssignmentPattern = nodeType === 'AssignmentPattern'; var hasTypeAnnotation = Boolean(_lodash2.default.get(identifierNode, 'typeAnnotation')); var leftAnnotated = Boolean(_lodash2.default.get(identifierNode, 'left.typeAnnotation')); if (isAssignmentPattern && hasTypeAnnotation && !leftAnnotated) { context.report({ data: { name: (0, _utilities.quoteName)((0, _utilities.getParameterName)(identifierNode, context)) }, message: '{{name}}parameter type annotation must be placed on left-hand side of assignment.', node: identifierNode }); } }); }; }); exports.default = { create, meta: { deprecated: true } }; module.exports = exports['default'];
module.exports={A:{A:{"2":"K C G E YB","1028":"B","1316":"A"},B:{"1":"D w Z I M H"},C:{"1":"0 1 3 5 6 7 8 X Y y a b c d e f L h i j k l m n o p q r s t u v z x","164":"WB AB F J K C G E A B D w Z I M H N O P Q UB OB","516":"R S T U V W"},D:{"1":"0 1 3 5 6 7 8 Y y a b c d e f L h i j k l m n o p q r s t u v z x BB IB DB FB ZB GB","33":"Q R S T U V W X","164":"F J K C G E A B D w Z I M H N O P"},E:{"1":"E A B MB NB g PB","33":"C G KB LB","164":"F J K HB CB JB"},F:{"1":"4 H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v","2":"9 E B D QB RB SB TB g VB","33":"I M"},G:{"1":"dB eB fB gB hB iB","33":"G bB cB","164":"2 CB XB EB aB"},H:{"1":"jB"},I:{"1":"BB oB pB","164":"2 AB F kB lB mB nB"},J:{"1":"A","164":"C"},K:{"1":"4 L","2":"9 A B D g"},L:{"1":"DB"},M:{"1":"x"},N:{"1":"B","292":"A"},O:{"1":"qB"},P:{"1":"F J rB"},Q:{"1":"sB"},R:{"1":"tB"}},B:4,C:"CSS Flexible Box Layout Module"};
var get = Ember.get, set = Ember.set; var rootState, stateName; module("unit/states - Flags for record states", { setup: function() { rootState = DS.RootState; } }); var isTrue = function(flag) { equal(get(rootState, stateName + "." + flag), true, stateName + "." + flag + " should be true"); }; var isFalse = function(flag) { equal(get(rootState, stateName + "." + flag), false, stateName + "." + flag + " should be false"); }; test("the empty state", function() { stateName = "empty"; isFalse("isLoading"); isFalse("isLoaded"); isFalse("isDirty"); isFalse("isSaving"); isFalse("isDeleted"); }); test("the loading state", function() { stateName = "loading"; isTrue("isLoading"); isFalse("isLoaded"); isFalse("isDirty"); isFalse("isSaving"); isFalse("isDeleted"); }); test("the loaded state", function() { stateName = "loaded"; isFalse("isLoading"); isTrue("isLoaded"); isFalse("isDirty"); isFalse("isSaving"); isFalse("isDeleted"); }); test("the updated state", function() { stateName = "loaded.updated"; isFalse("isLoading"); isTrue("isLoaded"); isTrue("isDirty"); isFalse("isSaving"); isFalse("isDeleted"); }); test("the saving state", function() { stateName = "loaded.updated.inFlight"; isFalse("isLoading"); isTrue("isLoaded"); isTrue("isDirty"); isTrue("isSaving"); isFalse("isDeleted"); }); test("the deleted state", function() { stateName = "deleted"; isFalse("isLoading"); isTrue("isLoaded"); isTrue("isDirty"); isFalse("isSaving"); isTrue("isDeleted"); }); test("the deleted.saving state", function() { stateName = "deleted.inFlight"; isFalse("isLoading"); isTrue("isLoaded"); isTrue("isDirty"); isTrue("isSaving"); isTrue("isDeleted"); }); test("the deleted.saved state", function() { stateName = "deleted.saved"; isFalse("isLoading"); isTrue("isLoaded"); isFalse("isDirty"); isFalse("isSaving"); isTrue("isDeleted"); });
$(function () { 'use strict'; var $image = $(window.createCropperImage()); $image.cropper({ built: function () { QUnit.test('methods#rotate', function (assert) { $image.cropper('rotate', 360); assert.equal($image.cropper('getImageData').rotate, 0); $image.cropper('rotate', 90); assert.equal($image.cropper('getImageData').rotate, 90); $image.cropper('rotate', -90); assert.equal($image.cropper('getImageData').rotate, 0); }); } }); });
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. 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. ****************************************************************************/ var TestAnimationsLayer = function() { this.onCCControlButtonIdleClicked = function(sender, controlEvent) { this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Idle", 0.3); }; this.onCCControlButtonWaveClicked = function(sender, controlEvent) { this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Wave", 0.3); }; this.onCCControlButtonJumpClicked = function(sender, controlEvent) { this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Jump", 0.3); }; this.onCCControlButtonFunkyClicked = function(sender, controlEvent) { this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Funky", 0.3); }; };
tinyMCE.addI18n('ru.xhtmlxtras_dlg',{ attribute_label_title:"\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A", attribute_label_id:"\u0418\u043C\u044F", attribute_label_class:"\u041A\u043B\u0430\u0441\u0441", attribute_label_style:"\u0421\u0442\u0438\u043B\u044C", attribute_label_cite:"\u0426\u0438\u0442\u0430\u0442\u0430", attribute_label_datetime:"\u0414\u0430\u0442\u0430/\u0412\u0440\u0435\u043C\u044F", attribute_label_langdir:"\u041D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0442\u0435\u043A\u0441\u0442\u0430", attribute_option_ltr:"\u0421\u043B\u0435\u0432\u0430 \u043D\u0430\u043F\u0440\u0430\u0432\u043E", attribute_option_rtl:"\u0421\u043F\u0440\u0430\u0432\u0430 \u043D\u0430\u043B\u0435\u0432\u043E", attribute_label_langcode:"\u042F\u0437\u044B\u043A", attribute_label_tabindex:"\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A", attribute_label_accesskey:"\u041A\u043B\u044E\u0447 \u0434\u043E\u0441\u0442\u0443\u043F\u0430", attribute_events_tab:"\u0421\u043E\u0431\u044B\u0442\u0438\u044F", attribute_attrib_tab:"\u0410\u0442\u0440\u0438\u0431\u0443\u0442\u044B", general_tab:"\u041E\u0431\u0449\u0435\u0435", attrib_tab:"\u0410\u0442\u0440\u0438\u0431\u0443\u0442\u044B", events_tab:"\u0421\u043E\u0431\u044B\u0442\u0438\u044F", fieldset_general_tab:"\u041E\u0431\u0449\u0438\u0435 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B", fieldset_attrib_tab:"\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", fieldset_events_tab:"\u0421\u043E\u0431\u044B\u0442\u0438\u044F \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", title_ins_element:"\u0417\u0430\u043C\u0435\u043D\u0430", title_del_element:"\u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435", title_acronym_element:"\u0410\u0431\u0431\u0440\u0435\u0432\u0438\u0430\u0446\u0438\u044F", title_abbr_element:"\u0421\u043E\u043A\u0440\u0430\u0449\u0435\u043D\u0438\u0435", title_cite_element:"\u0426\u0438\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435", remove:"\u0423\u0434\u0430\u043B\u0438\u0442\u044C", insert_date:"\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0443\u044E \u0434\u0430\u0442\u0443/\u0432\u0440\u0435\u043C\u044F", option_ltr:"\u0421\u043B\u0435\u0432\u0430 \u043D\u0430\u043F\u0440\u0430\u0432\u043E", option_rtl:"\u0421\u043F\u0440\u0430\u0432\u0430 \u043D\u0430\u043B\u0435\u0432\u043E", attribs_title:"\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430" });
/* flatpickr v4.2.4, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.ro = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Romanian = { weekdays: { shorthand: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sam"], longhand: [ "Duminică", "Luni", "Marți", "Miercuri", "Joi", "Vineri", "Sâmbătă", ], }, months: { shorthand: [ "Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Noi", "Dec", ], longhand: [ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie", ], }, firstDayOfWeek: 1, ordinal: function () { return ""; }, }; fp.l10ns.ro = Romanian; var ro = fp.l10ns; exports.Romanian = Romanian; exports['default'] = ro; Object.defineProperty(exports, '__esModule', { value: true }); })));